Compare commits

...
Author SHA1 Message Date
Dennis Kobert fb94d99807 Port the stale math-nodes and raster-nodes tests onto record wires 2026-08-11 09:54:48 +00:00
Dennis Kobert 264601c5f7 Return records from eval_batch through a RecordBatch view 2026-08-11 09:26:36 +00:00
Dennis Kobert 5db7e1816a Make Node::layout non-optional, defaulting to a shared empty layout 2026-08-11 09:20:02 +00:00
Dennis Kobert 5b02edfd9a Split the node macro codegen into classify, entries, and metadata modules 2026-08-10 16:15:31 +00:00
Dennis Kobert 7c0a4073e9 Select the eval tail form by class and dialect through an explicit Tail step 2026-08-10 15:57:58 +00:00
Dennis Kobert 275100eab0 Model the eval body as an EvalStep sequence with a structural stack discipline 2026-08-10 15:34:12 +00:00
Dennis Kobert 42cd2a4303 Resolve the dialect and input-role axes as node-model sum types 2026-08-10 15:21:59 +00:00
Dennis Kobert e4f81fc947 Drive the node macro from a single analyze pass, NodePlan, and shared NodeFields 2026-08-10 13:33:58 +00:00
Dennis Kobert 492cf18cb0 Flip the passthrough node onto record wires by dropping its dead lifetime 2026-08-10 13:33:58 +00:00
Dennis Kobert 05630bab6e Port the repeat node tests onto record-wire lazy inputs 2026-08-10 10:41:40 +00:00
Dennis Kobert a465948ad4 Always-spill records, retiring inline-16 and reclaiming read-out record frames 2026-08-10 10:29:22 +00:00
Dennis Kobert 63cf0151e2 Change stack return to standart sret semantics 2026-08-08 07:33:33 +00:00
Dennis Kobert 9c7a633d5b Adopt tuple attribute io and the carrier lowering, deleting the bridge adapters for record-only wires 2026-08-06 18:48:16 +00:00
Dennis Kobert 166241b0e8 Flip nested-generic nodes onto record wires by unifying row types against field types 2026-08-06 13:36:46 +00:00
Dennis Kobert ea49f3c2fc Delete the Ref wire type and its lend edge surface 2026-08-06 12:24:50 +00:00
Dennis Kobert 100f81c307 Retire the lend machinery and flip the clone node onto record wires 2026-08-06 11:57:18 +00:00
Dennis Kobert 886ff03ef2 Construct value nodes as native record sources 2026-08-06 10:24:44 +00:00
Dennis Kobert 7a1d1f3238 Define the frame memo through the record-opaque class over same-frame byte copies 2026-08-06 09:57:21 +00:00
Dennis Kobert 612afb7ebb Capture the input context snapshot on the monitor io record 2026-08-06 09:37:48 +00:00
Dennis Kobert daf3f25d21 Define the monitor through the record-opaque class and move introspection to element reads 2026-08-06 09:07:57 +00:00
Dennis Kobert a2de2a9c09 Add the record-opaque kernel class to the node macro and define memoize through it 2026-08-06 08:28:52 +00:00
Dennis Kobert 98be2b8c79 Carry erased element and re-park glue on layouts and collapse memoize to a generic record row 2026-08-06 08:01:19 +00:00
Dennis Kobert 83fda4f08c Update the core-types runtime tests to record wires 2026-08-06 06:46:28 +00:00
Dennis Kobert 20c6ba19d3 Flip async source nodes onto record wires by lifting their slot values 2026-08-05 23:54:42 +00:00
Dennis Kobert 7eeb7d84cd Flip poll kernels and derived-context lazy nodes onto record wires and land record roots at the host rim 2026-08-05 23:42:24 +00:00
Dennis Kobert 7ddc66adbe Flip lazy-input nodes onto record wires through the element lazy input 2026-08-05 23:12:43 +00:00
Dennis Kobert c20a243fc2 Flip lend-parameter nodes onto record wires and keep the clone adapter plain 2026-08-05 22:57:51 +00:00
Dennis Kobert 3eecc31bfd Flip generic value nodes onto record wires through phantom struct parameters 2026-08-05 22:39:25 +00:00
Dennis Kobert 7099f056dc Flip concrete value nodes onto record wires with bridge rows for every value type 2026-08-05 22:18:50 +00:00
Dennis Kobert 9680d34abf Carry record elements by the drop-glue rule and unify the lift and extract adapters 2026-08-05 22:17:50 +00:00
Dennis Kobert 592b2fbe32 Turn context modification into a generic record routing node and park droppable elements as arena references 2026-08-05 19:25:17 +00:00
Dennis Kobert 60f80682c5 Collapse duplicate proto nodes when assigning stable ids 2026-08-05 19:25:17 +00:00
Dennis Kobert 9fc4fcc7a0 Inline records of at most 16 bytes into the two-word RecordValue with layout-resolved storage 2026-08-05 17:23:09 +00:00
Dennis Kobert 7915800d73 Add per-field erased-read glue, the record monitor with introspection capture, and rename record constructors to new 2026-08-05 15:22:20 +00:00
Dennis Kobert c91be74a55 Add the Record wire type, record registry rows, lift and extract adapters, and executor stack reservation 2026-08-05 12:24:20 +00:00
Dennis Kobert abe2a565d1 Drop the list driver, make attribute values Copy over arena references, and land record-tier offset io on a per-thread record stack 2026-08-05 09:47:03 +00:00
Dennis Kobert 6154e4d219 Add the attribute census, node macro attribute io over list wires, and the rank-0 record tier 2026-08-04 22:05:02 +00:00
Dennis Kobert 62b7ccf40c Support bare reference parameters and lending outputs in the node macro and make the clone node the clone-out adapter 2026-08-03 18:29:16 +00:00
Dennis Kobert 9b45af854a Emit Ref wire types for lending rows and splice lend/clone_out adapters in the type checker 2026-08-03 16:33:27 +00:00
Dennis Kobert 562e6602eb Poll source tasks once at spawn and land inline completions in the first eval 2026-08-03 10:21:46 +00:00
Dennis Kobert 8fb18012cf Remove unuse allow dead code 2026-08-02 19:35:43 +02:00
Dennis Kobert 2b3161773f Propagate tokio runtime creation failure in graphene-cli 2026-08-02 19:29:33 +02:00
Dennis Kobert 167d733f02 Wire the async source runtimes into the hosts 2026-08-02 19:24:51 +02:00
Dennis Kobert ee499be31f Add test coverage for the repeat nodes 2026-08-02 16:18:07 +00:00
Dennis Kobert d385f3c69b Fix warnings 2026-08-02 15:06:11 +00:00
Dennis Kobert e372f78b7e Address pr review 2026-08-02 14:31:13 +00:00
Dennis Kobert 8686b2c891 Export the async-source flag from the macro and dispatch superseded type deltas in tests 2026-08-02 14:09:27 +00:00
Dennis Kobert e3aa32bc83 Fix wireing of async sources 2026-08-02 14:02:53 +02:00
Dennis Kobert 77d439ec35 Silence the dead-code warnings for groundwork the host wiring will use 2026-08-01 00:59:26 +02:00
Dennis Kobert c30054579f Adapt the cutover to the reviewed core-types API 2026-07-31 23:39:39 +02:00
Dennis Kobert 81a319430b Cut over to the graphene execution model 2026-07-31 23:19:42 +02:00
Dennis Kobert 1fb6fcb447 Remove the unused CtxSnapshot scope reconstruction 2026-07-31 22:55:53 +02:00
Dennis Kobert 32d244e700 Make the sources fields private and normalize them on every mutation 2026-07-31 22:00:22 +02:00
Dennis Kobert 0877f9d50e Park the arena during drop glue, guard filled batches, and normalize deserialized sources 2026-07-31 20:09:46 +02:00
Dennis Kobert 14c1dd0397 Guard the shared generation counter in tests and reject oversized batch ranges 2026-07-31 19:30:59 +02:00
Dennis Kobert daf7b3e7b9 Make arena generation exhaustion fallible with an unsafe counter rewind 2026-07-31 19:08:09 +02:00
Dennis Kobert bdf53070f2 Forward serialize through node wrappers and free abandoned frame table reservations 2026-07-31 18:12:53 +02:00
Dennis Kobert 0d0ec96709 Draw arena generations from a global counter so foreign handles never upgrade 2026-07-31 17:48:09 +02:00
Dennis Kobert 6feaf4ec9d Drop arena entries in reverse allocation order and require Send + Sync payloads 2026-07-31 17:21:11 +02:00
Dennis Kobert 5541769dc5 Fix frame table key aliasing and arena handle offset truncation 2026-07-31 16:46:20 +02:00
Dennis Kobert 1fccb112cb Add the core execution types, the borrowed context, and the seeded u64 fx hasher 2026-07-31 13:11:36 +00:00
Timon eb50be844b Remove now obsolete disable-registration special case from node macro (#4375) 2026-07-25 13:54:46 +00:00
Dennis Kobert 0f0f62c2e9 Enforce unwind safety on all public executor entry points (#4356) 2026-07-24 09:34:40 +00:00
Timon f5b1fee85f Fix node insertion crash caused by mismatched DefinitionIdentifier serialization (#4353) 2026-07-22 09:38:07 +00:00
Timon 6f8c4b2adb Desktop: Stop compiling the editor into the wasm wrapper (#4348)
* Make wasm wrapper not depend on editor on native

* Introduce pkg-native

* Fix tests

* Fix fmt

* Correct span and make cargo fmt work inside editor_commands block

* Review

* Fix lint
2026-07-18 10:33:38 +00:00
123 changed files with 14429 additions and 3930 deletions

No files matched your search

Generated
+6 -8
View File
@@ -2038,6 +2038,7 @@ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam", "glam",
"graphene-hash",
"graphene-resource", "graphene-resource",
"log", "log",
"raster-types", "raster-types",
@@ -2312,9 +2313,9 @@ dependencies = [
"graph-craft", "graph-craft",
"graphene-std", "graphene-std",
"graphite-editor", "graphite-editor",
"graphite-wasm-wrapper",
"image", "image",
"keyboard-types", "keyboard-types",
"ron",
"serde", "serde",
"serde_json", "serde_json",
"thiserror 2.0.18", "thiserror 2.0.18",
@@ -2374,6 +2375,7 @@ dependencies = [
name = "graphite-proc-macros" name = "graphite-proc-macros"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"convert_case",
"graphite-editor", "graphite-editor",
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -2385,17 +2387,17 @@ dependencies = [
name = "graphite-wasm-wrapper" name = "graphite-wasm-wrapper"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"bytemuck",
"graph-craft", "graph-craft",
"graphene-std", "graphene-std",
"graphite-editor", "graphite-editor",
"graphite-proc-macros",
"js-sys", "js-sys",
"log", "log",
"node-macro",
"ron",
"serde", "serde",
"serde-wasm-bindgen", "serde-wasm-bindgen",
"serde_bytes",
"serde_json", "serde_json",
"tsify",
"wasm-bindgen", "wasm-bindgen",
"wasm-bindgen-futures", "wasm-bindgen-futures",
"web-sys", "web-sys",
@@ -4878,15 +4880,11 @@ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam", "glam",
"graphene-core",
"graphic-types", "graphic-types",
"kurbo",
"log", "log",
"node-macro", "node-macro",
"raster-types", "raster-types",
"serde", "serde",
"tokio",
"vector-nodes",
"vector-types", "vector-types",
] ]
+6 -2
View File
@@ -14,13 +14,12 @@ use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEv
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId; use winit::window::WindowId;
use graphite_desktop_ui::{UiCommand, UiInstance};
use crate::dirs; use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler}; use crate::event::{AppEvent, AppEventScheduler};
use crate::persist; use crate::persist;
use crate::preferences; use crate::preferences;
use crate::render::{RenderError, RenderState}; use crate::render::{RenderError, RenderState};
use crate::ui::{UiCommand, UiInstance};
use crate::window::Window; use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences}; use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages}; use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
@@ -98,6 +97,11 @@ impl App {
}); });
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake); let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
let completion_render_sender = start_render_sender.clone();
DesktopWrapper::set_completion_notifier(move || {
let _ = completion_render_sender.try_send(());
});
Self { Self {
render_state: None, render_state: None,
wgpu_context, wgpu_context,
+2 -1
View File
@@ -1,9 +1,10 @@
use crate::ui::Cursor;
use crate::wrapper::NodeGraphExecutionResult; use crate::wrapper::NodeGraphExecutionResult;
use crate::wrapper::messages::DesktopWrapperMessage; use crate::wrapper::messages::DesktopWrapperMessage;
pub(crate) enum AppEvent { pub(crate) enum AppEvent {
UiUpdate(wgpu::Texture), UiUpdate(wgpu::Texture),
CursorChange(graphite_desktop_ui::Cursor), CursorChange(Cursor),
WebCommunicationInitialized, WebCommunicationInitialized,
DesktopWrapperMessage(DesktopWrapperMessage), DesktopWrapperMessage(DesktopWrapperMessage),
NodeGraphExecutionResult(NodeGraphExecutionResult), NodeGraphExecutionResult(NodeGraphExecutionResult),
+3 -2
View File
@@ -3,12 +3,13 @@ use crate::cli::Cli;
use crate::consts::APP_LOCK_FILE_NAME; use crate::consts::APP_LOCK_FILE_NAME;
use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt}; use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt};
use clap::Parser; use clap::Parser;
use graphite_desktop_ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
use std::io::Write; use std::io::Write;
use std::process::ExitCode; use std::process::ExitCode;
use tracing_subscriber::EnvFilter; use tracing_subscriber::EnvFilter;
use ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
use winit::event_loop::EventLoop; use winit::event_loop::EventLoop;
pub(crate) use graphite_desktop_ui as ui;
pub(crate) use graphite_desktop_wrapper as wrapper; pub(crate) use graphite_desktop_wrapper as wrapper;
mod app; mod app;
@@ -69,7 +70,7 @@ pub fn start() -> ExitCode {
} }
}; };
dirs::clear_dir(&graphite_desktop_ui::temp_dir_root()); dirs::clear_dir(&ui::temp_dir_root());
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory // TODO: Eventually remove this cleanup code for the old "browser" CEF directory
dirs::delete_old_cef_browser_directory(); dirs::delete_old_cef_browser_directory();
+1 -1
View File
@@ -228,7 +228,7 @@ impl RenderState {
return; return;
}; };
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height()); let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None)); let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
match result { match result {
Ok(texture) => { Ok(texture) => {
self.overlays_texture = Some(texture.into()); self.overlays_texture = Some(texture.into());
+1 -1
View File
@@ -1,8 +1,8 @@
use crate::consts::APP_NAME; use crate::consts::APP_NAME;
use crate::event::AppEventScheduler; use crate::event::AppEventScheduler;
use crate::ui::Cursor;
use crate::wrapper::messages::MenuItem; use crate::wrapper::messages::MenuItem;
use crate::wrapper::{WgpuInstance, WgpuSurface}; use crate::wrapper::{WgpuInstance, WgpuSurface};
use graphite_desktop_ui::Cursor;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use winit::cursor::{CustomCursor, CustomCursorSource}; use winit::cursor::{CustomCursor, CustomCursorSource};
+1 -1
View File
@@ -14,6 +14,7 @@ gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
[dependencies] [dependencies]
# Local dependencies # Local dependencies
graphite-editor = { workspace = true } graphite-editor = { workspace = true }
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
graphene-std = { workspace = true } graphene-std = { workspace = true }
graph-craft = { workspace = true } graph-craft = { workspace = true }
wgpu-executor = { workspace = true } wgpu-executor = { workspace = true }
@@ -22,7 +23,6 @@ wgpu = { workspace = true }
thiserror = { workspace = true } thiserror = { workspace = true }
tracing = { workspace = true } tracing = { workspace = true }
dirs = { workspace = true } dirs = { workspace = true }
ron = { workspace = true}
vello = { workspace = true } vello = { workspace = true }
image = { workspace = true } image = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
+10 -15
View File
@@ -1,7 +1,9 @@
use graph_craft::application_io::PlatformApplicationIo; use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage; use graph_craft::application_io::resource::ResourceStorage;
use graphite_editor::application::{Editor, Environment, Host, Platform}; use graphite_editor::application::{Editor, Environment, Host, Platform};
use graphite_editor::messages::prelude::{FrontendMessage, Message, Wake}; use graphite_editor::messages::frontend::FrontendMessage;
use graphite_editor::messages::prelude::Wake;
use message_dispatcher::DesktopWrapperMessageDispatcher; use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage}; use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
use std::sync::Arc; use std::sync::Arc;
@@ -50,6 +52,10 @@ impl DesktopWrapper {
executor.execute() executor.execute()
} }
pub fn set_completion_notifier(notifier: impl Fn() + Send + Sync + 'static) {
graphite_editor::node_graph_executor::set_completion_notifier(Arc::new(notifier));
}
pub async fn execute_node_graph() -> NodeGraphExecutionResult { pub async fn execute_node_graph() -> NodeGraphExecutionResult {
let result = graphite_editor::node_graph_executor::run_node_graph().await; let result = graphite_editor::node_graph_executor::run_node_graph().await;
match result { match result {
@@ -65,21 +71,10 @@ pub enum NodeGraphExecutionResult {
} }
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> { pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
if let Ok(string) = std::str::from_utf8(data) { let message = graphite_wasm_wrapper::native_communication::decode_editor_command(data)?;
if let Ok(message) = ron::de::from_str::<Message>(string) { Some(DesktopWrapperMessage::FromWeb(message.into()))
Some(DesktopWrapperMessage::FromWeb(message.into()))
} else {
None
}
} else {
None
}
} }
pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> { pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> {
if let Ok(serialized) = ron::ser::to_string(&messages) { graphite_wasm_wrapper::native_communication::encode_frontend_messages(messages)
Some(serialized.into_bytes())
} else {
None
}
} }
+1 -1
View File
@@ -45,7 +45,7 @@ impl<'de> Deserialize<'de> for ResourceEntry {
} }
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?; let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
sources.sort_by(|(a, _), (b, _)| a.cmp(b)); sources.sort_by_key(|(a, _)| *a);
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| { sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW. // `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
if later_key != kept_key { if later_key != kept_key {
@@ -246,10 +246,10 @@ fn test_nested_network_flattening() {
#[test] #[test]
fn test_metadata_preservation() { fn test_metadata_preservation() {
// Create a network with nodes that have non-default metadata // Create a network with nodes that have non-default metadata
let context_features = ContextDependencies { let context_features = ContextDependencies::new(
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME, core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
..Default::default() core_types::context::ContextFeatures::empty(),
}; );
let network = NodeNetwork { let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)], exports: vec![NodeInput::node(NodeId(1), 0)],
@@ -1,7 +1,7 @@
use super::IconName; use super::IconName;
use super::utility_types::{MouseCursorIcon, PersistedState}; use super::utility_types::{MouseCursorIcon, PersistedState};
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform; use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage}; use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, RasterizedImage};
use crate::messages::input_mapper::utility_types::misc::ActionShortcut; use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{ use crate::messages::portfolio::document::node_graph::utility_types::{
@@ -14,7 +14,6 @@ use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary; use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::raster::Image;
use graphene_std::vector::style::FillChoiceUI; use graphene_std::vector::style::FillChoiceUI;
use std::path::PathBuf; use std::path::PathBuf;
@@ -235,7 +234,7 @@ pub enum FrontendMessage {
svg: String, svg: String,
}, },
UpdateImageData { UpdateImageData {
image_data: Vec<(u64, Image<SRGBA8>)>, image_data: Vec<RasterizedImage>,
}, },
UpdateDocumentLayerDetails { UpdateDocumentLayerDetails {
data: LayerPanelEntry, data: LayerPanelEntry,
@@ -82,3 +82,12 @@ pub struct EyedropperPreviewImage {
pub width: u32, pub width: u32,
pub height: u32, pub height: u32,
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
pub struct RasterizedImage {
pub id: u64,
pub width: u32,
pub height: u32,
pub pixels: serde_bytes::ByteBuf,
}
@@ -1,5 +1,6 @@
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup; use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::vector::style::FillChoiceUI; use graphene_std::vector::style::FillChoiceUI;
@@ -291,7 +292,11 @@ impl LayoutMessageHandler {
responses.add(callback_message); responses.add(callback_message);
} }
WidgetValueAction::Update => { WidgetValueAction::Update => {
let callback_message = (node_type_input.on_update.callback)(&value.into()); let Value::String(ref node_type) = value else {
error!("NodeCatalog update was not of type: String, found {value:?}");
return;
};
let callback_message = (node_type_input.on_update.callback)(&DefinitionIdentifier::from_serialized(node_type));
responses.add(callback_message); responses.add(callback_message);
} }
}, },
@@ -10,11 +10,10 @@ use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::gradient::GradientStops; use graphene_std::gradient::GradientStops;
use graphene_std::list::List; use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster_types::{CPU, GPU, Raster}; use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::vector::Vector; use graphene_std::vector::Vector;
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType}; use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
use graphene_std::{Artboard, Color, Context, Graphic}; use graphene_std::{Artboard, Color, Graphic};
use std::any::Any; use std::any::Any;
use std::sync::Arc; use std::sync::Arc;
@@ -167,8 +166,8 @@ macro_rules! generate_layout_downcast {
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => { ($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
if false { None } if false { None }
$( $(
else if let Some(io) = $introspected_data.downcast_ref::<IORecord<Context, $ty>>() { else if let Some(element) = $introspected_data.downcast_ref::<$ty>() {
Some(io.output.layout_with_breadcrumb($data)) Some(element.layout_with_breadcrumb($data))
} }
)* )*
else { None } else { None }
@@ -178,8 +177,8 @@ macro_rules! generate_layout_downcast {
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> { fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
// `List<NodeId>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a // `List<NodeId>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
// `List` where each item's NodeId resolves against the prefix made up of the items above it. // `List` where each item's NodeId resolves against the prefix made up of the items above it.
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<NodeId>>>() { if let Some(list) = introspected_data.downcast_ref::<List<NodeId>>() {
return Some(table_node_id_path_layout_with_breadcrumb(&io.output, data)); return Some(table_node_id_path_layout_with_breadcrumb(list, data));
} }
generate_layout_downcast!(introspected_data, data, [ generate_layout_downcast!(introspected_data, data, [
List<Artboard>, List<Artboard>,
@@ -23,7 +23,6 @@ use graphene_std::raster_types::{CPU, Raster};
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
use graphene_std::vector::Vector; use graphene_std::vector::Vector;
use graphene_std::*; use graphene_std::*;
use serde_json::Value;
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
pub struct NodePropertiesContext<'a> { pub struct NodePropertiesContext<'a> {
@@ -89,12 +88,8 @@ impl DefinitionIdentifier {
DefinitionIdentifier::Network(data) => format!("NETWORK:{}", data), DefinitionIdentifier::Network(data) => format!("NETWORK:{}", data),
} }
} }
}
impl From<Value> for DefinitionIdentifier {
fn from(value: Value) -> Self {
let s = value.as_str().expect("DefinitionIdentifier value must be a string");
pub fn from_serialized(s: &str) -> Self {
match s.split_once(':') { match s.split_once(':') {
Some(("PROTONODE", data)) => DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::with_owned_string(data.to_string())), Some(("PROTONODE", data)) => DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::with_owned_string(data.to_string())),
Some(("NETWORK", data)) => DefinitionIdentifier::Network(data.to_string()), Some(("NETWORK", data)) => DefinitionIdentifier::Network(data.to_string()),
@@ -924,7 +919,12 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
exports: vec![NodeInput::node(NodeId(1), 0)], exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [ nodes: [
DocumentNode { DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(concrete!(String), 1)], inputs: vec![
NodeInput::value(TaggedValue::None, false),
NodeInput::import(concrete!(String), 1),
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
],
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
..Default::default() ..Default::default()
}, },
@@ -999,7 +999,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(concrete!(Footprint), 1), NodeInput::node(NodeId(1), 0)], inputs: vec![
NodeInput::import(generic!(T), 0),
NodeInput::import(concrete!(Footprint), 1),
NodeInput::node(NodeId(1), 0),
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
],
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
..Default::default() ..Default::default()
}, },
@@ -29,7 +29,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`. // fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY; let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
let node_registry = NODE_REGISTRY.lock().unwrap(); let node_registry = NODE_REGISTRY.lock().unwrap();
let empty_implementations: Vec<(NodeConstructor, NodeIOTypes)> = Vec::new(); let empty_implementations: Vec<RegistryEntry> = Vec::new();
let context_type = concrete!(Context); let context_type = concrete!(Context);
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() { for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
let identifier = DefinitionIdentifier::ProtoNode(id.clone()); let identifier = DefinitionIdentifier::ProtoNode(id.clone());
@@ -48,12 +48,12 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
let implementations = node_registry.get(id).unwrap_or(&empty_implementations); let implementations = node_registry.get(id).unwrap_or(&empty_implementations);
let first_node_io = implementations.first().map(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() }); let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
let call_arguments: Vec<&Type> = if !implementations.is_empty() { let call_arguments: Vec<&Type> = if !implementations.is_empty() {
implementations.iter().map(|(_, io)| &io.call_argument).collect() implementations.iter().map(|entry| &entry.io.call_argument).collect()
} else if let Some(impls) = extended_node_registry.get(id) { } else if let Some(impls) = extended_node_registry.get(id) {
impls.keys().map(|io| &io.call_argument).collect() impls.iter().map(|entry| &entry.io.call_argument).collect()
} else { } else {
Vec::new() Vec::new()
}; };
@@ -323,6 +323,7 @@ pub(crate) fn property_from_type(
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(), Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context), Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context), Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Record(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
}; };
extra_widgets.push(widgets); extra_widgets.push(widgets);
@@ -2359,7 +2360,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
return Vec::new(); return Vec::new();
}; };
let mut input_types = implementations.keys().filter_map(|item| item.inputs.get(input_index)).collect::<Vec<_>>(); let mut input_types = implementations.iter().filter_map(|entry| entry.io.inputs.get(input_index)).collect::<Vec<_>>();
input_types.sort_by_key(|ty| ty.type_name()); input_types.sort_by_key(|ty| ty.type_name());
let input_type = input_types.first().cloned(); let input_type = input_types.first().cloned();
@@ -253,8 +253,9 @@ impl NodeNetworkInterface {
}; };
let number_of_inputs = self.number_of_inputs(node_id, network_path); let number_of_inputs = self.number_of_inputs(node_id, network_path);
implementations implementations
.keys() .iter()
.filter_map(|node_io| { .filter_map(|entry| {
let node_io = &entry.io;
// Check if this NodeIOTypes implementation is valid for the other inputs // Check if this NodeIOTypes implementation is valid for the other inputs
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| { let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path); let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
@@ -293,8 +294,9 @@ impl NodeNetworkInterface {
let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path); let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path);
implementations implementations
.keys() .iter()
.filter_map(|node_io| { .filter_map(|entry| {
let node_io = &entry.io;
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) { if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
return None; return None;
} }
@@ -323,7 +325,7 @@ impl NodeNetworkInterface {
log::error!("Protonode {render_node:?} not found in registry"); log::error!("Protonode {render_node:?} not found in registry");
return Vec::new(); return Vec::new();
}; };
implementations.keys().map(|types| types.inputs[1].clone()).collect() implementations.iter().map(|entry| entry.io.inputs[1].clone()).collect()
} }
} }
} }
@@ -2406,7 +2406,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
&& let Some(reference) = document.network_interface.reference(node_id, network_path).clone() && let Some(reference) = document.network_interface.reference(node_id, network_path).clone()
&& let Some(node_definition) = resolve_document_node_type(&reference) && let Some(node_definition) = resolve_document_node_type(&reference)
{ {
let context_features = node_definition.node_template.document_node.context_features; let context_features = node_definition.node_template.document_node.context_features.clone();
document.network_interface.set_context_features(node_id, network_path, context_features); document.network_interface.set_context_features(node_id, network_path, context_features);
} }
+34 -40
View File
@@ -1,4 +1,4 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType}; use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage};
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
@@ -10,12 +10,11 @@ use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderC
use graphene_std::bounds::RenderBoundingBox; use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::list::List; use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster::{CPU, Raster}; use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box}; use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, graphic_types}; use graphene_std::vector::{Vector, graphic_types};
use graphene_std::{ATTR_TRANSFORM, Context, Graphic, NodeInputDecleration}; use graphene_std::{ATTR_TRANSFORM, Graphic, NodeInputDecleration};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta; use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any; use std::any::Any;
use std::sync::Arc; use std::sync::Arc;
@@ -26,7 +25,7 @@ pub use runtime_io::NodeRuntimeIO;
mod runtime; mod runtime;
pub use runtime::*; pub use runtime::*;
#[derive(Debug, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExecutionRequest { pub struct ExecutionRequest {
execution_id: u64, execution_id: u64,
render_config: RenderConfig, render_config: RenderConfig,
@@ -59,6 +58,9 @@ pub struct NodeGraphExecutor {
runtime_io: NodeRuntimeIO, runtime_io: NodeRuntimeIO,
current_execution_id: u64, current_execution_id: u64,
futures: VecDeque<(u64, ExecutionContext)>, futures: VecDeque<(u64, ExecutionContext)>,
/// The most recently consumed plain render execution, kept so a runtime-replayed response with the same id
/// (sent after an async source completion) finds its context again.
last_execution_context: Option<(u64, ExecutionContext)>,
node_graph_hash: u64, node_graph_hash: u64,
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected. /// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
/// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in, /// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in,
@@ -108,6 +110,7 @@ impl NodeGraphExecutor {
let node_executor = Self { let node_executor = Self {
futures: Default::default(), futures: Default::default(),
runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver), runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver),
last_execution_context: None,
node_graph_hash: 0, node_graph_hash: 0,
current_execution_id: 0, current_execution_id: 0,
previous_node_to_inspect: Vec::new(), previous_node_to_inspect: Vec::new(),
@@ -375,10 +378,22 @@ impl NodeGraphExecutor {
} }
} }
let Some((queued_execution_id, execution_context)) = self.futures.pop_front() else { let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
panic!("InvalidGenerationId") let (_, execution_context) = self.futures.pop_front().expect("front was just matched");
self.last_execution_context = Some((execution_id, execution_context.clone()));
execution_context
} else {
// A runtime-replayed response re-uses an already consumed id; only plain renders may re-apply.
match &self.last_execution_context {
Some((last_execution_id, execution_context)) if *last_execution_id == execution_id => {
if execution_context.export_config.is_some() || execution_context.measure_fill.is_some() {
continue;
}
execution_context.clone()
}
_ => panic!("InvalidGenerationId"),
}
}; };
assert_eq!(queued_execution_id, execution_id, "Missmatch in execution id");
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
// Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork. // Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork.
@@ -660,19 +675,15 @@ impl NodeGraphExecutor {
match render_output.data { match render_output.data {
RenderOutputType::Svg { svg, image_data } => { RenderOutputType::Svg { svg, image_data } => {
// Convert each linear-light `Image<Color>` into the JS-boundary `Image<SRGBA8>` form (gamma byte channels) before dispatching. // Convert each linear-light `Image<Color>` into gamma sRGB bytes (the DOM boundary form) before dispatching.
let rgba8_bytes = |&color: &_| <[u8; 4]>::from(SRGBA8::from(color));
let image_data = image_data let image_data = image_data
.into_iter() .into_iter()
.map(|(id, image)| { .map(|(id, image)| RasterizedImage {
( id,
id, width: image.width,
graphene_std::raster::Image { height: image.height,
width: image.width, pixels: image.data.iter().flat_map(rgba8_bytes).collect::<Vec<u8>>().into(),
height: image.height,
data: image.data.iter().map(|&c| SRGBA8::from(c)).collect(),
base64_string: image.base64_string,
},
)
}) })
.collect(); .collect();
responses.add(FrontendMessage::UpdateImageData { image_data }); responses.add(FrontendMessage::UpdateImageData { image_data });
@@ -888,18 +899,9 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
} }
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Extract a monitor node's recorded output, trying each context type the runtime may have evaluated it under. /// Extract a monitor node's captured output element.
fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> { fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> {
if let Some(io) = data.downcast_ref::<IORecord<(), T>>() { data.downcast_ref::<T>().cloned()
return Some(io.output.clone());
}
if let Some(io) = data.downcast_ref::<IORecord<Footprint, T>>() {
return Some(io.output.clone());
}
if let Some(io) = data.downcast_ref::<IORecord<Context, T>>() {
return Some(io.output.clone());
}
None
} }
// Re-export for usage by tests in other modules // Re-export for usage by tests in other modules
@@ -915,9 +917,7 @@ mod test {
use crate::test_utils::test_prelude::{self, NodeGraphLayer}; use crate::test_utils::test_prelude::{self, NodeGraphLayer};
use graph_craft::ProtoNodeIdentifier; use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::NodeNetwork; use graph_craft::document::NodeNetwork;
use graphene_std::Context;
use graphene_std::NodeInputDecleration; use graphene_std::NodeInputDecleration;
use graphene_std::memo::IORecord;
use test_prelude::LayerNodeIdentifier; use test_prelude::LayerNodeIdentifier;
/// Stores all of the monitor nodes that have been attached to a graph /// Stores all of the monitor nodes that have been attached to a graph
@@ -978,17 +978,11 @@ mod test {
where where
Input::Result: Send + Sync + Clone + 'static, Input::Result: Send + Sync + Clone + 'static,
{ {
// This is quite inflexible since it only allows the footprint as inputs. let element = dynamic.downcast_ref::<Input::Result>().cloned();
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Input::Result>>() { if element.is_none() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Input::Result>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Input::Result>>() {
Some(x.output.clone())
} else {
warn!("cannot downcast type for introspection"); warn!("cannot downcast type for introspection");
None
} }
element
} }
/// Grab all of the values of the input every time it occurs in the graph. /// Grab all of the values of the input every time it occurs in the graph.
+126 -40
View File
@@ -3,25 +3,25 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry; use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::concrete;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{NodeId, NodeNetwork}; use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::Compiler; use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::GraphErrors; use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture}; use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
use graphene_std::bounds::RenderBoundingBox; use graphene_std::bounds::RenderBoundingBox;
use graphene_std::core_types::gpoll::GPoll;
use graphene_std::list::List; use graphene_std::list::List;
use graphene_std::memo::IORecord; use graphene_std::ops::ConvertAsync;
use graphene_std::ops::Convert;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle}; use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster; use graphene_std::raster_types::Raster;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment}; use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
use graphene_std::transform::RenderQuality; use graphene_std::transform::RenderQuality;
use graphene_std::vector::Vector; use graphene_std::vector::Vector;
use graphene_std::vector::style::RenderMode; use graphene_std::vector::style::RenderMode;
use graphene_std::{Artboard, Context, Graphic}; use graphene_std::{Artboard, Graphic};
use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta}; use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope; use interpreted_executor::util::wrap_network_in_scope;
use spin::Mutex; use spin::Mutex;
use std::sync::Arc; use std::sync::Arc;
@@ -40,6 +40,9 @@ pub struct NodeRuntime {
editor_preferences: EditorPreferences, editor_preferences: EditorPreferences,
old_graph: Option<NodeNetwork>, old_graph: Option<NodeNetwork>,
update_thumbnails: bool, update_thumbnails: bool,
graph_runtime: Arc<DynGraphRuntime>,
/// The last plain render request, replayed when an async source completion marks the graph dirty.
last_render: Option<ExecutionRequest>,
editor_api: Arc<PlatformEditorApi>, editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry, resources: ResourceRegistry,
@@ -119,20 +122,86 @@ impl NodeGraphUpdateSender for InternalNodeGraphUpdateSender {
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar // TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
pub static NODE_RUNTIME: once_cell::sync::Lazy<Mutex<Option<NodeRuntime>>> = once_cell::sync::Lazy::new(|| Mutex::new(None)); pub static NODE_RUNTIME: once_cell::sync::Lazy<Mutex<Option<NodeRuntime>>> = once_cell::sync::Lazy::new(|| Mutex::new(None));
#[cfg(not(target_family = "wasm"))]
pub struct TokioSpawner(Option<tokio::runtime::Runtime>);
#[cfg(not(target_family = "wasm"))]
impl TokioSpawner {
pub fn new() -> Self {
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
}
}
#[cfg(not(target_family = "wasm"))]
impl Default for TokioSpawner {
fn default() -> Self {
Self::new()
}
}
#[cfg(not(target_family = "wasm"))]
impl Spawner for TokioSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
let runtime = self.0.as_ref().expect("runtime lives until drop");
let _guard = runtime.enter();
if poll_once(&mut task) {
return true;
}
runtime.spawn(task);
false
}
}
/// Dropping a tokio runtime blocks on its tasks, which panics inside an async context; the tests drop
/// [`NodeRuntime`] from one, so shut down in the background instead.
#[cfg(not(target_family = "wasm"))]
impl Drop for TokioSpawner {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
}
}
}
#[cfg(target_family = "wasm")]
pub struct WasmSpawner;
#[cfg(target_family = "wasm")]
impl Spawner for WasmSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
wasm_bindgen_futures::spawn_local(task);
false
}
}
impl NodeRuntime { impl NodeRuntime {
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self { pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
#[cfg(not(target_family = "wasm"))]
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
#[cfg(target_family = "wasm")]
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(spawner));
let mut executor = DynamicExecutor::default();
executor.set_runtime(Arc::clone(&graph_runtime));
Self { Self {
executor: DynamicExecutor::default(), executor,
receiver, receiver,
sender: InternalNodeGraphUpdateSender(sender.clone()), sender: InternalNodeGraphUpdateSender(sender.clone()),
editor_preferences: EditorPreferences::default(), editor_preferences: EditorPreferences::default(),
old_graph: None, old_graph: None,
resources: ResourceRegistry::default(), resources: ResourceRegistry::default(),
update_thumbnails: true, update_thumbnails: true,
graph_runtime: Arc::clone(&graph_runtime),
last_render: None,
editor_api: PlatformEditorApi { editor_api: PlatformEditorApi {
editor_preferences: Box::new(EditorPreferences::default()), editor_preferences: Box::new(EditorPreferences::default()),
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)), node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
runtime: RuntimeHandle(graph_runtime),
#[cfg(not(test))] #[cfg(not(test))]
application_io: None, application_io: None,
@@ -157,6 +226,11 @@ impl NodeRuntime {
} }
} }
#[cfg(test)]
pub fn take_dirty(&self) -> bool {
self.executor.take_dirty()
}
pub async fn run(&mut self) -> Option<Texture> { pub async fn run(&mut self) -> Option<Texture> {
let mut preferences = None; let mut preferences = None;
let mut graph = None; let mut graph = None;
@@ -173,6 +247,9 @@ impl NodeRuntime {
} }
let for_export = execution_request.render_config.for_export; let for_export = execution_request.render_config.for_export;
if !for_export {
self.last_render = Some(execution_request.clone());
}
execution = Some(request); execution = Some(request);
@@ -193,6 +270,10 @@ impl NodeRuntime {
eyedropper.render_config.pointer = execution.render_config.pointer; eyedropper.render_config.pointer = execution.render_config.pointer;
} }
if self.executor.take_dirty() && execution.is_none() {
execution = self.last_render.clone().map(GraphRuntimeRequest::ExecutionRequest);
}
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten(); let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
for request in requests { for request in requests {
@@ -203,11 +284,12 @@ impl NodeRuntime {
application_io: self.editor_api.application_io.clone(), application_io: self.editor_api.application_io.clone(),
node_graph_message_sender: Box::new(self.sender.clone()), node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(preferences), editor_preferences: Box::new(preferences),
runtime: self.editor_api.runtime.clone(),
} }
.into(); .into();
if let Some(graph) = self.old_graph.clone() { if let Some(graph) = self.old_graph.clone() {
// We ignore this result as compilation errors should have been reported in an earlier iteration // We ignore this result as compilation errors should have been reported in an earlier iteration
let _ = self.update_network(graph).await; let _ = self.update_network(graph);
} }
} }
GraphRuntimeRequest::GraphUpdate(GraphUpdate { GraphRuntimeRequest::GraphUpdate(GraphUpdate {
@@ -222,7 +304,7 @@ impl NodeRuntime {
self.resources = resources; self.resources = resources;
self.node_graph_errors.clear(); self.node_graph_errors.clear();
let result = self.update_network(network).await; let result = self.update_network(network);
let node_graph_errors = self.node_graph_errors.clone(); let node_graph_errors = self.node_graph_errors.clone();
self.update_thumbnails = true; self.update_thumbnails = true;
@@ -237,7 +319,7 @@ impl NodeRuntime {
render_config.export_format = ExportFormat::Svg; render_config.export_format = ExportFormat::Svg;
} }
let result = self.execute_network(render_config).await; let result = self.execute_network(render_config);
let mut responses = VecDeque::new(); let mut responses = VecDeque::new();
// TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes // TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes
if !render_config.for_eyedropper { if !render_config.for_eyedropper {
@@ -258,10 +340,10 @@ impl NodeRuntime {
.application_io .application_io
.as_ref() .as_ref()
.unwrap() .unwrap()
.gpu_executor() .gpu_executor_arc()
.expect("GPU executor should be available when we receive a texture"); .expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await; let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
let (data, width, height) = raster_cpu.to_flat_u8(); let (data, width, height) = raster_cpu.to_flat_u8();
@@ -282,10 +364,10 @@ impl NodeRuntime {
.application_io .application_io
.as_ref() .as_ref()
.unwrap() .unwrap()
.gpu_executor() .gpu_executor_arc()
.expect("GPU executor should be available when we receive a texture"); .expect("GPU executor should be available when we receive a texture");
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await; let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
self.sender.send_eyedropper_preview(raster_cpu); self.sender.send_eyedropper_preview(raster_cpu);
continue; continue;
@@ -345,7 +427,7 @@ impl NodeRuntime {
None None
} }
async fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> { fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone()); let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) { if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
@@ -368,20 +450,24 @@ impl NodeRuntime {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?"); assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
self.executor.update(proto_network).await.map_err(|(types, e)| { self.executor.update(proto_network).map_err(|(types, e)| {
self.node_graph_errors.clone_from(&e); self.node_graph_errors.clone_from(&e);
(types, format!("{e:?}")) (types, format!("{e:?}"))
}) })
} }
async fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> { fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
use graph_craft::graphene_compiler::Executor; use graph_craft::graphene_compiler::Executor;
match self.executor.input_type() { match (&self.executor).execute(render_config).map_err(|e| e.to_string())? {
Some(t) if t == concrete!(RenderConfig) => (&self.executor).execute(render_config).await.map_err(|e| e.to_string()), GPoll::Final(value) | GPoll::Partial(value) => Ok(value),
Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()), GPoll::Fallback(boxed) => {
Some(t) => Err(format!("Invalid input type {t:?}")), let (value, error) = *boxed;
_ => Err(format!("No input type:\n{:?}", self.node_graph_errors)), error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
Ok(value)
}
GPoll::Pending => Err("Node graph evaluation is pending".to_string()),
GPoll::Error(error) => Err(format!("Node graph evaluation failed: {error:?}")),
} }
} }
@@ -415,30 +501,30 @@ impl NodeRuntime {
}; };
// Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content) // Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Graphic>>>() { if let Some(list) = introspected_data.downcast_ref::<List<Graphic>>() {
if update_thumbnails { if update_thumbnails {
let bounds = graphene_std::renderer::graphic_list_bounding_box(&io.output, DAffine2::IDENTITY); let bounds = graphene_std::renderer::graphic_list_bounding_box(list, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses) Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
} }
} }
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer // 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 // clips content to those rectangles so anything outside isn't visible
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Artboard>>>() { else if let Some(list) = introspected_data.downcast_ref::<List<Artboard>>() {
if update_thumbnails { if update_thumbnails {
let bounds = artboard_clip_bounds(&io.output); let bounds = artboard_clip_bounds(list);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses) Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
} }
} }
// Vector list: vector modifications // Vector list: vector modifications
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Vector>>>() { else if let Some(list) = introspected_data.downcast_ref::<List<Vector>>() {
// Insert the vector modify // Insert the vector modify
self.vector_modify.insert(parent_network_node_id, io.output.element(0).cloned().unwrap_or_default()); self.vector_modify.insert(parent_network_node_id, list.element(0).cloned().unwrap_or_default());
} }
// String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`) // String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<String>>>() { else if let Some(list) = introspected_data.downcast_ref::<List<String>>() {
if update_thumbnails { if update_thumbnails {
let bounds = graphene_std::renderer::text_list_bounding_box(&io.output, DAffine2::IDENTITY); let bounds = graphene_std::renderer::text_list_bounding_box(list, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses) Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
} }
} }
// Other // Other
@@ -544,14 +630,6 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
[center - half, center + half] [center - half, center + half]
} }
pub async fn introspect_node(path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
let runtime = NODE_RUNTIME.lock();
if let Some(ref mut runtime) = runtime.as_ref() {
return runtime.executor.introspect(path);
}
Err(IntrospectError::RuntimeNotReady)
}
pub async fn run_node_graph() -> (bool, Option<Texture>) { pub async fn run_node_graph() -> (bool, Option<Texture>) {
let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) }; let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) };
if let Some(ref mut runtime) = runtime.as_mut() { if let Some(ref mut runtime) = runtime.as_mut() {
@@ -571,12 +649,20 @@ pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) {
} }
} }
pub fn set_completion_notifier(notifier: Arc<DynNotifier>) {
let node_runtime = NODE_RUNTIME.lock();
if let Some(node_runtime) = &*node_runtime {
node_runtime.graph_runtime.set_notifier(notifier);
}
}
impl NodeRuntime { impl NodeRuntime {
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) { pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
self.editor_api = PlatformEditorApi { self.editor_api = PlatformEditorApi {
application_io: Some(application_io.into()), application_io: Some(application_io.into()),
node_graph_message_sender: Box::new(self.sender.clone()), node_graph_message_sender: Box::new(self.sender.clone()),
editor_preferences: Box::new(self.editor_preferences.clone()), editor_preferences: Box::new(self.editor_preferences.clone()),
runtime: self.editor_api.runtime.clone(),
} }
.into(); .into();
} }
+21
View File
@@ -53,6 +53,27 @@ impl EditorTestUtils {
} }
runtime.run().await; runtime.run().await;
// An async source reports `Pending` on the evaluation that starts it and marks the runtime dirty once
// it completes, so the value only reaches the render on a follow-up evaluation. The superseded response's
// `Pending` error is ignored, but its messages carry the incremental resolved-types delta and must be
// dispatched, or the editor's type map desyncs permanently.
while runtime.take_dirty() {
let mut superseded_messages = VecDeque::new();
let _ = editor.poll_node_graph_evaluation(&mut superseded_messages);
for message in superseded_messages {
editor.handle_message(message);
}
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
}
runtime.run().await;
}
let mut messages = VecDeque::new(); let mut messages = VecDeque::new();
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) { if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
return Err(format!("Graph should render\n\n{e}")); return Err(format!("Graph should render\n\n{e}"));
+1
View File
@@ -1,4 +1,5 @@
node_modules/ node_modules/
wrapper/pkg/ wrapper/pkg/
wrapper/pkg-native/
public/build/ public/build/
dist/ dist/
+1
View File
@@ -29,6 +29,7 @@ export default defineConfig([
"**/node_modules/", "**/node_modules/",
"**/dist/", "**/dist/",
"**/pkg/", "**/pkg/",
"**/pkg-native/",
"wasm/pkg/", "wasm/pkg/",
// Don't ignore JS and TS dotfiles in this folder // Don't ignore JS and TS dotfiles in this folder
"!**/.*.js", "!**/.*.js",
+4 -1
View File
@@ -23,7 +23,10 @@ export default defineConfig(({ mode }) => {
// Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active // Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active
define: { __WASM_PART_COUNT__: "1" }, define: { __WASM_PART_COUNT__: "1" },
resolve: { resolve: {
alias: [{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") }], alias: [
...(mode === "native" ? [{ find: /^\/wrapper\/pkg\//, replacement: "/wrapper/pkg-native/" }] : []),
{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") },
],
}, },
server: { server: {
port: 8080, port: 8080,
+15 -11
View File
@@ -11,33 +11,37 @@ repository = "https://github.com/GraphiteEditor/Graphite"
license = "Apache-2.0" license = "Apache-2.0"
[features] [features]
default = ["gpu", "shader-nodes"] default = ["gpu", "shader-nodes", "web"]
gpu = ["editor/gpu"] web = ["editor", "editor?/wasm"]
shader-nodes = ["graphene-std/shader-nodes", "gpu"] editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:wgpu"]
native = ["node-macro/disable-registration"] gpu = ["editor?/gpu"]
shader-nodes = ["graphene-std?/shader-nodes", "gpu"]
native = []
[lib] [lib]
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
# Local dependencies # Local dependencies
editor = { path = "../../editor", package = "graphite-editor", features = ["gpu", "wasm"] } editor = { path = "../../editor", package = "graphite-editor", optional = true }
graphene-std = { workspace = true } graphite-proc-macros = { workspace = true }
graphene-std = { workspace = true, optional = true }
# Workspace dependencies # Workspace dependencies
bytemuck = { workspace = true } graph-craft = { workspace = true, optional = true }
graph-craft = { workspace = true }
log = { workspace = true } log = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
wasm-bindgen = { workspace = true } wasm-bindgen = { workspace = true }
serde-wasm-bindgen = { workspace = true } serde-wasm-bindgen = { workspace = true }
js-sys = { workspace = true } js-sys = { workspace = true }
wasm-bindgen-futures = { workspace = true } wasm-bindgen-futures = { workspace = true }
wgpu = { workspace = true } wgpu = { workspace = true, optional = true }
web-sys = { workspace = true } web-sys = { workspace = true }
ron = { workspace = true }
serde_json = { workspace = true } serde_json = { workspace = true }
node-macro = { workspace = true } tsify = { workspace = true }
[dev-dependencies]
serde_bytes = { workspace = true }
[lints.rust] [lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = [ unexpected_cfgs = { level = "warn", check-cfg = [
+690
View File
@@ -0,0 +1,690 @@
//! Commands that JS can call on the editor. Each function maps its arguments to a `Message`. On web the generated
//! stub dispatches it directly, on native the arguments are sent as an `EditorCommand` and the same body runs in
//! the editor process.
#![allow(clippy::too_many_arguments)]
#[cfg(target_family = "wasm")]
use crate::editor_wrapper::EditorWrapper;
use graphite_proc_macros::editor_commands;
use serde::{Deserialize, Serialize};
use tsify::Tsify;
#[cfg(target_family = "wasm")]
use wasm_bindgen::prelude::*;
#[editor_commands]
mod editor_commands {
use crate::helpers::translate_key;
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
use editor::messages::portfolio::utility_types::PanelGroupId;
use editor::messages::prelude::*;
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
use graph_craft::document::NodeId;
use graphene_std::raster::color::Color;
use graphene_std::vector::style::FillChoice;
use std::path::PathBuf;
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state.
fn resend_all_layouts() -> Message {
LayoutMessage::ResendAllLayouts.into()
}
/// First message of a session, sent once the frontend is ready
fn init_portfolio() -> Message {
PortfolioMessage::Init.into()
}
/// Per-frame tick: advances the animation clock and broadcasts the animation frame event
fn animation_frame(timestamp: u64) -> Message {
Message::Batched {
messages: Box::new([
InputPreprocessorMessage::CurrentTime { timestamp }.into(),
AnimationMessage::IncrementFrameCounter.into(),
// Used by auto-panning, but this could possibly be refactored in the future, see:
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(),
]),
}
}
fn auto_save_all_documents() -> Message {
PortfolioMessage::AutoSaveAllDocuments.into()
}
fn add_primary_import() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddPrimaryImport.into()]),
}
}
fn add_secondary_import() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddSecondaryImport.into()]),
}
}
fn add_primary_export() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddPrimaryExport.into()]),
}
}
fn add_secondary_export() -> Message {
Message::Batched {
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddSecondaryExport.into()]),
}
}
/// Start Pointer Lock
fn app_window_pointer_lock() -> Message {
AppWindowMessage::PointerLock.into()
}
/// Minimizes the application window to the taskbar or dock
fn app_window_minimize() -> Message {
AppWindowMessage::Minimize.into()
}
/// Toggles minimizing or restoring down the application window
fn app_window_maximize() -> Message {
AppWindowMessage::Maximize.into()
}
fn app_window_fullscreen() -> Message {
AppWindowMessage::Fullscreen.into()
}
/// Closes the application window
fn app_window_close() -> Message {
AppWindowMessage::Close.into()
}
/// Drag the application window
fn app_window_drag() -> Message {
AppWindowMessage::Drag.into()
}
/// Displays a dialog with an error message
fn error_dialog(title: String, description: String) -> Message {
DialogMessage::DisplayDialogError { title, description }.into()
}
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
fn widget_value_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
let widget_id = WidgetId(widget_id);
let update = LayoutMessage::WidgetValueUpdate {
layout_target,
widget_id,
value: value.cast(),
};
if resend_widget {
Message::Batched {
messages: Box::new([update.into(), LayoutMessage::ResendActiveWidget { layout_target, widget_id }.into()]),
}
} else {
update.into()
}
}
/// Commit the value of a given UI widget to the history
fn widget_value_commit(layout_target: LayoutTarget, widget_id: u64, value: Any) -> Message {
LayoutMessage::WidgetValueCommit {
layout_target,
widget_id: WidgetId(widget_id),
value: value.cast(),
}
.into()
}
/// Update the value of a given UI widget, and commit it to the history
fn widget_value_commit_and_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
let widget_id = WidgetId(widget_id);
let mut messages: Vec<Message> = vec![
LayoutMessage::WidgetValueCommit {
layout_target,
widget_id,
value: value.cast(),
}
.into(),
LayoutMessage::WidgetValueUpdate {
layout_target,
widget_id,
value: value.cast(),
}
.into(),
];
if resend_widget {
messages.push(LayoutMessage::ResendActiveWidget { layout_target, widget_id }.into());
}
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
messages.push(DocumentMessage::EndTransaction.into());
Message::Batched { messages: messages.into() }
}
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
fn widget_value_drag_drop(layout_target: LayoutTarget, widget_id: u64) -> Message {
let widget_id = WidgetId(widget_id);
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id }.into()
}
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
fn end_transaction() -> Message {
DocumentMessage::EndTransaction.into()
}
fn load_preferences(preferences: Option<String>) -> Message {
let Some(preferences) = preferences else { return Message::NoOp };
let Ok(preferences) = serde_json::from_str(&preferences) else {
log::error!("Failed to deserialize preferences");
return Message::NoOp;
};
PreferencesMessage::Load { preferences }.into()
}
fn load_document_content(document_id: u64, document: String) -> Message {
PersistentStateMessage::LoadDocument {
document_id: DocumentId(document_id),
document,
}
.into()
}
fn select_document(document_id: u64) -> Message {
PortfolioMessage::SelectDocument { document_id: DocumentId(document_id) }.into()
}
/// Rename the currently active document.
fn rename_document(new_name: String) -> Message {
PortfolioMessage::RenameDocument { new_name }.into()
}
fn new_document_dialog() -> Message {
DialogMessage::RequestNewDocumentDialog.into()
}
fn open_file(path: String, content: Vec<u8>) -> Message {
PortfolioMessage::OpenFile { path: PathBuf::from(path), content }.into()
}
fn import_file(path: String, content: Vec<u8>) -> Message {
PortfolioMessage::ImportFile { path: PathBuf::from(path), content }.into()
}
fn trigger_auto_save(document_id: u64) -> Message {
PortfolioMessage::AutoSaveDocument { document_id: DocumentId(document_id) }.into()
}
fn reorder_document(document_id: u64, new_index: usize) -> Message {
PortfolioMessage::ReorderDocument {
document_id: DocumentId(document_id),
new_index,
}
.into()
}
fn reorder_panel_group_tab(group: u64, old_index: usize, new_index: usize) -> Message {
PortfolioMessage::ReorderPanelGroupTab {
group: PanelGroupId(group),
old_index,
new_index,
}
.into()
}
fn move_all_panel_tabs(source_group: u64, target_group: u64, insert_index: usize) -> Message {
PortfolioMessage::MoveAllPanelTabs {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
}
.into()
}
fn move_panel_tab(source_group: u64, target_group: u64, insert_index: usize) -> Message {
PortfolioMessage::MovePanelTab {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
}
.into()
}
fn set_panel_group_active_tab(group: u64, tab_index: usize) -> Message {
PortfolioMessage::SetPanelGroupActiveTab {
group: PanelGroupId(group),
tab_index,
}
.into()
}
fn split_panel_group(target_group: u64, direction: DockingSplitDirection, tabs: PanelTypes, active_tab_index: usize) -> Message {
PortfolioMessage::SplitPanelGroup {
target_group: PanelGroupId(target_group),
direction,
tabs,
active_tab_index,
}
.into()
}
fn set_panel_group_sizes(split_path: Vec<u32>, sizes: Vec<f64>) -> Message {
let split_path = split_path.into_iter().map(|i| i as usize).collect();
PortfolioMessage::SetPanelGroupSizes { split_path, sizes }.into()
}
fn close_document_with_confirmation(document_id: u64) -> Message {
PortfolioMessage::CloseDocumentWithConfirmation { document_id: DocumentId(document_id) }.into()
}
fn request_about_graphite_dialog_with_localized_commit_date(localized_commit_date: String, localized_commit_year: String) -> Message {
DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
localized_commit_date,
localized_commit_year,
}
.into()
}
fn request_licenses_third_party_dialog_with_license_text(license_text: String) -> Message {
DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text }.into()
}
/// Send new viewport info to the backend
fn update_viewport(x: f64, y: f64, width: f64, height: f64, scale: f64) -> Message {
ViewportMessage::Update { x, y, width, height, scale }.into()
}
/// Mouse movement within the screenspace bounds of the viewport
fn on_mouse_move(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys }.into()
}
/// Mouse scrolling within the screenspace bounds of the viewport
fn on_wheel_scroll(x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) -> Message {
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys }.into()
}
/// A mouse button depressed within screenspace the bounds of the viewport
fn on_mouse_down(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys }.into()
}
/// A mouse button released
fn on_mouse_up(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys }.into()
}
/// Mouse shaken
fn on_mouse_shake(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys }.into()
}
/// Mouse double clicked
fn on_double_click(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys }.into()
}
/// A keyboard button depressed within screenspace the bounds of the viewport
fn on_key_down(name: String, modifiers: u8, key_repeat: bool) -> Message {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys }.into()
}
/// A keyboard button released
fn on_key_up(name: String, modifiers: u8, key_repeat: bool) -> Message {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys }.into()
}
/// A text box was committed
fn on_change_text(new_text: String, is_left_or_right_click: bool) -> Message {
TextToolMessage::TextChange { new_text, is_left_or_right_click }.into()
}
/// Dialog got dismissed
fn on_dialog_dismiss() -> Message {
DialogMessage::Dismiss.into()
}
/// A text box was changed
fn update_bounds(new_text: String) -> Message {
TextToolMessage::UpdateBounds { new_text }.into()
}
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
fn update_primary_color(color: SRGBA8) -> Message {
ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: true,
}
.into()
}
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
fn update_secondary_color(color: SRGBA8) -> Message {
ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: false,
}
.into()
}
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
fn open_color_picker(initial_value: FillChoiceUI, allow_none: bool, disabled: bool) -> Message {
ColorPickerMessage::Open {
initial_value: FillChoice::from(&initial_value),
allow_none,
disabled,
}
.into()
}
/// Tell the Rust color picker handler that the popover is closing.
fn close_color_picker() -> Message {
ColorPickerMessage::Close.into()
}
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
fn update_gradient_stop_color(color: SRGBA8) -> Message {
GradientToolMessage::UpdateStopColor { color: Color::from(color) }.into()
}
/// Start a new undo transaction for gradient stop color editing
fn start_gradient_stop_color_transaction() -> Message {
GradientToolMessage::StartTransactionForColorStop.into()
}
/// Commit the current gradient stop color transaction (called on pointer-up after each drag/click)
fn commit_gradient_stop_color_transaction() -> Message {
GradientToolMessage::CommitTransactionForColorStop.into()
}
/// Close the gradient stop color picker and commit any pending transaction
fn close_gradient_stop_color_picker() -> Message {
GradientToolMessage::CloseStopColorPicker.into()
}
/// Toggle clipping the alpha of a layer to the alpha of the layer below it in the layer stack
fn clip_layer(id: u64) -> Message {
DocumentMessage::ClipLayer { id: NodeId(id) }.into()
}
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
fn select_layer(id: u64, ctrl: bool, shift: bool) -> Message {
DocumentMessage::SelectLayer { id: NodeId(id), ctrl, shift }.into()
}
/// Deselect all layers
fn deselect_all_layers() -> Message {
DocumentMessage::DeselectAllLayers.into()
}
/// Move a layer to within a folder and placed down at the given index.
/// If the folder is `None`, it is inserted into the document root.
/// If the insert index is `None`, it is inserted at the start of the folder.
fn move_layer_in_tree(insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
let insert_parent_id = insert_parent_id.map(NodeId);
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
DocumentMessage::MoveSelectedLayersTo {
parent,
insert_index: insert_index.unwrap_or_default(),
}
.into()
}
/// Reorder a draggable Properties panel section to the given index among its peers.
fn reorder_properties_section(node_id: u64, insert_index: usize) -> Message {
DocumentMessage::ReorderPropertiesSection {
node_id: NodeId(node_id),
insert_index,
}
.into()
}
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
/// If the folder is `None`, they are inserted into the document root.
/// If the insert index is `None`, they are inserted at the start of the folder.
fn duplicate_layer_in_tree(insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
DocumentMessage::DuplicateSelectedLayersTo {
parent: insert_parent_id.map(NodeId).map(LayerNodeIdentifier::new_unchecked).unwrap_or_default(),
insert_index: insert_index.unwrap_or_default(),
}
.into()
}
/// Set the name for the layer
fn set_layer_name(id: u64, name: String) -> Message {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
NodeGraphMessage::SetDisplayName {
node_id: layer.to_node(),
network_path: Vec::new(),
alias: name,
skip_adding_history_step: false,
}
.into()
}
/// Translates document (in viewport coords)
fn pan_canvas_abort_prepare(x_not_y_axis: bool) -> Message {
NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis }.into()
}
fn pan_canvas_abort(x_not_y_axis: bool) -> Message {
NavigationMessage::CanvasPanAbort { x_not_y_axis }.into()
}
/// Translates document (in viewport coords)
fn pan_canvas(delta_x: f64, delta_y: f64) -> Message {
NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() }.into()
}
/// Translates document (in viewport coords)
fn pan_canvas_by_fraction(delta_x: f64, delta_y: f64) -> Message {
NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() }.into()
}
/// Merge the selected nodes into a subnetwork
fn merge_selected_nodes() -> Message {
NodeGraphMessage::MergeSelectedNodes.into()
}
/// Toggle lock state of all selected layers
fn toggle_selected_locked() -> Message {
NodeGraphMessage::ToggleSelectedLocked.into()
}
/// Creates a new document node in the node graph
fn create_node(node_type: String, x: i32, y: i32) -> Message {
let id = NodeId::new();
NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(id),
node_type: DefinitionIdentifier::from_serialized(&node_type),
xy: Some((x / 24, y / 24)),
add_transaction: true,
}
.into()
}
/// Respond to selection read
fn read_selection(content: Option<String>, cut: bool) -> Message {
ClipboardMessage::ReadSelection { content, cut }.into()
}
/// Paste from a serialized JSON representation
fn paste_text(data: String) -> Message {
ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(data),
}
.into()
}
/// Pastes an image
fn paste_image(
name: Option<String>,
image_data: Vec<u8>,
width: u32,
height: u32,
mouse_x: Option<f64>,
mouse_y: Option<f64>,
insert_parent_id: Option<u64>,
insert_index: Option<usize>,
) -> Message {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
PortfolioMessage::InsertImage {
name,
image,
mouse,
parent_and_insert_index,
}
.into()
}
/// Pastes an SVG given its string representation
fn paste_svg(name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
PortfolioMessage::InsertSvg {
name,
svg,
mouse,
parent_and_insert_index,
}
.into()
}
/// Toggle visibility of a layer or node given its node ID
fn toggle_node_visibility_layer_panel(id: u64) -> Message {
NodeGraphMessage::ToggleVisibility {
node_id: NodeId(id),
network_path: Vec::new(),
}
.into()
}
/// Pin or unpin a node given its node ID
fn set_node_pinned(id: u64, pinned: bool) -> Message {
DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into()
}
/// Collapse or expand a node's section in the Properties panel
fn toggle_node_properties_section_expanded(id: u64) -> Message {
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) }.into()
}
/// Delete a layer or node given its node ID
fn delete_node(id: u64) -> Message {
DocumentMessage::DeleteNode { node_id: NodeId(id) }.into()
}
/// Toggle lock state of a layer from the layer list
fn toggle_layer_lock(node_id: u64) -> Message {
NodeGraphMessage::ToggleLocked {
node_id: NodeId(node_id),
network_path: Vec::new(),
}
.into()
}
/// Toggle expansions state of a layer from the layer list
fn toggle_layer_expansion(tree_path: Vec<u64>, recursive: bool) -> Message {
let tree_path = tree_path.into_iter().map(NodeId).collect();
DocumentMessage::ToggleLayerExpansion { tree_path, recursive }.into()
}
/// Set the active panel to the most recently clicked panel
fn set_active_panel(panel: String) -> Message {
DocumentMessage::SetActivePanel { active_panel: panel.into() }.into()
}
/// Toggle display type for a layer
fn set_to_node_or_layer(id: u64, is_layer: bool) -> Message {
DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer }.into()
}
/// Set the name of an import or export
fn set_import_name(index: usize, name: String) -> Message {
NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Import(index),
}
.into()
}
/// Set the name of an export
fn set_export_name(index: usize, name: String) -> Message {
NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Export(index),
}
.into()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
pub struct Any(#[tsify(type = "any")] serde_json::Value);
impl Any {
#[cfg(feature = "editor")]
pub(crate) fn cast<T: for<'de> Deserialize<'de>>(&self) -> T {
serde_json::from_value(self.0.clone()).unwrap()
}
}
macro_rules! editor_proxy_types {
($($name:ident = $real:ty;)*) => {
$(
#[cfg(feature = "editor")]
pub type $name = $real;
#[cfg(not(feature = "editor"))]
pub type $name = Any;
)*
};
}
editor_proxy_types! {
LayoutTarget = editor::messages::layout::utility_types::layout_widget::LayoutTarget;
DockingSplitDirection = editor::messages::portfolio::utility_types::DockingSplitDirection;
PanelTypes = Vec<editor::messages::portfolio::utility_types::PanelType>;
SRGBA8 = graphene_std::color::SRGBA8;
FillChoiceUI = graphene_std::vector::style::FillChoiceUI;
}
+70 -811
View File
@@ -1,44 +1,33 @@
#![allow(clippy::too_many_arguments)] //! JS-facing editor handle. Owns the callback that delivers `FrontendMessage`s to JS; on web `dispatch` runs
// //! messages through the in-process editor, on native `send` forwards them as `EditorCommand`s.
// This file is where functions are defined to be called directly from JS.
// It serves as a thin wrapper over the editor backend API that relies
// on the dispatcher messaging system and more complex Rust data types.
//
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
use crate::EDITOR; use crate::EDITOR;
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
use crate::helpers::poll_node_graph_evaluation; use crate::MESSAGE_BUFFER;
use crate::helpers::{auto_save_all_documents, calculate_hash, render_image_data_to_canvases, request_animation_frame, set_timeout, translate_key, wrapper}; #[cfg(all(feature = "native", target_family = "wasm"))]
use crate::{EDITOR_HAS_CRASHED, Error, FRONTEND_READY, MESSAGE_BUFFER}; use crate::editor_commands::EditorCommand;
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
use crate::helpers::poll_node_graph_evaluation;
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
use crate::helpers::wrapper;
#[cfg(feature = "editor")]
use crate::helpers::{calculate_hash, render_image_data_to_canvases};
use crate::helpers::{request_animation_frame, set_timeout};
use crate::{EDITOR_HAS_CRASHED, FRONTEND_READY};
#[cfg(all(not(feature = "native"), target_family = "wasm"))] #[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::application::{Editor, Environment, Host, Platform}; use editor::application::{Editor, Environment, Host, Platform};
use editor::consts::{FILE_EXTENSION, GDD_FILE_EXTENSION}; #[cfg(feature = "editor")]
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
use editor::messages::layout::utility_types::layout_widget::LayoutTarget;
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
use editor::messages::portfolio::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
use editor::messages::prelude::*; use editor::messages::prelude::*;
use editor::messages::tool::tool_messages::tool_prelude::WidgetId; #[cfg(feature = "editor")]
use graph_craft::document::NodeId;
use graphene_std::color::SRGBA8;
use graphene_std::graphene_hash::CacheHashWrapper;
use graphene_std::raster::color::Color;
use graphene_std::vector::style::{FillChoice, FillChoiceUI};
use serde::Serialize; use serde::Serialize;
use serde_wasm_bindgen::{self, from_value};
use std::cell::RefCell; use std::cell::RefCell;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration; use std::time::Duration;
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0); pub(crate) static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0);
/// This struct is, via wasm-bindgen, used by JS to interact with the editor backend. It does this by calling functions, which are `impl`ed
#[wasm_bindgen] #[wasm_bindgen]
#[derive(Clone)] #[derive(Clone)]
pub struct EditorWrapper { pub struct EditorWrapper {
@@ -46,13 +35,7 @@ pub struct EditorWrapper {
frontend_message_handler_callback: js_sys::Function, frontend_message_handler_callback: js_sys::Function,
} }
// Defined separately from the `impl` block below since this `impl` block lacks the `#[wasm_bindgen]` attribute.
// Quirks in wasm-bindgen prevent functions in `#[wasm_bindgen]` `impl` blocks from being made publicly accessible from Rust.
impl EditorWrapper { impl EditorWrapper {
pub fn send_frontend_message_to_js_rust_proxy(&self, message: FrontendMessage) {
self.send_frontend_message_to_js(message);
}
#[cfg(any(feature = "native", target_family = "wasm"))] #[cfg(any(feature = "native", target_family = "wasm"))]
fn initialize_wrapper(frontend_message_handler_callback: js_sys::Function) -> EditorWrapper { fn initialize_wrapper(frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
use crate::{EDITOR_WRAPPER, PANIC_DIALOG_MESSAGE_CALLBACK}; use crate::{EDITOR_WRAPPER, PANIC_DIALOG_MESSAGE_CALLBACK};
@@ -69,10 +52,6 @@ impl EditorWrapper {
#[wasm_bindgen] #[wasm_bindgen]
impl EditorWrapper { impl EditorWrapper {
// ========================
// Editor wrapper machinery
// ========================
#[cfg(all(not(feature = "native"), target_family = "wasm"))] #[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub async fn create(platform: String, uuid_random_seed: u64, frontend_message_handler_callback: js_sys::Function) -> EditorWrapper { pub async fn create(platform: String, uuid_random_seed: u64, frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
use graph_craft::application_io::PlatformApplicationIo; use graph_craft::application_io::PlatformApplicationIo;
@@ -115,7 +94,6 @@ impl EditorWrapper {
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) { pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
// Process no further messages after a crash to avoid spamming the console // Process no further messages after a crash to avoid spamming the console
use crate::MESSAGE_BUFFER;
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) { if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return; return;
} }
@@ -137,24 +115,15 @@ impl EditorWrapper {
self.send_frontend_message_to_js(message); self.send_frontend_message_to_js(message);
} }
} }
#[cfg(feature = "native")]
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
let message: Message = message.into();
let Ok(serialized_message) = ron::to_string(&message) else {
log::error!("Failed to serialize message");
return;
};
crate::native_communication::send_message_to_cef(serialized_message)
}
// Sends a FrontendMessage to JavaScript #[cfg(feature = "editor")]
pub(crate) fn send_frontend_message_to_js(&self, message: FrontendMessage) { pub(crate) fn send_frontend_message_to_js(&self, message: FrontendMessage) {
if let FrontendMessage::UpdateImageData { ref image_data } = message { if let FrontendMessage::UpdateImageData { ref image_data } = message {
let new_hash = calculate_hash(&CacheHashWrapper(image_data)); let new_hash = calculate_hash(image_data);
let prev_hash = IMAGE_DATA_HASH.load(Ordering::Relaxed); let prev_hash = IMAGE_DATA_HASH.load(Ordering::Relaxed);
if new_hash != prev_hash { if new_hash != prev_hash {
render_image_data_to_canvases(image_data.as_slice()); render_image_data_to_canvases(image_data.iter());
IMAGE_DATA_HASH.store(new_hash, Ordering::Relaxed); IMAGE_DATA_HASH.store(new_hash, Ordering::Relaxed);
} }
return; return;
@@ -172,16 +141,31 @@ impl EditorWrapper {
} }
} }
// ================================================ pub(crate) fn forward_serialized_frontend_message_to_js(&self, name: &str, data: crate::wasm_value::WasmValue) {
// Functions for calling the editor in Rust from JS let js_return_value = self.frontend_message_handler_callback.call2(&JsValue::null(), &JsValue::from(name), &data.into());
// ================================================
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state. if let Err(error) = js_return_value {
#[wasm_bindgen(js_name = resendAllLayouts)] error!("While handling FrontendMessage {name:?}, JavaScript threw an error:\n{error:?}")
pub fn resend_all_layouts(&self) { }
self.dispatch(LayoutMessage::ResendAllLayouts);
} }
#[cfg(all(feature = "native", target_family = "wasm"))]
pub(crate) fn send(&self, command: EditorCommand) {
// Process no further commands after a crash to avoid spamming the console
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return;
}
let Ok(serialized) = serde_json::to_string(&command) else {
log::error!("Failed to serialize editor command");
return;
};
crate::native_communication::send_message_to_cef(serialized)
}
}
#[wasm_bindgen]
impl EditorWrapper {
#[wasm_bindgen(js_name = initAfterFrontendReady)] #[wasm_bindgen(js_name = initAfterFrontendReady)]
pub fn init_after_frontend_ready(&self) { pub fn init_after_frontend_ready(&self) {
// Enforce idempotency, so if this is called again during an HMR re-mount, we don't initialize the editor backend twice // Enforce idempotency, so if this is called again during an HMR re-mount, we don't initialize the editor backend twice
@@ -192,7 +176,8 @@ impl EditorWrapper {
#[cfg(feature = "native")] #[cfg(feature = "native")]
crate::native_communication::initialize_native_communication(); crate::native_communication::initialize_native_communication();
self.dispatch(PortfolioMessage::Init); #[cfg(target_family = "wasm")]
self.init_portfolio();
// Poll node graph evaluation on `requestAnimationFrame` // Poll node graph evaluation on `requestAnimationFrame`
{ {
@@ -203,25 +188,19 @@ impl EditorWrapper {
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
wasm_bindgen_futures::spawn_local(poll_node_graph_evaluation()); wasm_bindgen_futures::spawn_local(poll_node_graph_evaluation());
if !EDITOR_HAS_CRASHED.load(Ordering::SeqCst) { #[cfg(any(not(feature = "native"), target_family = "wasm"))]
wrapper(|wrapper| { wrapper(|wrapper| {
// Process all messages that have been queued up // On web, flush the messages that queued up while the editor was locked before this frame's tick
let mut messages = MESSAGE_BUFFER.take(); #[cfg(not(feature = "native"))]
messages.push( {
InputPreprocessorMessage::CurrentTime { let messages = MESSAGE_BUFFER.take();
timestamp: js_sys::Date::now() as u64, if !messages.is_empty() {
} wrapper.dispatch(Message::Batched { messages: messages.into() });
.into(), }
); }
messages.push(AnimationMessage::IncrementFrameCounter.into()); #[cfg(target_family = "wasm")]
wrapper.animation_frame(js_sys::Date::now() as u64);
// Used by auto-panning, but this could possibly be refactored in the future, see: });
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
messages.push(BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into());
wrapper.dispatch(Message::Batched { messages: messages.into() });
});
}
// Schedule ourself for another requestAnimationFrame callback // Schedule ourself for another requestAnimationFrame callback
request_animation_frame(f.borrow().as_ref().unwrap()); request_animation_frame(f.borrow().as_ref().unwrap());
@@ -230,94 +209,25 @@ impl EditorWrapper {
request_animation_frame(g.borrow().as_ref().unwrap()); request_animation_frame(g.borrow().as_ref().unwrap());
} }
const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
// Auto save all documents on `setTimeout` // Auto save all documents on `setTimeout`
{ {
let f = std::rc::Rc::new(RefCell::new(None)); let f = std::rc::Rc::new(RefCell::new(None));
let g = f.clone(); let g = f.clone();
*g.borrow_mut() = Some(Closure::new(move || { *g.borrow_mut() = Some(Closure::new(move || {
auto_save_all_documents(); #[cfg(target_family = "wasm")]
wrapper(|wrapper| wrapper.auto_save_all_documents());
// Schedule ourself for another setTimeout callback // Schedule ourself for another setTimeout callback
set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS)); set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(AUTO_SAVE_TIMEOUT_SECONDS));
})); }));
set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS)); set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(AUTO_SAVE_TIMEOUT_SECONDS));
} }
} }
#[wasm_bindgen(js_name = addPrimaryImport)]
pub fn add_primary_import(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddPrimaryImport);
}
#[wasm_bindgen(js_name = addSecondaryImport)]
pub fn add_secondary_import(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddSecondaryImport);
}
#[wasm_bindgen(js_name = addPrimaryExport)]
pub fn add_primary_export(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddPrimaryExport);
}
#[wasm_bindgen(js_name = addSecondaryExport)]
pub fn add_secondary_export(&self) {
self.dispatch(DocumentMessage::AddTransaction);
self.dispatch(NodeGraphMessage::AddSecondaryExport);
}
/// Start Pointer Lock
#[wasm_bindgen(js_name = appWindowPointerLock)]
pub fn app_window_pointer_lock(&self) {
let message = AppWindowMessage::PointerLock;
self.dispatch(message);
}
/// Minimizes the application window to the taskbar or dock
#[wasm_bindgen(js_name = appWindowMinimize)]
pub fn app_window_minimize(&self) {
let message = AppWindowMessage::Minimize;
self.dispatch(message);
}
/// Toggles minimizing or restoring down the application window
#[wasm_bindgen(js_name = appWindowMaximize)]
pub fn app_window_maximize(&self) {
let message = AppWindowMessage::Maximize;
self.dispatch(message);
}
#[wasm_bindgen(js_name = appWindowFullscreen)]
pub fn app_window_fullscreen(&self) {
let message = AppWindowMessage::Fullscreen;
self.dispatch(message);
}
/// Closes the application window
#[wasm_bindgen(js_name = appWindowClose)]
pub fn app_window_close(&self) {
let message = AppWindowMessage::Close;
self.dispatch(message);
}
/// Drag the application window
#[wasm_bindgen(js_name = appWindowDrag)]
pub fn app_window_start_drag(&self) {
let message = AppWindowMessage::Drag;
self.dispatch(message);
}
/// Displays a dialog with an error message
#[wasm_bindgen(js_name = errorDialog)]
pub fn error_dialog(&self, title: String, description: String) {
let message = DialogMessage::DisplayDialogError { title, description };
self.dispatch(message);
}
/// Answer whether or not the editor has crashed /// Answer whether or not the editor has crashed
#[wasm_bindgen(js_name = hasCrashed)] #[wasm_bindgen(js_name = hasCrashed)]
pub fn has_crashed(&self) -> bool { pub fn has_crashed(&self) -> bool {
@@ -330,676 +240,25 @@ impl EditorWrapper {
cfg!(debug_assertions) cfg!(debug_assertions)
} }
/// Get the constant `FILE_EXTENSION`
#[wasm_bindgen(js_name = fileExtension)] #[wasm_bindgen(js_name = fileExtension)]
pub fn file_extension(&self) -> String { pub fn file_extension(&self) -> String {
FILE_EXTENSION.into() "graphite".into()
} }
/// Get the constant `GDD_FILE_EXTENSION`
#[wasm_bindgen(js_name = gddFileExtension)] #[wasm_bindgen(js_name = gddFileExtension)]
pub fn gdd_file_extension(&self) -> String { pub fn gdd_file_extension(&self) -> String {
GDD_FILE_EXTENSION.into() "gdd".into()
}
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
#[wasm_bindgen(js_name = widgetValueUpdate)]
pub fn widget_value_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)
}
/// Commit the value of a given UI widget to the history
#[wasm_bindgen(js_name = widgetValueCommit)]
pub fn widget_value_commit(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
self.widget_value_commit_helper(layout_target, widget_id, value)
}
/// Update the value of a given UI widget, and commit it to the history
#[wasm_bindgen(js_name = widgetValueCommitAndUpdate)]
pub fn widget_value_commit_and_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
self.widget_value_commit_helper(layout_target, widget_id, value.clone())?;
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)?;
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
self.dispatch(DocumentMessage::EndTransaction);
Ok(())
}
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
#[wasm_bindgen(js_name = widgetValueDragDrop)]
pub fn widget_value_drag_drop(&self, layout_target: LayoutTarget, widget_id: u64) {
let widget_id = WidgetId(widget_id);
self.dispatch(LayoutMessage::WidgetValueDragDrop { layout_target, widget_id });
}
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
#[wasm_bindgen(js_name = endTransaction)]
pub fn end_transaction(&self) {
self.dispatch(DocumentMessage::EndTransaction);
}
pub fn widget_value_update_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
let widget_id = WidgetId(widget_id);
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not update UI: {e}")))?;
let message = LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value };
self.dispatch(message);
if resend_widget {
let resend_message = LayoutMessage::ResendActiveWidget { layout_target, widget_id };
self.dispatch(resend_message);
}
Ok(())
}
pub fn widget_value_commit_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
let widget_id = WidgetId(widget_id);
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not commit UI: {e}")))?;
let message = LayoutMessage::WidgetValueCommit { layout_target, widget_id, value };
self.dispatch(message);
Ok(())
}
#[wasm_bindgen(js_name = loadPreferences)]
pub fn load_preferences(&self, preferences: Option<String>) {
if let Some(preferences) = preferences {
let Ok(preferences) = serde_json::from_str(&preferences) else {
log::error!("Failed to deserialize preferences");
return;
};
let message = PreferencesMessage::Load { preferences };
self.dispatch(message);
}
} }
/// Load persisted browser storage state (web only; on desktop, persistence is handled natively and this is never triggered)
#[cfg(all(feature = "web", not(feature = "native")))]
#[wasm_bindgen(js_name = loadPersistedState)] #[wasm_bindgen(js_name = loadPersistedState)]
pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) { pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) {
self.dispatch(PersistentStateMessage::LoadState { state }); self.dispatch(PersistentStateMessage::LoadState { state });
} }
#[cfg(feature = "native")]
#[wasm_bindgen(js_name = loadDocumentContent)] #[wasm_bindgen(js_name = loadPersistedState)]
pub fn load_document_content(&self, document_id: u64, document: String) { pub fn load_persisted_state(&self, _state: JsValue) {
let message = PersistentStateMessage::LoadDocument { log::error!("loadPersistedState is unavailable on desktop; persistence is handled natively");
document_id: DocumentId(document_id),
document,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = selectDocument)]
pub fn select_document(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::SelectDocument { document_id };
self.dispatch(message);
}
/// Rename the currently active document.
#[wasm_bindgen(js_name = renameDocument)]
pub fn rename_document(&self, new_name: String) {
let message = PortfolioMessage::RenameDocument { new_name };
self.dispatch(message);
}
#[wasm_bindgen(js_name = newDocumentDialog)]
pub fn new_document_dialog(&self) {
let message = DialogMessage::RequestNewDocumentDialog;
self.dispatch(message);
}
#[wasm_bindgen(js_name = openFile)]
pub fn open_file(&self, path: String, content: Vec<u8>) {
let message = PortfolioMessage::OpenFile { path: PathBuf::from(path), content };
self.dispatch(message);
}
#[wasm_bindgen(js_name = importFile)]
pub fn import_file(&self, path: String, content: Vec<u8>) {
let message = PortfolioMessage::ImportFile { path: PathBuf::from(path), content };
self.dispatch(message);
}
#[wasm_bindgen(js_name = triggerAutoSave)]
pub fn trigger_auto_save(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::AutoSaveDocument { document_id };
self.dispatch(message);
}
#[wasm_bindgen(js_name = reorderDocument)]
pub fn reorder_document(&self, document_id: u64, new_index: usize) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::ReorderDocument { document_id, new_index };
self.dispatch(message);
}
#[wasm_bindgen(js_name = reorderPanelGroupTab)]
pub fn reorder_panel_group_tab(&self, group: u64, old_index: usize, new_index: usize) {
let message = PortfolioMessage::ReorderPanelGroupTab {
group: PanelGroupId(group),
old_index,
new_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = moveAllPanelTabs)]
pub fn move_all_panel_tabs(&self, source_group: u64, target_group: u64, insert_index: usize) {
let message = PortfolioMessage::MoveAllPanelTabs {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = movePanelTab)]
pub fn move_panel_tab(&self, source_group: u64, target_group: u64, insert_index: usize) {
let message = PortfolioMessage::MovePanelTab {
source_group: PanelGroupId(source_group),
target_group: PanelGroupId(target_group),
insert_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = setPanelGroupActiveTab)]
pub fn set_panel_group_active_tab(&self, group: u64, tab_index: usize) {
let message = PortfolioMessage::SetPanelGroupActiveTab {
group: PanelGroupId(group),
tab_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = splitPanelGroup)]
pub fn split_panel_group(&self, target_group: u64, direction: DockingSplitDirection, tabs: Vec<PanelType>, active_tab_index: usize) {
let message = PortfolioMessage::SplitPanelGroup {
target_group: PanelGroupId(target_group),
direction,
tabs,
active_tab_index,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = setPanelGroupSizes)]
pub fn set_panel_group_sizes(&self, split_path: Vec<u32>, sizes: Vec<f64>) {
let split_path = split_path.into_iter().map(|i| i as usize).collect();
let message = PortfolioMessage::SetPanelGroupSizes { split_path, sizes };
self.dispatch(message);
}
#[wasm_bindgen(js_name = closeDocumentWithConfirmation)]
pub fn close_document_with_confirmation(&self, document_id: u64) {
let document_id = DocumentId(document_id);
let message = PortfolioMessage::CloseDocumentWithConfirmation { document_id };
self.dispatch(message);
}
#[wasm_bindgen(js_name = requestAboutGraphiteDialogWithLocalizedCommitDate)]
pub fn request_about_graphite_dialog_with_localized_commit_date(&self, localized_commit_date: String, localized_commit_year: String) {
let message = DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
localized_commit_date,
localized_commit_year,
};
self.dispatch(message);
}
#[wasm_bindgen(js_name = requestLicensesThirdPartyDialogWithLicenseText)]
pub fn request_licenses_third_party_dialog_with_license_text(&self, license_text: String) {
let message = DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text };
self.dispatch(message);
}
/// Send new viewport info to the backend
#[wasm_bindgen(js_name = updateViewport)]
pub fn update_viewport(&self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
let message = ViewportMessage::Update { x, y, width, height, scale };
self.dispatch(message);
}
/// Mouse movement within the screenspace bounds of the viewport
#[wasm_bindgen(js_name = onMouseMove)]
pub fn on_mouse_move(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse scrolling within the screenspace bounds of the viewport
#[wasm_bindgen(js_name = onWheelScroll)]
pub fn on_wheel_scroll(&self, x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) {
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A mouse button depressed within screenspace the bounds of the viewport
#[wasm_bindgen(js_name = onMouseDown)]
pub fn on_mouse_down(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A mouse button released
#[wasm_bindgen(js_name = onMouseUp)]
pub fn on_mouse_up(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse shaken
#[wasm_bindgen(js_name = onMouseShake)]
pub fn on_mouse_shake(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// Mouse double clicked
#[wasm_bindgen(js_name = onDoubleClick)]
pub fn on_double_click(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
let message = InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys };
self.dispatch(message);
}
/// A keyboard button depressed within screenspace the bounds of the viewport
#[wasm_bindgen(js_name = onKeyDown)]
pub fn on_key_down(&self, name: String, modifiers: u8, key_repeat: bool) {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
let message = InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys };
self.dispatch(message);
}
/// A keyboard button released
#[wasm_bindgen(js_name = onKeyUp)]
pub fn on_key_up(&self, name: String, modifiers: u8, key_repeat: bool) {
let key = translate_key(&name);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
let message = InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys };
self.dispatch(message);
}
/// A text box was committed
#[wasm_bindgen(js_name = onChangeText)]
pub fn on_change_text(&self, new_text: String, is_left_or_right_click: bool) -> Result<(), JsValue> {
let message = TextToolMessage::TextChange { new_text, is_left_or_right_click };
self.dispatch(message);
Ok(())
}
/// Dialog got dismissed
#[wasm_bindgen(js_name = onDialogDismiss)]
pub fn on_dialog_dismiss(&self) {
let message = DialogMessage::Dismiss;
self.dispatch(message);
}
/// A text box was changed
#[wasm_bindgen(js_name = updateBounds)]
pub fn update_bounds(&self, new_text: String) -> Result<(), JsValue> {
let message = TextToolMessage::UpdateBounds { new_text };
self.dispatch(message);
Ok(())
}
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
#[wasm_bindgen(js_name = updatePrimaryColor)]
pub fn update_primary_color(&self, color: SRGBA8) {
self.dispatch(ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: true,
});
}
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
#[wasm_bindgen(js_name = updateSecondaryColor)]
pub fn update_secondary_color(&self, color: SRGBA8) {
self.dispatch(ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: false,
});
}
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
#[wasm_bindgen(js_name = openColorPicker)]
pub fn open_color_picker(&self, initial_value: FillChoiceUI, allow_none: bool, disabled: bool) {
let initial_value = FillChoice::from(&initial_value);
self.dispatch(ColorPickerMessage::Open { initial_value, allow_none, disabled });
}
/// Tell the Rust color picker handler that the popover is closing.
#[wasm_bindgen(js_name = closeColorPicker)]
pub fn close_color_picker(&self) {
self.dispatch(ColorPickerMessage::Close);
}
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
#[wasm_bindgen(js_name = updateGradientStopColor)]
pub fn update_gradient_stop_color(&self, color: SRGBA8) {
self.dispatch(GradientToolMessage::UpdateStopColor { color: Color::from(color) });
}
/// Start a new undo transaction for gradient stop color editing
#[wasm_bindgen(js_name = startGradientStopColorTransaction)]
pub fn start_gradient_stop_color_transaction(&self) {
self.dispatch(GradientToolMessage::StartTransactionForColorStop);
}
/// Commit the current gradient stop color transaction (called on pointer-up after each drag/click)
#[wasm_bindgen(js_name = commitGradientStopColorTransaction)]
pub fn commit_gradient_stop_color_transaction(&self) {
self.dispatch(GradientToolMessage::CommitTransactionForColorStop);
}
/// Close the gradient stop color picker and commit any pending transaction
#[wasm_bindgen(js_name = closeGradientStopColorPicker)]
pub fn close_gradient_stop_color_picker(&self) {
self.dispatch(GradientToolMessage::CloseStopColorPicker);
}
/// Toggle clipping the alpha of a layer to the alpha of the layer below it in the layer stack
#[wasm_bindgen(js_name = clipLayer)]
pub fn clip_layer(&self, id: u64) {
let id = NodeId(id);
let message = DocumentMessage::ClipLayer { id };
self.dispatch(message);
}
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
#[wasm_bindgen(js_name = selectLayer)]
pub fn select_layer(&self, id: u64, ctrl: bool, shift: bool) {
let id = NodeId(id);
let message = DocumentMessage::SelectLayer { id, ctrl, shift };
self.dispatch(message);
}
/// Deselect all layers
#[wasm_bindgen(js_name = deselectAllLayers)]
pub fn deselect_all_layers(&self) {
let message = DocumentMessage::DeselectAllLayers;
self.dispatch(message);
}
/// Move a layer to within a folder and placed down at the given index.
/// If the folder is `None`, it is inserted into the document root.
/// If the insert index is `None`, it is inserted at the start of the folder.
#[wasm_bindgen(js_name = moveLayerInTree)]
pub fn move_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let insert_parent_id = insert_parent_id.map(NodeId);
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
let message = DocumentMessage::MoveSelectedLayersTo {
parent,
insert_index: insert_index.unwrap_or_default(),
};
self.dispatch(message);
}
/// Reorder a draggable Properties panel section to the given index among its peers.
#[wasm_bindgen(js_name = reorderPropertiesSection)]
pub fn reorder_properties_section(&self, node_id: u64, insert_index: usize) {
self.dispatch(DocumentMessage::ReorderPropertiesSection {
node_id: NodeId(node_id),
insert_index,
});
}
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
/// If the folder is `None`, they are inserted into the document root.
/// If the insert index is `None`, they are inserted at the start of the folder.
#[wasm_bindgen(js_name = duplicateLayerInTree)]
pub fn duplicate_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let message = DocumentMessage::DuplicateSelectedLayersTo {
parent: insert_parent_id.map(NodeId).map(LayerNodeIdentifier::new_unchecked).unwrap_or_default(),
insert_index: insert_index.unwrap_or_default(),
};
self.dispatch(message);
}
/// Set the name for the layer
#[wasm_bindgen(js_name = setLayerName)]
pub fn set_layer_name(&self, id: u64, name: String) {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
let message = NodeGraphMessage::SetDisplayName {
node_id: layer.to_node(),
network_path: Vec::new(),
alias: name,
skip_adding_history_step: false,
};
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvasAbortPrepare)]
pub fn pan_canvas_abort_prepare(&self, x_not_y_axis: bool) {
let message = NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis };
self.dispatch(message);
}
#[wasm_bindgen(js_name = panCanvasAbort)]
pub fn pan_canvas_abort(&self, x_not_y_axis: bool) {
let message = NavigationMessage::CanvasPanAbort { x_not_y_axis };
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvas)]
pub fn pan_canvas(&self, delta_x: f64, delta_y: f64) {
let message = NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() };
self.dispatch(message);
}
/// Translates document (in viewport coords)
#[wasm_bindgen(js_name = panCanvasByFraction)]
pub fn pan_canvas_by_fraction(&self, delta_x: f64, delta_y: f64) {
let message = NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() };
self.dispatch(message);
}
/// Merge the selected nodes into a subnetwork
#[wasm_bindgen(js_name = mergeSelectedNodes)]
pub fn merge_nodes(&self) {
let message = NodeGraphMessage::MergeSelectedNodes;
self.dispatch(message);
}
/// Toggle lock state of all selected layers
#[wasm_bindgen(js_name = toggleSelectedLocked)]
pub fn toggle_selected_locked(&self) {
let message = NodeGraphMessage::ToggleSelectedLocked;
self.dispatch(message);
}
/// Creates a new document node in the node graph
#[wasm_bindgen(js_name = createNode)]
pub fn create_node(&self, node_type: JsValue, x: i32, y: i32) {
let value: serde_json::Value = serde_wasm_bindgen::from_value(node_type).unwrap();
let id = NodeId::new();
let message = NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(id),
node_type: value.into(),
xy: Some((x / 24, y / 24)),
add_transaction: true,
};
self.dispatch(message);
}
/// Respond to selection read
#[wasm_bindgen(js_name = readSelection)]
pub fn read_selection(&self, content: Option<String>, cut: bool) {
let message = ClipboardMessage::ReadSelection { content, cut };
self.dispatch(message);
}
/// Paste from a serialized JSON representation
#[wasm_bindgen(js_name = pasteText)]
pub fn paste_text(&self, data: String) {
let message = ClipboardMessage::ReadClipboard {
content: ClipboardContentRaw::Text(data),
};
self.dispatch(message);
}
/// Pastes an image
#[wasm_bindgen(js_name = pasteImage)]
pub fn paste_image(
&self,
name: Option<String>,
image_data: Vec<u8>,
width: u32,
height: u32,
mouse_x: Option<f64>,
mouse_y: Option<f64>,
insert_parent_id: Option<u64>,
insert_index: Option<usize>,
) {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
let message = PortfolioMessage::InsertImage {
name,
image,
mouse,
parent_and_insert_index,
};
self.dispatch(message);
}
/// Pastes an SVG given its string representation
#[wasm_bindgen(js_name = pasteSvg)]
pub fn paste_svg(&self, name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
let insert_parent_id = NodeId(insert_parent_id);
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
Some((parent, insert_index))
} else {
None
};
let message = PortfolioMessage::InsertSvg {
name,
svg,
mouse,
parent_and_insert_index,
};
self.dispatch(message);
}
/// Toggle visibility of a layer or node given its node ID
#[wasm_bindgen(js_name = toggleNodeVisibilityLayerPanel)]
pub fn toggle_node_visibility_layer(&self, id: u64) {
let node_id = NodeId(id);
let message = NodeGraphMessage::ToggleVisibility { node_id, network_path: Vec::new() };
self.dispatch(message);
}
/// Pin or unpin a node given its node ID
#[wasm_bindgen(js_name = setNodePinned)]
pub fn set_node_pinned(&self, id: u64, pinned: bool) {
self.dispatch(DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned });
}
/// Collapse or expand a node's section in the Properties panel
#[wasm_bindgen(js_name = toggleNodePropertiesSectionExpanded)]
pub fn toggle_node_properties_section_expanded(&self, id: u64) {
self.dispatch(DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) });
}
/// Delete a layer or node given its node ID
#[wasm_bindgen(js_name = deleteNode)]
pub fn delete_node(&self, id: u64) {
self.dispatch(DocumentMessage::DeleteNode { node_id: NodeId(id) });
}
/// Toggle lock state of a layer from the layer list
#[wasm_bindgen(js_name = toggleLayerLock)]
pub fn toggle_layer_lock(&self, node_id: u64) {
let message = NodeGraphMessage::ToggleLocked {
node_id: NodeId(node_id),
network_path: Vec::new(),
};
self.dispatch(message);
}
/// Toggle expansions state of a layer from the layer list
#[wasm_bindgen(js_name = toggleLayerExpansion)]
pub fn toggle_layer_expansion(&self, tree_path: &[u64], recursive: bool) {
let tree_path = tree_path.iter().map(|&id| NodeId(id)).collect();
let message = DocumentMessage::ToggleLayerExpansion { tree_path, recursive };
self.dispatch(message);
}
/// Set the active panel to the most recently clicked panel
#[wasm_bindgen(js_name = setActivePanel)]
pub fn set_active_panel(&self, panel: String) {
let message = DocumentMessage::SetActivePanel { active_panel: panel.into() };
self.dispatch(message);
}
/// Toggle display type for a layer
#[wasm_bindgen(js_name = setToNodeOrLayer)]
pub fn set_to_node_or_layer(&self, id: u64, is_layer: bool) {
self.dispatch(DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer });
}
/// Set the name of an import or export
#[wasm_bindgen(js_name = setImportName)]
pub fn set_import_name(&self, index: usize, name: String) {
let message = NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Import(index),
};
self.dispatch(message);
}
/// Set the name of an export
#[wasm_bindgen(js_name = setExportName)]
pub fn set_export_name(&self, index: usize, name: String) {
let message = NodeGraphMessage::SetImportExportName {
name,
index: ImportOrExport::Export(index),
};
self.dispatch(message);
} }
} }
+18 -23
View File
@@ -1,14 +1,18 @@
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
use crate::EDITOR; use crate::EDITOR;
#[cfg(not(feature = "native"))]
use crate::EDITOR_HAS_CRASHED;
use crate::EDITOR_WRAPPER;
use crate::editor_wrapper::EditorWrapper; use crate::editor_wrapper::EditorWrapper;
use crate::{EDITOR_HAS_CRASHED, EDITOR_WRAPPER}; use crate::native_communication::RasterizedImage;
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
use editor::application::Editor; use editor::application::Editor;
#[cfg(feature = "editor")]
use editor::messages::input_mapper::utility_types::input_keyboard::Key; use editor::messages::input_mapper::utility_types::input_keyboard::Key;
#[cfg(not(feature = "native"))]
use editor::messages::prelude::*; use editor::messages::prelude::*;
use graphene_std::color::SRGBA8;
use graphene_std::raster::Image;
use js_sys::{Object, Reflect}; use js_sys::{Object, Reflect};
#[cfg(not(feature = "native"))]
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
use std::time::Duration; use std::time::Duration;
use wasm_bindgen::JsCast; use wasm_bindgen::JsCast;
@@ -119,18 +123,8 @@ pub(crate) fn async_wake_callback() -> Wake {
}) })
} }
pub(crate) fn auto_save_all_documents() { /// Blits each rasterized image to a canvas registered on `window.imageCanvases`
// Process no further messages after a crash to avoid spamming the console pub(crate) fn render_image_data_to_canvases<'a>(image_data: impl IntoIterator<Item = &'a RasterizedImage>) {
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
return;
}
wrapper(|wrapper| {
wrapper.dispatch(PortfolioMessage::AutoSaveAllDocuments);
});
}
pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)]) {
let window = match window() { let window = match window() {
Some(window) => window, Some(window) => window,
None => { None => {
@@ -155,11 +149,13 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
}; };
let canvases_obj = Object::from(canvases_obj); let canvases_obj = Object::from(canvases_obj);
for (placeholder_id, image) in image_data.iter() { for image in image_data {
let (placeholder_id, width, height) = (image.id, image.width, image.height);
let pixels = image.pixels.as_slice();
let canvas_name = placeholder_id.to_string(); let canvas_name = placeholder_id.to_string();
let js_key = JsValue::from_str(&canvas_name); let js_key = JsValue::from_str(&canvas_name);
if Reflect::has(&canvases_obj, &js_key).unwrap_or(false) || image.width == 0 || image.height == 0 { if Reflect::has(&canvases_obj, &js_key).unwrap_or(false) || width == 0 || height == 0 {
continue; continue;
} }
@@ -169,8 +165,8 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
.dyn_into::<HtmlCanvasElement>() .dyn_into::<HtmlCanvasElement>()
.expect("Failed to cast element to HtmlCanvasElement"); .expect("Failed to cast element to HtmlCanvasElement");
canvas.set_width(image.width); canvas.set_width(width);
canvas.set_height(image.height); canvas.set_height(height);
let context: CanvasRenderingContext2d = canvas let context: CanvasRenderingContext2d = canvas
.get_context("2d") .get_context("2d")
@@ -178,10 +174,8 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
.expect("2d context was not found") .expect("2d context was not found")
.dyn_into::<CanvasRenderingContext2d>() .dyn_into::<CanvasRenderingContext2d>()
.expect("Failed to cast context to CanvasRenderingContext2d"); .expect("Failed to cast context to CanvasRenderingContext2d");
// `SRGBA8` is `#[repr(C)]` of four `u8`s, so the data buffer is already the byte format the canvas expects let clamped_pixels = wasm_bindgen::Clamped(pixels);
let u8_data: &[u8] = bytemuck::cast_slice(&image.data); match ImageData::new_with_u8_clamped_array_and_sh(clamped_pixels, width, height) {
let clamped_u8_data = wasm_bindgen::Clamped(u8_data);
match ImageData::new_with_u8_clamped_array_and_sh(clamped_u8_data, image.width, image.height) {
Ok(image_data_obj) => { Ok(image_data_obj) => {
if context.put_image_data(&image_data_obj, 0, 0).is_err() { if context.put_image_data(&image_data_obj, 0, 0).is_err() {
error!("Failed to put image data on canvas for id: {placeholder_id}"); error!("Failed to put image data on canvas for id: {placeholder_id}");
@@ -209,6 +203,7 @@ pub(crate) fn calculate_hash<T: std::hash::Hash>(t: &T) -> u64 {
} }
/// Translate a keyboard key from its JS name to its Rust `Key` enum /// Translate a keyboard key from its JS name to its Rust `Key` enum
#[cfg(feature = "editor")]
pub(crate) fn translate_key(name: &str) -> Key { pub(crate) fn translate_key(name: &str) -> Key {
use Key::*; use Key::*;
+69 -39
View File
@@ -4,11 +4,18 @@
#[macro_use] #[macro_use]
extern crate log; extern crate log;
pub mod editor_commands;
pub mod editor_wrapper; pub mod editor_wrapper;
pub mod helpers; pub mod helpers;
pub mod native_communication; pub mod native_communication;
mod wasm_value;
#[cfg(any(feature = "native", not(target_family = "wasm")))]
pub use editor_commands::EditorCommand;
#[cfg(feature = "editor")]
use crate::helpers::wrapper; use crate::helpers::wrapper;
#[cfg(feature = "editor")]
use editor::messages::prelude::*; use editor::messages::prelude::*;
use std::panic; use std::panic;
use std::sync::Mutex; use std::sync::Mutex;
@@ -24,6 +31,7 @@ pub static LOGGER: WasmLog = WasmLog;
thread_local! { thread_local! {
#[cfg(not(feature = "native"))] #[cfg(not(feature = "native"))]
pub static EDITOR: Mutex<Option<editor::application::Editor>> = const { Mutex::new(None) }; pub static EDITOR: Mutex<Option<editor::application::Editor>> = const { Mutex::new(None) };
#[cfg(not(feature = "native"))]
pub static MESSAGE_BUFFER: std::cell::RefCell<Vec<Message>> = const { std::cell::RefCell::new(Vec::new()) }; pub static MESSAGE_BUFFER: std::cell::RefCell<Vec<Message>> = const { std::cell::RefCell::new(Vec::new()) };
pub static EDITOR_WRAPPER: Mutex<Option<editor_wrapper::EditorWrapper>> = const { Mutex::new(None) }; pub static EDITOR_WRAPPER: Mutex<Option<editor_wrapper::EditorWrapper>> = const { Mutex::new(None) };
pub static PANIC_DIALOG_MESSAGE_CALLBACK: std::cell::RefCell<Option<js_sys::Function>> = const { std::cell::RefCell::new(None) }; pub static PANIC_DIALOG_MESSAGE_CALLBACK: std::cell::RefCell<Option<js_sys::Function>> = const { std::cell::RefCell::new(None) };
@@ -43,36 +51,41 @@ pub fn init_graphite() {
/// When a panic occurs, notify the user and log the error to the JS console before the backend dies /// When a panic occurs, notify the user and log the error to the JS console before the backend dies
pub fn panic_hook(info: &panic::PanicHookInfo) { pub fn panic_hook(info: &panic::PanicHookInfo) {
let info = info.to_string(); let info = info.to_string();
let backtrace = Error::new("stack").stack().to_string();
if backtrace.contains("DynAnyNode") {
log::error!("Node graph evaluation panicked {info}");
// When the graph panics, the node runtime lock may not be released properly // Node graph panics can only originate here when the node graph runs inside this wasm module
if editor::node_graph_executor::NODE_RUNTIME.try_lock().is_none() { #[cfg(feature = "editor")]
unsafe { editor::node_graph_executor::NODE_RUNTIME.force_unlock() }; {
let backtrace = Error::new("stack").stack().to_string();
if backtrace.contains("DynAnyNode") {
log::error!("Node graph evaluation panicked {info}");
// When the graph panics, the node runtime lock may not be released properly
if editor::node_graph_executor::NODE_RUNTIME.try_lock().is_none() {
unsafe { editor::node_graph_executor::NODE_RUNTIME.force_unlock() };
}
if !NODE_GRAPH_ERROR_DISPLAYED.load(Ordering::SeqCst) {
NODE_GRAPH_ERROR_DISPLAYED.store(true, Ordering::SeqCst);
wrapper(|wrapper| {
let error = r#"
<rect x="50%" y="50%" width="600" height="100" transform="translate(-300 -50)" rx="4" fill="var(--color-error-red)" />
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="18" fill="var(--color-2-mildblack)">
<tspan x="50%" dy="-24" font-weight="bold">The document crashed while being rendered in its current state.</tspan>
<tspan x="50%" dy="24">The editor is now unstable! Undo your last action to restore the artwork,</tspan>
<tspan x="50%" dy="24">then save your document and restart the editor before continuing work.</tspan>
/text>"#
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
.to_string();
wrapper.send_frontend_message_to_js(FrontendMessage::UpdateDocumentArtwork { svg: error });
});
}
return;
} }
if !NODE_GRAPH_ERROR_DISPLAYED.load(Ordering::SeqCst) {
NODE_GRAPH_ERROR_DISPLAYED.store(true, Ordering::SeqCst);
wrapper(|wrapper| {
let error = r#"
<rect x="50%" y="50%" width="600" height="100" transform="translate(-300 -50)" rx="4" fill="var(--color-error-red)" />
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="18" fill="var(--color-2-mildblack)">
<tspan x="50%" dy="-24" font-weight="bold">The document crashed while being rendered in its current state.</tspan>
<tspan x="50%" dy="24">The editor is now unstable! Undo your last action to restore the artwork,</tspan>
<tspan x="50%" dy="24">then save your document and restart the editor before continuing work.</tspan>
/text>"#
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
.to_string();
wrapper.send_frontend_message_to_js_rust_proxy(FrontendMessage::UpdateDocumentArtwork { svg: error });
});
}
return;
} else {
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
} }
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
log::error!("{info}"); log::error!("{info}");
// Prefer using the raw JS callback to avoid mutex lock contention inside the panic hook. // Prefer using the raw JS callback to avoid mutex lock contention inside the panic hook.
@@ -82,30 +95,20 @@ pub fn panic_hook(info: &panic::PanicHookInfo) {
} }
fn send_panic_dialog_via_callback(panic_info: String) -> Result<(), String> { fn send_panic_dialog_via_callback(panic_info: String) -> Result<(), String> {
let message = FrontendMessage::DisplayDialogPanic { panic_info }; let message = PanicDialogMessage::DisplayDialogPanic { panic_info: panic_info.clone() };
let message_type = message.to_discriminant().local_name();
let Ok(message_data) = serde_wasm_bindgen::to_value(&message) else { let Ok(message_data) = serde_wasm_bindgen::to_value(&message) else {
log::error!("Failed to serialize crash dialog panic message"); log::error!("Failed to serialize crash dialog panic message");
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
unreachable!("Message variant changed unexpectedly")
};
return Err(panic_info); return Err(panic_info);
}; };
PANIC_DIALOG_MESSAGE_CALLBACK.with(|callback| { PANIC_DIALOG_MESSAGE_CALLBACK.with(|callback| {
let callback_ref = callback.borrow(); let callback_ref = callback.borrow();
let Some(callback) = callback_ref.as_ref() else { let Some(callback) = callback_ref.as_ref() else {
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
unreachable!("Message variant changed unexpectedly")
};
return Err(panic_info); return Err(panic_info);
}; };
if let Err(error) = callback.call2(&JsValue::null(), &JsValue::from(message_type), &message_data) { if let Err(error) = callback.call2(&JsValue::null(), &JsValue::from("DisplayDialogPanic"), &message_data) {
log::error!("Failed to send crash dialog panic message to JS: {:?}", error); log::error!("Failed to send crash dialog panic message to JS: {error:?}");
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
unreachable!("Message variant changed unexpectedly")
};
return Err(panic_info); return Err(panic_info);
} }
@@ -201,3 +204,30 @@ impl log::Log for WasmLog {
fn flush(&self) {} fn flush(&self) {}
} }
#[cfg(feature = "editor")]
use editor::messages::prelude::FrontendMessage as PanicDialogMessage;
#[cfg(not(feature = "editor"))]
use PanicDialogMessageCopy as PanicDialogMessage;
#[cfg(any(not(feature = "editor"), test))]
#[derive(serde::Serialize)]
enum PanicDialogMessageCopy {
DisplayDialogPanic {
#[serde(rename = "panicInfo")]
panic_info: String,
},
}
#[cfg(all(test, feature = "editor"))]
mod tests {
use super::*;
#[test]
fn panic_dialog_copy_matches_editor_shape() {
let copy = serde_json::to_value(PanicDialogMessageCopy::DisplayDialogPanic { panic_info: "info".into() }).unwrap();
let real = serde_json::to_value(FrontendMessage::DisplayDialogPanic { panic_info: "info".into() }).unwrap();
assert_eq!(copy, real);
}
}
+96 -9
View File
@@ -1,25 +1,77 @@
use crate::editor_wrapper::EditorWrapper; //! Messaging with the native process. Serialized `FrontendMessage`s come in and are forwarded to JS,
use crate::helpers::wrapper; //! `EditorCommand`s go back out. Encoding and decoding both live here so the wire format stays in one place.
use editor::messages::prelude::FrontendMessage;
use crate::editor_wrapper::{EditorWrapper, IMAGE_DATA_HASH};
use crate::helpers::{calculate_hash, render_image_data_to_canvases, wrapper};
use crate::wasm_value::WasmValue;
use js_sys::{ArrayBuffer, Uint8Array}; use js_sys::{ArrayBuffer, Uint8Array};
use std::sync::atomic::Ordering;
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
#[wasm_bindgen(js_name = "receiveNativeMessage")] #[wasm_bindgen(js_name = "receiveNativeMessage")]
pub fn receive_native_message(buffer: ArrayBuffer) { pub fn receive_native_message(buffer: ArrayBuffer) {
let buffer = Uint8Array::new(buffer.as_ref()).to_vec(); let buffer = Uint8Array::new(buffer.as_ref()).to_vec();
match ron::from_str::<Vec<FrontendMessage>>(str::from_utf8(buffer.as_slice()).unwrap()) { match serde_json::from_slice::<Vec<(String, String)>>(&buffer) {
Ok(messages) => { Ok(messages) => {
let callback = move |wrapper: &mut EditorWrapper| { wrapper(move |wrapper: &mut EditorWrapper| {
for message in messages { for (name, data) in messages {
wrapper.send_frontend_message_to_js_rust_proxy(message); match name.as_str() {
"UpdateImageData" => {
let new_hash = calculate_hash(&data);
if IMAGE_DATA_HASH.swap(new_hash, Ordering::Relaxed) == new_hash {
continue;
}
match serde_json::from_str::<Vec<RasterizedImage>>(&data) {
Ok(image_data) => render_image_data_to_canvases(image_data.iter()),
Err(e) => error!("Failed to deserialize image data: {e:?}"),
}
}
_ => match serde_json::from_str::<WasmValue>(&data) {
Ok(value) => wrapper.forward_serialized_frontend_message_to_js(&name, value),
Err(e) => log::error!("Failed to deserialize frontend message {name}: {e:?}"),
},
}
} }
}; });
wrapper(callback);
} }
Err(e) => log::error!("Failed to deserialize frontend messages: {e:?}"), Err(e) => log::error!("Failed to deserialize frontend messages: {e:?}"),
} }
} }
#[cfg(feature = "editor")]
pub fn encode_frontend_messages(messages: Vec<editor::messages::prelude::FrontendMessage>) -> Option<Vec<u8>> {
use editor::messages::prelude::FrontendMessage;
use editor::utility_traits::{AsMessage, ToDiscriminant};
let messages: Vec<(String, String)> = messages
.into_iter()
.map(|message| {
let name = message.to_discriminant().local_name();
let data = match message {
FrontendMessage::UpdateImageData { image_data } => serde_json::to_string(&image_data).inspect_err(|e| log::error!("Failed to serialize {name} payload: {e}")).ok()?,
message => crate::wasm_value::encode(&message)
.inspect_err(|e| log::error!("Failed to serialize FrontendMessage {name}: {e}"))
.ok()?,
};
Some((name, data))
})
.collect::<Option<_>>()?;
serde_json::to_vec(&messages).ok()
}
#[cfg(all(feature = "editor", any(feature = "native", not(target_family = "wasm"))))]
pub fn decode_editor_command(data: &[u8]) -> Option<editor::messages::prelude::Message> {
match serde_json::from_slice::<crate::EditorCommand>(data) {
Ok(command) => Some(command.into()),
Err(e) => {
log::error!("Failed to deserialize editor command: {e}");
None
}
}
}
pub fn initialize_native_communication() { pub fn initialize_native_communication() {
let global = js_sys::global(); let global = js_sys::global();
@@ -44,3 +96,38 @@ pub fn send_message_to_cef(message: String) {
// Call it with argument // Call it with argument
func.call1(&JsValue::NULL, &JsValue::from(buffer)).expect("Function call failed"); func.call1(&JsValue::NULL, &JsValue::from(buffer)).expect("Function call failed");
} }
#[cfg(feature = "editor")]
pub(crate) use editor::messages::frontend::utility_types::RasterizedImage;
#[cfg(not(feature = "editor"))]
pub(crate) use RasterizedImageCopy as RasterizedImage;
#[cfg(any(not(feature = "editor"), test))]
#[derive(serde::Deserialize)]
pub(crate) struct RasterizedImageCopy {
pub(crate) id: u64,
pub(crate) width: u32,
pub(crate) height: u32,
pub(crate) pixels: Vec<u8>,
}
#[cfg(all(test, feature = "editor"))]
mod tests {
use super::*;
#[test]
fn rasterized_image_copy_matches_editor_shape() {
let editor_image = RasterizedImage {
id: 7,
width: 2,
height: 1,
pixels: serde_bytes::ByteBuf::from(vec![1, 2, 3, 4, 5, 6, 7, 8]),
};
let json = serde_json::to_string(&vec![editor_image]).unwrap();
let decoded: Vec<RasterizedImageCopy> = serde_json::from_str(&json).unwrap();
assert_eq!(decoded[0].id, 7);
assert_eq!((decoded[0].width, decoded[0].height), (2, 1));
assert_eq!(decoded[0].pixels, [1, 2, 3, 4, 5, 6, 7, 8]);
}
}
+448
View File
@@ -0,0 +1,448 @@
//! Serializable stand-in for `JsValue`, used to send `FrontendMessage`s from the native editor process to JS.
//! Keeps the types JSON can't represent (`BigInt`, `Uint8Array`, `Map`, `undefined`, `NaN`) so the wasm side
//! can reconstruct the same `JsValue`s that `serde_wasm_bindgen` produces on web.
use serde::{Deserialize, Serialize};
#[cfg(feature = "editor")]
use serde_json::Error;
use wasm_bindgen::JsValue;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) enum WasmValue {
Undefined,
Bool(bool),
Number(f64),
NonFinite(NonFinite),
Int(i64),
UInt(u64),
String(String),
Bytes(Vec<u8>),
Seq(Vec<WasmValue>),
Object(Vec<(String, WasmValue)>),
Map(Vec<(WasmValue, WasmValue)>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) enum NonFinite {
Nan,
PositiveInfinity,
NegativeInfinity,
}
impl From<NonFinite> for f64 {
fn from(value: NonFinite) -> Self {
match value {
NonFinite::Nan => f64::NAN,
NonFinite::PositiveInfinity => f64::INFINITY,
NonFinite::NegativeInfinity => f64::NEG_INFINITY,
}
}
}
impl From<WasmValue> for JsValue {
fn from(value: WasmValue) -> Self {
match value {
WasmValue::Undefined => JsValue::UNDEFINED,
WasmValue::Bool(value) => JsValue::from_bool(value),
WasmValue::Number(value) => JsValue::from_f64(value),
WasmValue::NonFinite(value) => JsValue::from_f64(value.into()),
WasmValue::Int(value) => JsValue::from(value),
WasmValue::UInt(value) => JsValue::from(value),
WasmValue::String(value) => JsValue::from_str(&value),
WasmValue::Bytes(bytes) => js_sys::Uint8Array::from(bytes.as_slice()).into(),
WasmValue::Seq(values) => {
let array = js_sys::Array::new();
for value in values {
array.push(&value.into());
}
array.into()
}
WasmValue::Object(fields) => {
let object = js_sys::Object::new();
for (key, value) in fields {
let _ = js_sys::Reflect::set(&object, &JsValue::from_str(&key), &value.into());
}
object.into()
}
WasmValue::Map(entries) => {
let map = js_sys::Map::new();
for (key, value) in entries {
map.set(&key.into(), &value.into());
}
map.into()
}
}
}
}
#[cfg(feature = "editor")]
pub(crate) fn encode<T: Serialize + ?Sized>(value: &T) -> Result<String, serde_json::Error> {
serde_json::to_string(&ser::to_value(value)?)
}
#[cfg(feature = "editor")]
mod ser {
use super::*;
use serde::ser::{self, Error as _};
pub(super) fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<WasmValue, Error> {
value.serialize(ValueSerializer)
}
struct ValueSerializer;
impl ser::Serializer for ValueSerializer {
type Ok = WasmValue;
type Error = Error;
type SerializeSeq = SeqSerializer;
type SerializeTuple = SeqSerializer;
type SerializeTupleStruct = SeqSerializer;
type SerializeTupleVariant = VariantSeqSerializer;
type SerializeMap = MapSerializer;
type SerializeStruct = ObjectSerializer;
type SerializeStructVariant = VariantObjectSerializer;
fn serialize_bool(self, v: bool) -> Result<WasmValue, Error> {
Ok(WasmValue::Bool(v))
}
fn serialize_i8(self, v: i8) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_i16(self, v: i16) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_i32(self, v: i32) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_i64(self, v: i64) -> Result<WasmValue, Error> {
Ok(WasmValue::Int(v))
}
fn serialize_i128(self, v: i128) -> Result<WasmValue, Error> {
if let Ok(v) = i64::try_from(v) {
Ok(WasmValue::Int(v))
} else {
u64::try_from(v)
.map(WasmValue::UInt)
.map_err(|_| Error::custom(format!("i128 value {v} exceeds the wire BigInt range")))
}
}
fn serialize_u8(self, v: u8) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_u16(self, v: u16) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_u32(self, v: u32) -> Result<WasmValue, Error> {
Ok(WasmValue::Number(v as f64))
}
fn serialize_u64(self, v: u64) -> Result<WasmValue, Error> {
Ok(WasmValue::UInt(v))
}
fn serialize_u128(self, v: u128) -> Result<WasmValue, Error> {
u64::try_from(v)
.map(WasmValue::UInt)
.map_err(|_| Error::custom(format!("u128 value {v} exceeds the wire BigInt range")))
}
fn serialize_f32(self, v: f32) -> Result<WasmValue, Error> {
self.serialize_f64(v as f64)
}
fn serialize_f64(self, v: f64) -> Result<WasmValue, Error> {
Ok(if v.is_finite() {
WasmValue::Number(v)
} else if v.is_nan() {
WasmValue::NonFinite(NonFinite::Nan)
} else if v > 0. {
WasmValue::NonFinite(NonFinite::PositiveInfinity)
} else {
WasmValue::NonFinite(NonFinite::NegativeInfinity)
})
}
fn serialize_char(self, v: char) -> Result<WasmValue, Error> {
Ok(WasmValue::String(v.to_string()))
}
fn serialize_str(self, v: &str) -> Result<WasmValue, Error> {
Ok(WasmValue::String(v.to_string()))
}
fn serialize_bytes(self, v: &[u8]) -> Result<WasmValue, Error> {
Ok(WasmValue::Bytes(v.to_vec()))
}
fn serialize_none(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Undefined)
}
fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<WasmValue, Error> {
value.serialize(self)
}
fn serialize_unit(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Undefined)
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<WasmValue, Error> {
Ok(WasmValue::Undefined)
}
fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str) -> Result<WasmValue, Error> {
Ok(WasmValue::String(variant.to_string()))
}
fn serialize_newtype_struct<T: Serialize + ?Sized>(self, _name: &'static str, value: &T) -> Result<WasmValue, Error> {
value.serialize(self)
}
fn serialize_newtype_variant<T: Serialize + ?Sized>(self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(vec![(variant.to_string(), value.serialize(ValueSerializer)?)]))
}
fn serialize_seq(self, len: Option<usize>) -> Result<SeqSerializer, Error> {
Ok(SeqSerializer(Vec::with_capacity(len.unwrap_or_default())))
}
fn serialize_tuple(self, len: usize) -> Result<SeqSerializer, Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<SeqSerializer, Error> {
self.serialize_seq(Some(len))
}
fn serialize_tuple_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result<VariantSeqSerializer, Error> {
Ok(VariantSeqSerializer {
variant,
elements: Vec::with_capacity(len),
})
}
fn serialize_map(self, len: Option<usize>) -> Result<MapSerializer, Error> {
Ok(MapSerializer {
entries: Vec::with_capacity(len.unwrap_or_default()),
pending_key: None,
})
}
fn serialize_struct(self, _name: &'static str, len: usize) -> Result<ObjectSerializer, Error> {
Ok(ObjectSerializer(Vec::with_capacity(len)))
}
fn serialize_struct_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result<VariantObjectSerializer, Error> {
Ok(VariantObjectSerializer {
variant,
fields: Vec::with_capacity(len),
})
}
}
struct SeqSerializer(Vec<WasmValue>);
impl ser::SerializeSeq for SeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
self.0.push(value.serialize(ValueSerializer)?);
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Seq(self.0))
}
}
impl ser::SerializeTuple for SeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<WasmValue, Error> {
ser::SerializeSeq::end(self)
}
}
impl ser::SerializeTupleStruct for SeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
ser::SerializeSeq::serialize_element(self, value)
}
fn end(self) -> Result<WasmValue, Error> {
ser::SerializeSeq::end(self)
}
}
struct VariantSeqSerializer {
variant: &'static str,
elements: Vec<WasmValue>,
}
impl ser::SerializeTupleVariant for VariantSeqSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
self.elements.push(value.serialize(ValueSerializer)?);
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(vec![(self.variant.to_string(), WasmValue::Seq(self.elements))]))
}
}
struct MapSerializer {
entries: Vec<(WasmValue, WasmValue)>,
pending_key: Option<WasmValue>,
}
impl ser::SerializeMap for MapSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<(), Error> {
self.pending_key = Some(key.serialize(ValueSerializer)?);
Ok(())
}
fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
let key = self.pending_key.take().ok_or_else(|| Error::custom("Map value serialized without a key"))?;
self.entries.push((key, value.serialize(ValueSerializer)?));
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Map(self.entries))
}
}
struct ObjectSerializer(Vec<(String, WasmValue)>);
impl ser::SerializeStruct for ObjectSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> {
self.0.push((key.to_string(), value.serialize(ValueSerializer)?));
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(self.0))
}
}
struct VariantObjectSerializer {
variant: &'static str,
fields: Vec<(String, WasmValue)>,
}
impl ser::SerializeStructVariant for VariantObjectSerializer {
type Ok = WasmValue;
type Error = Error;
fn serialize_field<T: Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> {
self.fields.push((key.to_string(), value.serialize(ValueSerializer)?));
Ok(())
}
fn end(self) -> Result<WasmValue, Error> {
Ok(WasmValue::Object(vec![(self.variant.to_string(), WasmValue::Object(self.fields))]))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::wasm_value::encode;
use serde::Serialize;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
enum TestMessage {
UnitVariant,
StructVariant {
#[serde(rename = "nodeId")]
node_id: u64,
width: u32,
scale: f64,
min: f64,
max: f64,
label: Option<String>,
widths: std::collections::BTreeMap<u64, u32>,
flags: Vec<bool>,
bytes: serde_bytes::ByteBuf,
},
}
#[test]
fn mirrors_serde_wasm_bindgen_representations() {
assert_eq!(to_value(&TestMessage::UnitVariant).unwrap(), WasmValue::String("unitVariant".into()));
let message = TestMessage::StructVariant {
node_id: u64::MAX,
width: 8,
scale: f64::NAN,
min: f64::NEG_INFINITY,
max: f64::INFINITY,
label: None,
widths: [(42, 7)].into(),
flags: vec![true, false],
bytes: serde_bytes::ByteBuf::from(vec![0, 255]),
};
let expected = WasmValue::Object(vec![(
"structVariant".into(),
WasmValue::Object(vec![
("nodeId".into(), WasmValue::UInt(u64::MAX)),
("width".into(), WasmValue::Number(8.)),
("scale".into(), WasmValue::NonFinite(NonFinite::Nan)),
("min".into(), WasmValue::NonFinite(NonFinite::NegativeInfinity)),
("max".into(), WasmValue::NonFinite(NonFinite::PositiveInfinity)),
("label".into(), WasmValue::Undefined),
("widths".into(), WasmValue::Map(vec![(WasmValue::UInt(42), WasmValue::Number(7.))])),
("flags".into(), WasmValue::Seq(vec![WasmValue::Bool(true), WasmValue::Bool(false)])),
("bytes".into(), WasmValue::Bytes(vec![0, 255])),
]),
)]);
assert_eq!(to_value(&message).unwrap(), expected);
}
#[test]
fn encode_decode_roundtrip() {
let message = TestMessage::StructVariant {
node_id: 1,
width: 2,
scale: f64::NAN,
min: f64::NEG_INFINITY,
max: 1.5,
label: Some("hi".into()),
widths: [(3, 4)].into(),
flags: vec![true],
bytes: serde_bytes::ByteBuf::from(vec![9]),
};
let json: &str = &encode(&message).unwrap();
let decoded: WasmValue = serde_json::from_str(json).unwrap();
assert_eq!(decoded, to_value(&message).unwrap());
}
}
}
+9 -4
View File
@@ -9,7 +9,7 @@ pub use graphene_application_io::ApplicationIo;
#[derive(Default)] #[derive(Default)]
pub struct PlatformApplicationIo { pub struct PlatformApplicationIo {
#[cfg(feature = "wgpu")] #[cfg(feature = "wgpu")]
gpu_executor: Option<WgpuExecutor>, gpu_executor: Option<std::sync::Arc<WgpuExecutor>>,
resources: Option<Box<dyn resource::LoadResource>>, resources: Option<Box<dyn resource::LoadResource>>,
} }
@@ -26,7 +26,7 @@ impl PlatformApplicationIo {
Self { Self {
#[cfg(feature = "wgpu")] #[cfg(feature = "wgpu")]
gpu_executor: executor, gpu_executor: executor.map(std::sync::Arc::new),
resources: None, resources: None,
} }
} }
@@ -39,7 +39,7 @@ impl PlatformApplicationIo {
set_wgpu_available(wgpu_available); set_wgpu_available(wgpu_available);
Self { Self {
gpu_executor: executor, gpu_executor: executor.map(std::sync::Arc::new),
resources: None, resources: None,
} }
} }
@@ -57,7 +57,12 @@ impl ApplicationIo for PlatformApplicationIo {
#[cfg(feature = "wgpu")] #[cfg(feature = "wgpu")]
fn gpu_executor(&self) -> Option<&Self::Executor> { fn gpu_executor(&self) -> Option<&Self::Executor> {
self.gpu_executor.as_ref() self.gpu_executor.as_deref()
}
#[cfg(feature = "wgpu")]
fn gpu_executor_arc(&self) -> Option<std::sync::Arc<Self::Executor>> {
self.gpu_executor.clone()
} }
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> { fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
+21 -3
View File
@@ -8,7 +8,6 @@ pub use core_types::uuid::generate_uuid;
use core_types::{Context, ContextDependencies, Cow, MemoHash, ProtoNodeIdentifier, Type}; use core_types::{Context, ContextDependencies, Cow, MemoHash, ProtoNodeIdentifier, Type};
use dyn_any::DynAny; use dyn_any::DynAny;
use glam::IVec2; use glam::IVec2;
use log::Metadata;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use std::collections::HashMap; use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher; use std::collections::hash_map::DefaultHasher;
@@ -215,12 +214,14 @@ impl InlineRust {
#[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
pub enum DocumentNodeMetadata { pub enum DocumentNodeMetadata {
DocumentNodePath, DocumentNodePath,
SourceId,
} }
impl DocumentNodeMetadata { impl DocumentNodeMetadata {
pub fn ty(&self) -> Type { pub fn ty(&self) -> Type {
match self { match self {
DocumentNodeMetadata::DocumentNodePath => concrete!(core_types::list::List<NodeId>), DocumentNodeMetadata::DocumentNodePath => concrete!(core_types::list::List<NodeId>),
DocumentNodeMetadata::SourceId => concrete!(u64),
} }
} }
} }
@@ -273,7 +274,7 @@ impl NodeInput {
NodeInput::Import { import_type, .. } => import_type.clone(), NodeInput::Import { import_type, .. } => import_type.clone(),
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"), NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"), NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
NodeInput::Reflection(_) => concrete!(Metadata), NodeInput::Reflection(metadata) => metadata.ty(),
} }
} }
@@ -879,7 +880,7 @@ impl NodeNetwork {
// Replace value inputs with dedicated value nodes // Replace value inputs with dedicated value nodes
if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) { if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) {
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id); Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id, Some(&mut node.context_features));
} }
let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else { let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else {
@@ -898,6 +899,7 @@ impl NodeNetwork {
gen_id, gen_id,
map_ids, map_ids,
id, id,
None,
); );
// Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node. // Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node.
@@ -978,6 +980,12 @@ impl NodeNetwork {
} }
} }
fn source_id_for_path(path: &[NodeId]) -> u64 {
let mut hasher = graphene_hash::FxHasher64::new();
path.hash(&mut hasher);
hasher.finish()
}
#[inline(never)] #[inline(never)]
fn replace_value_inputs_with_nodes( fn replace_value_inputs_with_nodes(
inputs: &mut [NodeInput], inputs: &mut [NodeInput],
@@ -986,6 +994,7 @@ impl NodeNetwork {
gen_id: impl Fn() -> NodeId + Copy, gen_id: impl Fn() -> NodeId + Copy,
map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy, map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy,
id: NodeId, id: NodeId,
mut context_features: Option<&mut ContextDependencies>,
) { ) {
// Replace value exports and imports with value nodes, added inside the nested network // Replace value exports and imports with value nodes, added inside the nested network
for export in inputs { for export in inputs {
@@ -996,6 +1005,13 @@ impl NodeNetwork {
NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed), NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed),
NodeInput::Reflection(reflect) => match reflect { NodeInput::Reflection(reflect) => match reflect {
DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(path.to_vec()).into(), false), DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(path.to_vec()).into(), false),
DocumentNodeMetadata::SourceId => {
let source_id = Self::source_id_for_path(path);
if let Some(context_features) = context_features.as_deref_mut() {
context_features.add_sources(&[source_id]);
}
(TaggedValue::U64(source_id).into(), false)
}
}, },
previous_export => { previous_export => {
*export = previous_export; *export = previous_export;
@@ -1208,7 +1224,9 @@ fn migrate_call_argument<'de, D: serde::Deserializer<'de>>(deserializer: D) -> R
Old(Option<Type>), Old(Option<Type>),
} }
// TODO: Eventually remove this migration document upgrade code
Ok(match CallArg::deserialize(deserializer)? { Ok(match CallArg::deserialize(deserializer)? {
CallArg::New(Type::Concrete(descriptor)) if descriptor.name.ends_with("OwnedContextImpl>>") => concrete!(Context),
CallArg::New(ty) => ty, CallArg::New(ty) => ty,
CallArg::Old(ty) => ty.unwrap_or_default(), CallArg::Old(ty) => ty.unwrap_or_default(),
}) })
+116 -43
View File
@@ -1,13 +1,18 @@
use super::DocumentNode; use super::DocumentNode;
use crate::application_io::PlatformEditorApi; use crate::application_io::PlatformEditorApi;
use crate::application_io::resource::Resource; use crate::application_io::resource::Resource;
use crate::proto::{Any as DAny, FutureAny}; use crate::proto::Any as DAny;
use brush_nodes::brush_stroke::BrushStroke; use brush_nodes::brush_stroke::BrushStroke;
use core_types::color::SRGBA8; use core_types::color::SRGBA8;
use core_types::context::Context;
use core_types::gpoll::GPoll;
use core_types::list::List; use core_types::list::List;
use core_types::node::Node;
use core_types::registry::{EdgeHandle, edge_type};
use core_types::transform::Footprint; use core_types::transform::Footprint;
use core_types::uuid::NodeId; use core_types::uuid::NodeId;
use core_types::{CacheHash, Color, ContextFeatures, MemoHash, Node, Type, TypeDescriptor}; use core_types::value::record_value_edge;
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
use dyn_any::DynAny; use dyn_any::DynAny;
pub use dyn_any::StaticType; pub use dyn_any::StaticType;
pub use glam::{DAffine2, DVec2, IVec2, UVec2}; pub use glam::{DAffine2, DVec2, IVec2, UVec2};
@@ -19,7 +24,6 @@ use graphic_types::{Artboard, Graphic, Vector};
use rendering::RenderMetadata; use rendering::RenderMetadata;
use std::fmt::Display; use std::fmt::Display;
use std::hash::Hash; use std::hash::Hash;
use std::marker::PhantomData;
use std::str::FromStr; use std::str::FromStr;
pub use std::sync::Arc; pub use std::sync::Arc;
use text_nodes::Font; use text_nodes::Font;
@@ -90,7 +94,7 @@ macro_rules! tagged_value {
DocumentNode(DocumentNode), DocumentNode(DocumentNode),
/// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`. /// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`.
#[serde(skip)] #[serde(skip)]
ContextFeatures(ContextFeatures), ContextModification(ContextModification),
#[serde(skip)] #[serde(skip)]
EditorApi(Arc<PlatformEditorApi>), EditorApi(Arc<PlatformEditorApi>),
/// Only used by the `resource` node, should never be serialized /// Only used by the `resource` node, should never be serialized
@@ -120,7 +124,7 @@ macro_rules! tagged_value {
// ======================= // =======================
Self::NodeIdPath(path) => path.hash(state), Self::NodeIdPath(path) => path.hash(state),
Self::DocumentNode(node) => node.cache_hash(state), Self::DocumentNode(node) => node.cache_hash(state),
Self::ContextFeatures(features) => features.cache_hash(state), Self::ContextModification(modification) => modification.cache_hash(state),
Self::RenderOutput(x) => x.cache_hash(state), Self::RenderOutput(x) => x.cache_hash(state),
Self::EditorApi(x) => x.cache_hash(state), Self::EditorApi(x) => x.cache_hash(state),
Self::ResourceHash(x) => x.cache_hash(state), Self::ResourceHash(x) => x.cache_hash(state),
@@ -175,7 +179,7 @@ macro_rules! tagged_value {
Box::new(list) Box::new(list)
} }
Self::DocumentNode(node) => Box::new(node), Self::DocumentNode(node) => Box::new(node),
Self::ContextFeatures(features) => Box::new(features), Self::ContextModification(modification) => Box::new(modification),
Self::EditorApi(x) => Box::new(x), Self::EditorApi(x) => Box::new(x),
Self::ResourceHash(x) => Box::new(x), Self::ResourceHash(x) => Box::new(x),
} }
@@ -225,7 +229,7 @@ macro_rules! tagged_value {
Arc::new(list) Arc::new(list)
} }
Self::DocumentNode(node) => Arc::new(node), Self::DocumentNode(node) => Arc::new(node),
Self::ContextFeatures(features) => Arc::new(features), Self::ContextModification(modification) => Arc::new(modification),
Self::EditorApi(x) => Arc::new(x), Self::EditorApi(x) => Arc::new(x),
Self::ResourceHash(x) => Arc::new(x), Self::ResourceHash(x) => Arc::new(x),
} }
@@ -253,12 +257,112 @@ macro_rules! tagged_value {
Self::RenderOutput(_) => concrete!(RenderOutput), Self::RenderOutput(_) => concrete!(RenderOutput),
Self::NodeIdPath(_) => concrete!(List<NodeId>), Self::NodeIdPath(_) => concrete!(List<NodeId>),
Self::DocumentNode(_) => concrete!(DocumentNode), Self::DocumentNode(_) => concrete!(DocumentNode),
Self::ContextFeatures(_) => concrete!(ContextFeatures), Self::ContextModification(_) => concrete!(ContextModification),
Self::EditorApi(_) => concrete!(&PlatformEditorApi), Self::EditorApi(_) => concrete!(Arc<PlatformEditorApi>),
Self::ResourceHash(_) => concrete!(ResourceHash), Self::ResourceHash(_) => concrete!(ResourceHash),
} }
} }
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a `ClonedNode` edge typed by [`Self::ty`].
pub fn to_edge(self) -> Result<EdgeHandle, String> {
match self {
// ===============
// MANUAL VARIANTS
// ===============
Self::None => Ok(record_value_edge(())),
Self::TypeDefault(td) => {
// Same direct-construction path as `to_dynany` for the same reason as in `to_dynany`.
let name = td.name.as_ref();
macro_rules! check {
($type_default:ty) => {
if name == std::any::type_name::<$type_default>() { return Ok(record_value_edge(<$type_default>::default())); }
};
}
for_each_type_default!(check);
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
}
Self::F64Array(values) => {
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
Ok(record_value_edge(list))
}
Self::Color(color) => {
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
Ok(record_value_edge(list))
}
Self::Gradient(stops) => Ok(record_value_edge(List::<GradientStops>::new_from_element(stops))),
Self::BrushStrokes(strokes) => {
let list: List<BrushStroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
Ok(record_value_edge(list))
}
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(x) => Ok(record_value_edge(x)), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
Self::RenderOutput(x) => Ok(record_value_edge(x)),
Self::NodeIdPath(path) => {
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
Ok(record_value_edge(list))
}
Self::DocumentNode(node) => Ok(record_value_edge(node)),
Self::ContextModification(modification) => Ok(record_value_edge(modification)),
Self::EditorApi(x) => Ok(record_value_edge(x)),
Self::ResourceHash(x) => Ok(record_value_edge(x)),
}
}
/// Evaluates a typed edge and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
pub fn from_edge(handle: EdgeHandle, ctx: &Context) -> Result<GPoll<Self>, String> {
let ty = handle.ty().clone();
// ===============
// MANUAL VARIANTS
// ===============
if ty == edge_type::<()>() {
return Ok(handle.downcast::<()>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(|_| TaggedValue::None));
}
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$(
if ty == edge_type::<$ty>() {
return Ok(handle.downcast::<$ty>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(TaggedValue::$identifier));
}
)*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
if ty == edge_type::<RenderOutput>() {
return Ok(handle.downcast::<RenderOutput>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(TaggedValue::RenderOutput));
}
// =======================
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
// =======================
if ty == core_types::registry::record_edge_type::<()>() {
return Ok(handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(|_| TaggedValue::None));
}
$(
if ty == core_types::registry::record_edge_type::<$ty>() {
let layout = handle.layout().ok_or_else(|| "a record edge must carry its layout".to_string())?.clone();
return Ok(handle
.downcast_record::<$ty>()
.map_err(|e| format!("{e:?}"))?
.eval(ctx)
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
}
)*
if ty == core_types::registry::record_edge_type::<RenderOutput>() {
let layout = handle.layout().ok_or_else(|| "a record edge must carry its layout".to_string())?.clone();
return Ok(handle
.downcast_record::<RenderOutput>()
.map_err(|e| format!("{e:?}"))?
.eval(ctx)
.map(|value| TaggedValue::RenderOutput(unsafe { core_types::record::read_element::<RenderOutput>(layout.rec(&value)) })));
}
Err(format!("Cannot convert edge of type {ty} to TaggedValue"))
}
/// Attempts to downcast the dynamic type to a tagged value /// Attempts to downcast the dynamic type to a tagged value
pub fn try_from_any(input: Box<dyn DynAny<'a> + 'a>) -> Result<Self, String> { pub fn try_from_any(input: Box<dyn DynAny<'a> + 'a>) -> Result<Self, String> {
use dyn_any::downcast; use dyn_any::downcast;
@@ -309,6 +413,7 @@ macro_rules! tagged_value {
pub fn from_type(input: &Type) -> Option<Self> { pub fn from_type(input: &Type) -> Option<Self> {
match input { match input {
Type::Generic(_) => None, Type::Generic(_) => None,
Type::Record(inner) => Self::from_type(inner),
Type::Concrete(concrete_type) => { Type::Concrete(concrete_type) => {
let name = concrete_type.name.as_ref(); let name = concrete_type.name.as_ref();
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types // TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
@@ -359,7 +464,7 @@ macro_rules! tagged_value {
Self::RenderOutput(_) => "RenderOutput".to_string(), Self::RenderOutput(_) => "RenderOutput".to_string(),
Self::NodeIdPath(path) => format!("NodeIdPath({path:?})"), Self::NodeIdPath(path) => format!("NodeIdPath({path:?})"),
Self::DocumentNode(node) => format!("DocumentNode({node:?})"), Self::DocumentNode(node) => format!("DocumentNode({node:?})"),
Self::ContextFeatures(features) => format!("ContextFeatures({features:?})"), Self::ContextModification(modification) => format!("ContextModification({modification:?})"),
Self::EditorApi(_) => "PlatformEditorApi".to_string(), Self::EditorApi(_) => "PlatformEditorApi".to_string(),
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"), Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
} }
@@ -569,6 +674,7 @@ impl TaggedValue {
match ty { match ty {
Type::Generic(_) => None, Type::Generic(_) => None,
Type::Record(_) => None,
Type::Concrete(concrete_type) => { Type::Concrete(concrete_type) => {
let ty = concrete_type.id?; let ty = concrete_type.id?;
use std::any::TypeId; use std::any::TypeId;
@@ -684,39 +790,6 @@ impl Display for TaggedValue {
} }
} }
pub struct UpcastNode {
value: MemoHash<TaggedValue>,
}
impl<'input> Node<'input, DAny<'input>> for UpcastNode {
type Output = FutureAny<'input>;
fn eval(&'input self, _: DAny<'input>) -> Self::Output {
let memo_clone = MemoHash::clone(&self.value);
Box::pin(async move { memo_clone.into_inner().as_ref().clone().to_dynany() })
}
}
impl UpcastNode {
pub fn new(value: MemoHash<TaggedValue>) -> Self {
Self { value }
}
}
#[derive(Default, Debug, Clone, Copy)]
pub struct UpcastAsRefNode<T: AsRef<U> + Sync + Send, U: Sync + Send>(pub T, PhantomData<U>);
impl<'i, T: 'i + AsRef<U> + Sync + Send, U: 'i + StaticType + Sync + Send> Node<'i, DAny<'i>> for UpcastAsRefNode<T, U> {
type Output = FutureAny<'i>;
#[inline(always)]
fn eval(&'i self, _: DAny<'i>) -> Self::Output {
Box::pin(async move { Box::new(self.0.as_ref()) as DAny<'i> })
}
}
impl<T: AsRef<U> + Sync + Send, U: Sync + Send> UpcastAsRefNode<T, U> {
pub const fn new(value: T) -> UpcastAsRefNode<T, U> {
UpcastAsRefNode(value, PhantomData)
}
}
#[derive(Debug, Clone, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)]
pub struct RenderOutput { pub struct RenderOutput {
pub data: RenderOutputType, pub data: RenderOutputType,
@@ -1,5 +1,5 @@
use crate::document::NodeNetwork; use crate::document::NodeNetwork;
use crate::proto::{LocalFuture, ProtoNetwork}; use crate::proto::ProtoNetwork;
use std::error::Error; use std::error::Error;
pub struct Compiler {} pub struct Compiler {}
@@ -33,5 +33,5 @@ impl Compiler {
} }
pub trait Executor<I, O> { pub trait Executor<I, O> {
fn execute(&self, input: I) -> LocalFuture<'_, Result<O, Box<dyn Error>>>; fn execute(&self, input: I) -> Result<O, Box<dyn Error>>;
} }
+210 -68
View File
@@ -258,6 +258,11 @@ impl ProtoNetwork {
self.replace_node_id(&outwards_edges, NodeId(index as u64), sni); self.replace_node_id(&outwards_edges, NodeId(index as u64), sni);
self.nodes[index].0 = sni; self.nodes[index].0 = sni;
} }
// Equal nodes hash to one id; the copies must go, or a pass that
// rewrites one of them (like adapter splicing) leaves the others stale.
let mut seen = HashSet::new();
self.nodes.retain(|(id, _)| seen.insert(*id));
} }
// TODO: Remove // TODO: Remove
@@ -294,6 +299,10 @@ impl ProtoNetwork {
(inwards_edges, id_map) (inwards_edges, id_map)
} }
pub fn source_ids(&self) -> Vec<SourceId> {
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources().iter().copied()).collect()
}
/// Inserts context nullification nodes to optimize caching. /// Inserts context nullification nodes to optimize caching.
/// This analysis is performed after topological sorting to ensure proper dependency tracking. /// This analysis is performed after topological sorting to ensure proper dependency tracking.
pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> { pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> {
@@ -308,7 +317,7 @@ impl ProtoNetwork {
Ok(()) Ok(())
} }
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextFeatures) -> NodeId { fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextModification) -> NodeId {
let (_, node) = &self.nodes[node_id.0 as usize]; let (_, node) = &self.nodes[node_id.0 as usize];
let mut path = node.original_location.path.clone(); let mut path = node.original_location.path.clone();
@@ -338,7 +347,7 @@ impl ProtoNetwork {
self.nodes.push(( self.nodes.push((
nullification_value_node_id, nullification_value_node_id,
ProtoNode { ProtoNode {
construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextFeatures(context_deps))), construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextModification(context_deps))),
call_argument: concrete!(Context), call_argument: concrete!(Context),
identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"), identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"),
original_location: OriginalLocation { original_location: OriginalLocation {
@@ -365,39 +374,43 @@ impl ProtoNetwork {
nullification_node_id nullification_node_id
} }
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextFeatures, Option<NodeId>) { fn find_context_dependencies(&mut self, id: NodeId) -> (ContextModification, Option<NodeId>) {
let mut branch_dependencies = Vec::new(); let mut branch_dependencies = Vec::new();
let mut combined_deps = ContextFeatures::default(); let mut combined_deps = ContextModification::default();
let node_index = id.0 as usize; let node_index = id.0 as usize;
let context_features = self.nodes[node_index].1.context_features; let (extract, inject, own_deps) = {
let dependencies = &self.nodes[node_index].1.context_features;
let own_deps = ContextModification::from_sources(dependencies.extract, dependencies.sources());
(dependencies.extract, dependencies.inject, own_deps)
};
let mut inputs = match &self.nodes[node_index].1.construction_args { let mut inputs = match &self.nodes[node_index].1.construction_args {
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached // We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
ConstructionArgs::Value(_) => return (context_features.extract, Some(id)), ConstructionArgs::Value(_) => return (own_deps, Some(id)),
ConstructionArgs::Nodes(items) => items.clone(), ConstructionArgs::Nodes(items) => items.clone(),
ConstructionArgs::Inline(_) => return (context_features.extract, Some(id)), ConstructionArgs::Inline(_) => return (own_deps, Some(id)),
}; };
// Compute the dependencies for each branch and combine all of them // Compute the dependencies for each branch and combine all of them
for &node in &inputs { for &node in &inputs {
let branch = self.find_context_dependencies(node); let branch = self.find_context_dependencies(node);
combined_deps |= &branch.0;
branch_dependencies.push(branch); branch_dependencies.push(branch);
combined_deps |= branch.0;
} }
let mut new_deps = combined_deps; let mut new_deps = combined_deps.clone();
// Remove requirements which this node provides // Remove requirements which this node provides
new_deps &= !context_features.inject; new_deps &= !inject;
// Add requirements we have // Add requirements we have
new_deps |= context_features.extract; new_deps |= own_deps;
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency // If we either introduce new dependencies, we can cache all children which don't yet need that dependency
let we_introduce_new_deps = !combined_deps.contains(new_deps); let we_introduce_new_deps = !combined_deps.contains(&new_deps);
// For diverging branches, we can add a cache node for all branches which don't reqire all dependencies // For diverging branches, we can add a cache node for all branches which don't reqire all dependencies
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies.into_iter()) { for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies) {
if let Some(new_id) = new_id { if let Some(new_id) = new_id {
*child_node = new_id; *child_node = new_id;
} else if we_introduce_new_deps || deps != combined_deps { } else if we_introduce_new_deps || deps != combined_deps {
@@ -407,18 +420,18 @@ impl ProtoNetwork {
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs); self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
// Which dependencies do we supply (and don't need ourselves)? // Which dependencies do we supply (and don't need ourselves)?
let net_injections = context_features.inject.difference(context_features.extract); let net_injections = inject.difference(extract);
// Which dependencies still need to be met after this node? // Which dependencies still need to be met after this node?
let remaining_deps_from_children = combined_deps.difference(net_injections); let remaining_deps_from_children = combined_deps.features.difference(net_injections);
// Do we satisfy any existing dependencies? // Do we satisfy any existing dependencies?
let we_supply_existing_deps = !combined_deps.difference(remaining_deps_from_children).is_empty(); let we_supply_existing_deps = !combined_deps.features.difference(remaining_deps_from_children).is_empty();
let mut new_id = None; let mut new_id = None;
if we_supply_existing_deps { if we_supply_existing_deps {
// Our set of context dependencies has shrunk so we can add a cache node after the current node // Our set of context dependencies has shrunk so we can add a cache node after the current node
new_id = Some(self.insert_context_nullification_node(id, new_deps)); new_id = Some(self.insert_context_nullification_node(id, new_deps.clone()));
} }
(new_deps, new_id) (new_deps, new_id)
@@ -545,6 +558,7 @@ pub enum GraphErrorType {
}, },
NoImplementations, NoImplementations,
NoConstructor, NoConstructor,
ConstructionFailed(String),
/// The `inputs` represents a formatted list of input indices corresponding to their types. /// The `inputs` represents a formatted list of input indices corresponding to their types.
/// Each element in `error_inputs` represents a valid `NodeIOTypes` implementation. /// Each element in `error_inputs` represents a valid `NodeIOTypes` implementation.
/// The inner Vec stores the inputs which need to be changed and what type each needs to be changed to. /// The inner Vec stores the inputs which need to be changed and what type each needs to be changed to.
@@ -565,6 +579,7 @@ impl Debug for GraphErrorType {
GraphErrorType::UnexpectedGenerics { index, inputs } => write!(f, "Generic inputs should not exist but found at {index}: {inputs:?}"), GraphErrorType::UnexpectedGenerics { index, inputs } => write!(f, "Generic inputs should not exist but found at {index}: {inputs:?}"),
GraphErrorType::NoImplementations => write!(f, "No implementations found"), GraphErrorType::NoImplementations => write!(f, "No implementations found"),
GraphErrorType::NoConstructor => write!(f, "No construct found for node"), GraphErrorType::NoConstructor => write!(f, "No construct found for node"),
GraphErrorType::ConstructionFailed(error) => write!(f, "Construction failed: {error}"),
GraphErrorType::InvalidImplementations { inputs, error_inputs } => { GraphErrorType::InvalidImplementations { inputs, error_inputs } => {
let format_error = |(index, (found, expected)): &(usize, (Type, Type))| { let format_error = |(index, (found, expected)): &(usize, (Type, Type))| {
let index = index + 1; let index = index + 1;
@@ -631,14 +646,14 @@ pub type GraphErrors = Vec<GraphError>;
/// The `TypingContext` is used to store the types of the nodes indexed by their stable node id. /// The `TypingContext` is used to store the types of the nodes indexed by their stable node id.
#[derive(Default, Clone, dyn_any::DynAny)] #[derive(Default, Clone, dyn_any::DynAny)]
pub struct TypingContext { pub struct TypingContext {
lookup: Cow<'static, HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>>, lookup: Cow<'static, HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>>,
inferred: HashMap<NodeId, NodeIOTypes>, inferred: HashMap<NodeId, NodeIOTypes>,
constructor: HashMap<NodeId, NodeConstructor>, constructor: HashMap<NodeId, NodeConstructor>,
} }
impl TypingContext { impl TypingContext {
/// Creates a new `TypingContext` with the given lookup table. /// Creates a new `TypingContext` with the given lookup table.
pub fn new(lookup: &'static HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>) -> Self { pub fn new(lookup: &'static HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>) -> Self {
Self { Self {
lookup: Cow::Borrowed(lookup), lookup: Cow::Borrowed(lookup),
..Default::default() ..Default::default()
@@ -648,8 +663,8 @@ impl TypingContext {
/// Updates the `TypingContext` with a given proto network. This will infer the types of the nodes /// Updates the `TypingContext` with a given proto network. This will infer the types of the nodes
/// and store them in the `inferred` field. The proto network has to be topologically sorted /// and store them in the `inferred` field. The proto network has to be topologically sorted
/// and contain fully resolved stable node ids. /// and contain fully resolved stable node ids.
pub fn update(&mut self, network: &ProtoNetwork) -> Result<(), GraphErrors> { pub fn update(&mut self, network: &mut ProtoNetwork) -> Result<(), GraphErrors> {
for (id, node) in network.nodes.iter() { for (id, node) in &network.nodes {
self.infer(*id, node)?; self.infer(*id, node)?;
} }
@@ -679,10 +694,10 @@ impl TypingContext {
} }
let inputs = match node.construction_args { let inputs = match node.construction_args {
// If the node has a value input we can infer the return type from it // A value node is a native record source, so it types as a record
// of its value.
ConstructionArgs::Value(ref v) => { ConstructionArgs::Value(ref v) => {
// TODO: This should return a reference to the value let types = NodeIOTypes::new(concrete!(Context), Type::Record(Box::new(v.ty())), vec![]);
let types = NodeIOTypes::new(concrete!(Context), Type::Future(Box::new(v.ty())), vec![]);
self.inferred.insert(node_id, types.clone()); self.inferred.insert(node_id, types.clone());
return Ok(types); return Ok(types);
} }
@@ -702,6 +717,7 @@ impl TypingContext {
// Get the node input type from the proto node declaration // Get the node input type from the proto node declaration
let call_argument = &node.call_argument; let call_argument = &node.call_argument;
let impls = self.lookup.get(&node.identifier).ok_or_else(|| vec![GraphError::new(node, GraphErrorType::NoImplementations)])?; let impls = self.lookup.get(&node.identifier).ok_or_else(|| vec![GraphError::new(node, GraphErrorType::NoImplementations)])?;
let candidates: Vec<(NodeIOTypes, NodeConstructor)> = impls.iter().map(|entry| (entry.io.clone(), entry.constructor)).collect();
if let Some(index) = inputs.iter().position(|p| { if let Some(index) = inputs.iter().position(|p| {
matches!(p, matches!(p,
@@ -710,55 +726,25 @@ impl TypingContext {
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs })]); return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs })]);
} }
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
fn valid_type(from: &Type, to: &Type) -> bool {
match (from, to) {
// Direct comparison of two concrete types.
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
// Check inner type for futures
(Type::Future(type1), Type::Future(type2)) => valid_type(type1, type2),
// Direct comparison of two function types.
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
// This allows us to supply anything to a function that is satisfied with `()`.
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
// TODO: Add proper generic counting which is not based on the name
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
// Reject unknown type relationships.
_ => false,
}
}
// List of all implementations that match the input types // List of all implementations that match the input types
let valid_output_types = impls let valid_output_types = candidates
.keys() .iter()
.filter(|node_io| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2))) .filter(|(node_io, _)| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// Attempt to substitute generic types with concrete types and save the list of results // Attempt to substitute generic types with concrete types and save the list of results
let substitution_results = valid_output_types let substitution_results = valid_output_types
.iter() .iter()
.map(|node_io| { .map(|(node_io, constructor)| {
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io) let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
.iter() .iter()
.map(|generic| check_generic(node_io, call_argument, &inputs, generic).map(|x| (generic.to_string(), x))) .map(|generic| check_generic(node_io, call_argument, &inputs, generic).map(|x| (generic.to_string(), x)))
.collect(); .collect();
generics_lookup.map(|generics_lookup| { generics_lookup.map(|generics_lookup| {
let orig_node_io = (*node_io).clone(); let mut new_node_io = node_io.clone();
let mut new_node_io = orig_node_io.clone();
replace_generics(&mut new_node_io, &generics_lookup); replace_generics(&mut new_node_io, &generics_lookup);
(new_node_io, orig_node_io) (new_node_io, *constructor)
}) })
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@@ -771,7 +757,7 @@ impl TypingContext {
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0); let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
let mut best_errors = usize::MAX; let mut best_errors = usize::MAX;
let mut error_inputs = Vec::new(); let mut error_inputs = Vec::new();
for node_io in impls.keys() { for (node_io, _) in &candidates {
// For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to. // For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to.
let current_errors = [call_argument] let current_errors = [call_argument]
.into_iter() .into_iter()
@@ -806,42 +792,72 @@ impl TypingContext {
.join("\n"); .join("\n");
Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })]) Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })])
} }
[(node_io, org_nio)] => { [(node_io, constructor)] => {
let node_io = node_io.clone(); let node_io = node_io.clone();
// Save the inferred type // Save the inferred type
self.inferred.insert(node_id, node_io.clone()); self.inferred.insert(node_id, node_io.clone());
self.constructor.insert(node_id, impls[org_nio]); self.constructor.insert(node_id, *constructor);
Ok(node_io) Ok(node_io)
} }
// If two types are available and one of them accepts () an input, always choose that one // If two types are available and one of them accepts () an input, always choose that one
[first, second] => { [first, second] => {
if first.0.call_argument != second.0.call_argument { if first.0.call_argument != second.0.call_argument {
for (node_io, orig_nio) in [first, second] { for (node_io, constructor) in [first, second] {
if node_io.call_argument != concrete!(()) { if node_io.call_argument != concrete!(()) {
continue; continue;
} }
// Save the inferred type // Save the inferred type
self.inferred.insert(node_id, node_io.clone()); self.inferred.insert(node_id, node_io.clone());
self.constructor.insert(node_id, impls[orig_nio]); self.constructor.insert(node_id, *constructor);
return Ok(node_io.clone()); return Ok(node_io.clone());
} }
} }
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", "); let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
let valid = valid_output_types.into_iter().cloned().collect(); let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })]) Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
} }
_ => { _ => {
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", "); let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
let valid = valid_output_types.into_iter().cloned().collect(); let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })]) Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
} }
} }
} }
} }
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
fn valid_type(from: &Type, to: &Type) -> bool {
match (from, to) {
// Direct comparison of two concrete types.
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
// Direct comparison of two function types.
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
// This allows us to supply anything to a function that is satisfied with `()`.
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
// A lend edge is substitutable exactly when the lent values are.
// A record edge is substitutable exactly when the elements are.
(Type::Record(in1), Type::Record(in2)) => valid_type(in1, in2),
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
// TODO: Add proper generic counting which is not based on the name
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
// Reject unknown type relationships.
_ => false,
}
}
/// Returns a list of all generic types used in the node /// Returns a list of all generic types used in the node
fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> { fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
let inputs = [&types.call_argument].into_iter().chain(types.inputs.iter().map(|x| x.nested_type())); let inputs = [&types.call_argument].into_iter().chain(types.inputs.iter().map(|x| x.nested_type()));
@@ -860,10 +876,23 @@ fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
/// Checks if a generic type can be substituted with a concrete type and returns the concrete type /// Checks if a generic type can be substituted with a concrete type and returns the concrete type
fn check_generic(types: &NodeIOTypes, input: &Type, parameters: &[Type], generic: &str) -> Result<Type, String> { fn check_generic(types: &NodeIOTypes, input: &Type, parameters: &[Type], generic: &str) -> Result<Type, String> {
fn record_element(ty: Option<&Type>) -> Option<&Type> {
match ty {
Some(Type::Record(inner)) => Some(inner.as_ref()),
_ => None,
}
}
let inputs = [(Some(&types.call_argument), Some(input))] let inputs = [(Some(&types.call_argument), Some(input))]
.into_iter() .into_iter()
.chain(types.inputs.iter().map(|x| x.fn_input()).zip(parameters.iter().map(|x| x.fn_input()))) .chain(types.inputs.iter().map(|x| x.fn_input()).zip(parameters.iter().map(|x| x.fn_input())))
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output()))); .chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())))
.chain(
types
.inputs
.iter()
.map(|x| record_element(x.fn_output()))
.zip(parameters.iter().map(|x| record_element(x.fn_output()))),
);
let concrete_inputs = inputs.filter(|(ni, _)| matches!(ni, Some(Type::Generic(input)) if generic == input)); let concrete_inputs = inputs.filter(|(ni, _)| matches!(ni, Some(Type::Generic(input)) if generic == input));
let mut outputs = concrete_inputs.flat_map(|(_, out)| out); let mut outputs = concrete_inputs.flat_map(|(_, out)| out);
let out_ty = outputs let out_ty = outputs
@@ -955,6 +984,81 @@ mod test {
); );
} }
#[test]
fn retain_filter_placement_on_source_free_branch() {
let mut network = source_branch_network(vec![1], vec![]);
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
let filters = nullification_filters(&network);
assert_eq!(filters.len(), 1, "only the source-free branch gets a filter");
let (filter_id, wrapped, retained) = &filters[0];
assert_eq!(wrapped, "source_b");
assert!(retained.is_empty(), "the source-free branch retains no sources");
let (source_a_id, _) = find_node(&network, "source_a");
let (_, join) = find_node(&network, "join");
let ConstructionArgs::Nodes(join_args) = &join.construction_args else {
panic!("join args must be nodes")
};
assert_eq!(join_args, &vec![source_a_id, *filter_id], "the source branch stays direct, the filter replaces the source-free branch");
}
#[test]
fn diverging_source_sets_filter_each_branch() {
let mut network = source_branch_network(vec![1], vec![2]);
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
let mut filters = nullification_filters(&network);
filters.sort_by(|(_, a, _), (_, b, _)| a.cmp(b));
let summary: Vec<_> = filters.iter().map(|(_, wrapped, retained)| (wrapped.as_str(), retained.as_slice())).collect();
assert_eq!(
summary,
vec![("source_a", &[1u64][..]), ("source_b", &[2u64][..])],
"each diverging branch is filtered down to its own source set"
);
}
#[test]
fn matching_source_sets_insert_no_filter() {
let mut network = source_branch_network(vec![1], vec![1]);
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
assert!(nullification_filters(&network).is_empty(), "equal branch source sets need no filter");
}
fn find_node<'a>(network: &'a ProtoNetwork, name: &str) -> (NodeId, &'a ProtoNode) {
network
.nodes
.iter()
.find(|(_, node)| node.identifier.as_str() == name)
.map(|(id, node)| (*id, node))
.unwrap_or_else(|| panic!("node {name} not found"))
}
fn nullification_filters(network: &ProtoNetwork) -> Vec<(NodeId, String, Vec<SourceId>)> {
let node = |id: NodeId| &network.nodes[id.0 as usize].1;
network
.nodes
.iter()
.filter(|(_, candidate)| candidate.identifier.as_str() == graphene_core::context_modification::context_modification::IDENTIFIER.as_str())
.map(|(id, candidate)| {
let ConstructionArgs::Nodes(args) = &candidate.construction_args else {
panic!("filter args must be nodes")
};
let ConstructionArgs::Nodes(memoized) = &node(args[0]).construction_args else {
panic!("filter memoize args must be nodes")
};
let ConstructionArgs::Value(value) = &node(args[1]).construction_args else {
panic!("filter payload must be a value")
};
let value::TaggedValue::ContextModification(modification) = &**value else {
panic!("filter payload must be a context modification")
};
(*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources().to_vec())
})
.collect()
}
fn test_network() -> ProtoNetwork { fn test_network() -> ProtoNetwork {
ProtoNetwork { ProtoNetwork {
inputs: vec![NodeId(10)], inputs: vec![NodeId(10)],
@@ -1011,6 +1115,44 @@ mod test {
} }
} }
fn source_branch_network(branch_a_sources: Vec<SourceId>, branch_b_sources: Vec<SourceId>) -> ProtoNetwork {
let branch = |name: &str, sources: Vec<SourceId>| ProtoNode {
identifier: ProtoNodeIdentifier::with_owned_string(name.to_string()),
call_argument: concrete!(()),
construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]),
context_features: ContextDependencies::from_sources(&sources),
..Default::default()
};
ProtoNetwork {
inputs: vec![],
output: NodeId(3),
nodes: [
(
NodeId(0),
ProtoNode {
identifier: ProtoNodeIdentifier::new("value"),
call_argument: concrete!(()),
construction_args: ConstructionArgs::Value(value::TaggedValue::U32(2).into()),
..Default::default()
},
),
(NodeId(1), branch("source_a", branch_a_sources)),
(NodeId(2), branch("source_b", branch_b_sources)),
(
NodeId(3),
ProtoNode {
identifier: ProtoNodeIdentifier::new("join"),
call_argument: concrete!(()),
construction_args: ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]),
..Default::default()
},
),
]
.into_iter()
.collect(),
}
}
fn test_network_with_cycles() -> ProtoNetwork { fn test_network_with_cycles() -> ProtoNetwork {
ProtoNetwork { ProtoNetwork {
inputs: vec![NodeId(1)], inputs: vec![NodeId(1)],
+37 -9
View File
@@ -1,15 +1,40 @@
use futures::executor::block_on;
use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2}; use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2};
use graph_craft::graphene_compiler::Executor; use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::core_types::ops::Convert; use graphene_std::core_types::gpoll::GPoll;
use graphene_std::core_types::ops::ConvertAsync;
use graphene_std::core_types::transform::Footprint; use graphene_std::core_types::transform::Footprint;
use graphene_std::raster_types::{CPU, GPU, Raster}; use graphene_std::raster_types::{CPU, GPU, Raster};
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
use std::error::Error; use std::error::Error;
use std::io::Cursor; use std::io::Cursor;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::mpsc::Receiver;
use std::time::Duration; use std::time::Duration;
const SOURCE_COMPLETION_TIMEOUT: Duration = Duration::from_secs(30);
fn execute_until_final(executor: &DynamicExecutor, render_config: RenderConfig, completion: &Receiver<()>) -> Result<TaggedValue, Box<dyn Error>> {
loop {
while completion.try_recv().is_ok() {}
match executor.execute(render_config)? {
GPoll::Final(value) => return Ok(value),
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
log::warn!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
return Ok(value);
}
GPoll::Partial(_) | GPoll::Pending => {
completion
.recv_timeout(SOURCE_COMPLETION_TIMEOUT)
.map_err(|_| format!("Timed out after {}s waiting for async sources to complete", SOURCE_COMPLETION_TIMEOUT.as_secs()))?;
}
GPoll::Error(error) => return Err(format!("Node graph evaluation failed: {error:?}").into()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileType { pub enum FileType {
Svg, Svg,
@@ -28,14 +53,16 @@ pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
} }
} }
pub async fn export_document( #[allow(clippy::too_many_arguments)]
pub fn export_document(
executor: &DynamicExecutor, executor: &DynamicExecutor,
wgpu_executor: &wgpu_executor::WgpuExecutor, wgpu_executor: wgpu_executor::WgpuExecutorHandle,
output_path: PathBuf, output_path: PathBuf,
file_type: FileType, file_type: FileType,
scale: f64, scale: f64,
(width, height): (Option<u32>, Option<u32>), (width, height): (Option<u32>, Option<u32>),
transparent: bool, transparent: bool,
completion: &Receiver<()>,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
// Determine export format based on file type // Determine export format based on file type
let export_format = match file_type { let export_format = match file_type {
@@ -57,7 +84,7 @@ pub async fn export_document(
} }
// Execute the graph // Execute the graph
let result = executor.execute(render_config).await?; let result = execute_until_final(executor, render_config, completion)?;
// Handle the result based on output type // Handle the result based on output type
match result { match result {
@@ -70,7 +97,7 @@ pub async fn export_document(
RenderOutputType::Texture(texture) => { RenderOutputType::Texture(texture) => {
// Convert GPU texture to CPU buffer // Convert GPU texture to CPU buffer
let gpu_raster = Raster::<GPU>::new_gpu(texture); let gpu_raster = Raster::<GPU>::new_gpu(texture);
let cpu_raster: Raster<CPU> = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await; let cpu_raster: Raster<CPU> = block_on(gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()));
let (data, width, height) = cpu_raster.to_flat_u8(); let (data, width, height) = cpu_raster.to_flat_u8();
// Encode and write raster image // Encode and write raster image
@@ -149,13 +176,14 @@ impl AnimationParams {
} }
/// Export an animated GIF by rendering multiple frames at different animation times /// Export an animated GIF by rendering multiple frames at different animation times
pub async fn export_gif( pub fn export_gif(
executor: &DynamicExecutor, executor: &DynamicExecutor,
wgpu_executor: &wgpu_executor::WgpuExecutor, wgpu_executor: wgpu_executor::WgpuExecutorHandle,
output_path: PathBuf, output_path: PathBuf,
scale: f64, scale: f64,
(width, height): (Option<u32>, Option<u32>), (width, height): (Option<u32>, Option<u32>),
animation: AnimationParams, animation: AnimationParams,
completion: &Receiver<()>,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
use image::codecs::gif::{GifEncoder, Repeat}; use image::codecs::gif::{GifEncoder, Repeat};
use image::{Frame, RgbaImage}; use image::{Frame, RgbaImage};
@@ -195,14 +223,14 @@ pub async fn export_gif(
} }
// Execute the graph for this frame // Execute the graph for this frame
let result = executor.execute(render_config).await?; let result = execute_until_final(executor, render_config, completion)?;
// Extract RGBA data from result // Extract RGBA data from result
let (data, img_width, img_height) = match result { let (data, img_width, img_height) = match result {
TaggedValue::RenderOutput(output) => match output.data { TaggedValue::RenderOutput(output) => match output.data {
RenderOutputType::Texture(texture) => { RenderOutputType::Texture(texture) => {
let gpu_raster = Raster::<GPU>::new_gpu(texture); let gpu_raster = Raster::<GPU>::new_gpu(texture);
let cpu_raster: Raster<CPU> = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await; let cpu_raster: Raster<CPU> = block_on(gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()));
cpu_raster.to_flat_u8() cpu_raster.to_flat_u8()
} }
RenderOutputType::Buffer { data, width, height } => (data, width, height), RenderOutputType::Buffer { data, width, height } => (data, width, height),
+48 -15
View File
@@ -7,13 +7,13 @@ use document_format::{GddV1, GddV1Layout};
use fern::colors::{Color, ColoredLevelConfig}; use fern::colors::{Color, ColoredLevelConfig};
use futures::executor::block_on; use futures::executor::block_on;
use graph_craft::application_io::EditorPreferences; use graph_craft::application_io::EditorPreferences;
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::*; use graph_craft::document::*;
use graph_craft::graphene_compiler::Compiler; use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::ProtoNetwork; use graph_craft::proto::ProtoNetwork;
use graph_craft::util::load_network; use graph_craft::util::load_network;
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender}; use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope; use interpreted_executor::util::wrap_network_in_scope;
use std::error::Error; use std::error::Error;
@@ -28,6 +28,35 @@ impl NodeGraphUpdateSender for UpdateLogger {
} }
} }
struct TokioSpawner(Option<tokio::runtime::Runtime>);
impl TokioSpawner {
fn new() -> Result<Self, std::io::Error> {
Ok(Self(Some(tokio::runtime::Runtime::new()?)))
}
}
impl Spawner for TokioSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
let runtime = self.0.as_ref().expect("runtime lives until drop");
let _guard = runtime.enter();
if poll_once(&mut task) {
return true;
}
runtime.spawn(task);
false
}
}
/// Dropping a tokio runtime blocks on its tasks, which panics inside the async main; shut down in the background instead.
impl Drop for TokioSpawner {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
}
}
}
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap(name = "graphene-cli", version)] #[clap(name = "graphene-cli", version)]
pub struct App { pub struct App {
@@ -101,8 +130,7 @@ struct GlobalOpts {
verbose: u8, verbose: u8,
} }
#[tokio::main] fn main() -> Result<(), Box<dyn Error>> {
async fn main() -> Result<(), Box<dyn Error>> {
let app = App::parse(); let app = App::parse();
let log_level = app.global_opts.verbose; let log_level = app.global_opts.verbose;
@@ -130,9 +158,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let gdd = if is_gdd { let gdd = if is_gdd {
let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?; let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
let container = AnyContainer::Memory(MemoryBackend::new()); let container = AnyContainer::Memory(MemoryBackend::new());
let gdd = document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout) let gdd = block_on(document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)).map_err(|error| format!("Failed to open document: {error}"))?;
.await
.map_err(|error| format!("Failed to open document: {error}"))?;
Some(gdd) Some(gdd)
} else { } else {
None None
@@ -140,7 +166,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
if let Command::ExtractLegacyDoc { ref document } = app.command { if let Command::ExtractLegacyDoc { ref document } = app.command {
let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) }; let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) };
let Some(legacy_doc) = gdd.read_legacy_document().await else { let Some(legacy_doc) = block_on(gdd.read_legacy_document()) else {
return Err("gdd file did not contain a legacy .graphite document".into()); return Err("gdd file did not contain a legacy .graphite document".into());
}; };
let mut new_path = document.clone(); let mut new_path = document.clone();
@@ -153,7 +179,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document. // Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document.
let node_network = match &gdd { let node_network = match &gdd {
Some(gdd) => { Some(gdd) => {
let declarations = gdd.declarations(gdd).await; let declarations = block_on(gdd.declarations(gdd));
let (node_network, _metadata) = gdd.registry().to_runtime_with_metadata(&declarations)?; let (node_network, _metadata) = gdd.registry().to_runtime_with_metadata(&declarations)?;
node_network node_network
} }
@@ -164,7 +190,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
}; };
log::info!("Creating GPU context"); log::info!("Creating GPU context");
let mut application_io = PlatformApplicationIo::new().await; let mut application_io = block_on(PlatformApplicationIo::new());
if let Some(gdd) = &gdd { if let Some(gdd) = &gdd {
application_io.inject_resource_proxy(Box::new(gdd.resource_proxy())); application_io.inject_resource_proxy(Box::new(gdd.resource_proxy()));
} }
@@ -176,16 +202,22 @@ async fn main() -> Result<(), Box<dyn Error>> {
let application_io_for_api = application_io_arc.clone(); let application_io_for_api = application_io_arc.clone();
// Get reference to wgpu executor and clone device handle // Get reference to wgpu executor and clone device handle
let wgpu_executor_ref = application_io_arc.gpu_executor().unwrap(); let wgpu_executor_ref = wgpu_executor::WgpuExecutorHandle(application_io_arc.gpu_executor_arc().unwrap());
let device = wgpu_executor_ref.context().device.clone(); let device = wgpu_executor_ref.context().device.clone();
let preferences = EditorPreferences { let preferences = EditorPreferences {
max_render_region_size: EditorPreferences::default().max_render_region_size, max_render_region_size: EditorPreferences::default().max_render_region_size,
}; };
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()?) as Box<DynSpawner>));
let (completion_sender, completion_receiver) = std::sync::mpsc::channel();
graph_runtime.set_notifier(Arc::new(move || {
let _ = completion_sender.send(());
}));
let editor_api = Arc::new(PlatformEditorApi { let editor_api = Arc::new(PlatformEditorApi {
application_io: Some(application_io_for_api), application_io: Some(application_io_for_api),
node_graph_message_sender: Box::new(UpdateLogger {}), node_graph_message_sender: Box::new(UpdateLogger {}),
editor_preferences: Box::new(preferences), editor_preferences: Box::new(preferences),
runtime: RuntimeHandle(graph_runtime.clone()),
}); });
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref())?; let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref())?;
@@ -218,7 +250,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let file_type = export::detect_file_type(&output)?; let file_type = export::detect_file_type(&output)?;
// Create executor // Create executor
let executor = create_executor(proto_graph)?; let executor = create_executor(proto_graph, graph_runtime)?;
if fps <= 0. { if fps <= 0. {
return Err("Fps number must be positive".into()); return Err("Fps number must be positive".into());
@@ -227,9 +259,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Perform export based on file type // Perform export based on file type
if file_type == export::FileType::Gif { if file_type == export::FileType::Gif {
let animation = export::AnimationParams::new(fps, frames, duration); let animation = export::AnimationParams::new(fps, frames, duration);
export::export_gif(&executor, wgpu_executor_ref, output, scale, (width, height), animation).await?; export::export_gif(&executor, wgpu_executor_ref.clone(), output, scale, (width, height), animation, &completion_receiver)?;
} else { } else {
export::export_document(&executor, wgpu_executor_ref, output, file_type, scale, (width, height), transparent).await?; export::export_document(&executor, wgpu_executor_ref.clone(), output, file_type, scale, (width, height), transparent, &completion_receiver)?;
} }
} }
_ => unreachable!("All other commands should be handled before this match statement is run"), _ => unreachable!("All other commands should be handled before this match statement is run"),
@@ -285,7 +317,8 @@ fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd:
compiler.compile_single(network).map_err(|x| x.into()) compiler.compile_single(network).map_err(|x| x.into())
} }
fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> { fn create_executor(proto_network: ProtoNetwork, runtime: Arc<DynGraphRuntime>) -> Result<DynamicExecutor, Box<dyn Error>> {
let executor = block_on(DynamicExecutor::new(proto_network)).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?; let mut executor = DynamicExecutor::new(proto_network).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?;
executor.set_runtime(runtime);
Ok(executor) Ok(executor)
} }
@@ -1,6 +1,5 @@
use criterion::BenchmarkGroup; use criterion::BenchmarkGroup;
use criterion::measurement::Measurement; use criterion::measurement::Measurement;
use futures::executor::block_on;
use graph_craft::proto::ProtoNetwork; use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile, load_from_name}; use graph_craft::util::{DEMO_ART, compile, load_from_name};
use graphene_std::application_io::EditorApi; use graphene_std::application_io::EditorApi;
@@ -14,10 +13,12 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let preprocessor = preprocessor::Preprocessor::new(); let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap(); preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network); let proto_network = compile(network);
let executor = block_on(DynamicExecutor::new(proto_network.clone())).unwrap(); let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
(executor, proto_network) (executor, proto_network)
} }
// Some benches in this module's include set drive the demos themselves.
#[allow(dead_code)]
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F) pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
where where
F: Fn(&str, &mut BenchmarkGroup<M>), F: Fn(&str, &mut BenchmarkGroup<M>),
@@ -2,6 +2,7 @@ mod benchmark_util;
use benchmark_util::{bench_for_each_demo, setup_network}; use benchmark_util::{bench_for_each_demo, setup_network};
use criterion::{Criterion, criterion_group, criterion_main}; use criterion::{Criterion, criterion_group, criterion_main};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig; use graphene_std::application_io::RenderConfig;
fn subsequent_evaluations(c: &mut Criterion) { fn subsequent_evaluations(c: &mut Criterion) {
@@ -9,9 +10,7 @@ fn subsequent_evaluations(c: &mut Criterion) {
let context = RenderConfig::default(); let context = RenderConfig::default();
bench_for_each_demo(&mut group, |name, g| { bench_for_each_demo(&mut group, |name, g| {
let (executor, _) = setup_network(name); let (executor, _) = setup_network(name);
g.bench_function(name, |b| { g.bench_function(name, |b| b.iter(|| Executor::execute(&&executor, std::hint::black_box(context)).unwrap()));
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap())
});
}); });
group.finish(); group.finish();
} }
@@ -1,6 +1,7 @@
mod benchmark_util; mod benchmark_util;
use benchmark_util::setup_network; use benchmark_util::setup_network;
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig; use graphene_std::application_io::RenderConfig;
use gungraun::prelude::*; use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -11,7 +12,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
// Warm up the cache by running once // Warm up the cache by running once
let context = RenderConfig::default(); let context = RenderConfig::default();
let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context)); let _ = Executor::execute(&&executor, context);
executor executor
} }
@@ -20,7 +21,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)] #[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor { pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
let context = RenderConfig::default(); let context = RenderConfig::default();
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap()); black_box(Executor::execute(&&executor, black_box(context)).unwrap());
// Return the executor so its teardown happens outside the measured section // Return the executor so its teardown happens outside the measured section
executor executor
@@ -9,14 +9,11 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) { fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let network = load_from_name(name); let network = load_from_name(name);
let proto_network = compile(network); let proto_network = compile(network);
let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
c.bench_function(name, |b| { c.bench_function(name, |b| {
b.iter_batched( b.iter_batched(
|| (executor.clone(), proto_network.clone()), || (DynamicExecutor::new(ProtoNetwork::default()).unwrap(), proto_network.clone()),
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))), |(mut executor, network)| executor.update(std::hint::black_box(network)),
criterion::BatchSize::SmallInput, criterion::BatchSize::SmallInput,
) )
}); });
@@ -33,10 +30,10 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let network = load_from_name(name); let network = load_from_name(name);
let proto_network = compile(network); let proto_network = compile(network);
let executor = futures::executor::block_on(DynamicExecutor::new(proto_network)).unwrap(); let executor = DynamicExecutor::new(proto_network).unwrap();
let footprint = Footprint::default(); let footprint = Footprint::default();
c.bench_function(name, |b| b.iter(|| futures::executor::block_on((&executor).execute(footprint)))); c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
} }
fn run_once_demo(c: &mut Criterion) { fn run_once_demo(c: &mut Criterion) {
let mut g = c.benchmark_group("Run Once no render"); let mut g = c.benchmark_group("Run Once no render");
@@ -2,6 +2,7 @@ mod benchmark_util;
use benchmark_util::{bench_for_each_demo, setup_network}; use benchmark_util::{bench_for_each_demo, setup_network};
use criterion::{Criterion, criterion_group, criterion_main}; use criterion::{Criterion, criterion_group, criterion_main};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig; use graphene_std::application_io::RenderConfig;
fn run_once(c: &mut Criterion) { fn run_once(c: &mut Criterion) {
@@ -11,7 +12,7 @@ fn run_once(c: &mut Criterion) {
g.bench_function(name, |b| { g.bench_function(name, |b| {
b.iter_batched( b.iter_batched(
|| setup_network(name), || setup_network(name),
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap(), |(executor, _)| Executor::execute(&&executor, std::hint::black_box(context)).unwrap(),
criterion::BatchSize::SmallInput, criterion::BatchSize::SmallInput,
) )
}); });
@@ -1,6 +1,7 @@
mod benchmark_util; mod benchmark_util;
use benchmark_util::setup_network; use benchmark_util::setup_network;
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io; use graphene_std::application_io;
use gungraun::prelude::*; use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -15,7 +16,7 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)] #[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor { pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
let context = application_io::RenderConfig::default(); let context = application_io::RenderConfig::default();
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap()); black_box(Executor::execute(&&executor, black_box(context)).unwrap());
// Return the executor so its teardown happens outside the measured section // Return the executor so its teardown happens outside the measured section
executor executor
@@ -13,10 +13,10 @@ fn update_executor(c: &mut Criterion) {
|| { || {
let (_, proto_network) = setup_network(name); let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default(); let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap(); let executor = DynamicExecutor::new(empty).unwrap();
(executor, proto_network) (executor, proto_network)
}, },
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))), |(mut executor, network)| executor.update(std::hint::black_box(network)),
criterion::BatchSize::SmallInput, criterion::BatchSize::SmallInput,
) )
}); });
@@ -9,7 +9,7 @@ use std::hint::black_box;
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) { fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let (_, proto_network) = setup_network(name); let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default(); let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap(); let executor = DynamicExecutor::new(empty).unwrap();
(executor, proto_network) (executor, proto_network)
} }
@@ -17,7 +17,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)] #[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor { pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
let (mut executor, network) = setup; let (mut executor, network) = setup;
let _ = black_box(futures::executor::block_on(executor.update(black_box(network)))); let _ = black_box(executor.update(black_box(network)));
// Return the executor so its teardown happens outside the measured section // Return the executor so its teardown happens outside the measured section
executor executor
@@ -1,17 +1,30 @@
use crate::node_registry; use crate::node_registry;
use dyn_any::StaticType; use core_types::arena::Arena;
use core_types::context::{ContextImpl, DynSlot, EvalScope, VarArg, VarArgLink, VarArgSlots};
use core_types::gpoll::GPoll;
use core_types::node::Node;
use core_types::registry::{EdgeHandle, ErasedNode};
use core_types::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner};
use graph_craft::Type; use graph_craft::Type;
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use graph_craft::document::value::{TaggedValue, UpcastAsRefNode, UpcastNode}; use graph_craft::document::value::TaggedValue;
use graph_craft::graphene_compiler::Executor; use graph_craft::graphene_compiler::Executor;
use graph_craft::proto::{ConstructionArgs, GraphError, LocalFuture, NodeContainer, ProtoNetwork, ProtoNode, SharedNodeContainer, TypeErasedBox, TypingContext}; use graph_craft::proto::{ConstructionArgs, GraphError, ProtoNetwork, ProtoNode, TypingContext};
use graph_craft::proto::{GraphErrorType, GraphErrors}; use graph_craft::proto::{GraphErrorType, GraphErrors};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::error::Error; use std::error::Error;
use std::sync::Arc; use std::sync::{Arc, Mutex, PoisonError};
const ARENA_CAPACITY: usize = 1 << 20;
fn new_arena() -> Arena {
Arena::new(ARENA_CAPACITY).unwrap_or_else(|| {
log::error!("arena generations exhausted; continuing without frame caching");
Arena::parked()
})
}
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`. /// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
#[derive(Clone)]
pub struct DynamicExecutor { pub struct DynamicExecutor {
output: NodeId, output: NodeId,
/// Stores all of the dynamic node structs. /// Stores all of the dynamic node structs.
@@ -20,6 +33,13 @@ pub struct DynamicExecutor {
typing_context: TypingContext, typing_context: TypingContext,
// This allows us to keep the nodes around for one more frame which is used for introspection // This allows us to keep the nodes around for one more frame which is used for introspection
orphaned_nodes: HashSet<NodeId>, orphaned_nodes: HashSet<NodeId>,
arena: Mutex<Arena>,
runtime: Arc<DynGraphRuntime>,
live_sources: Vec<core_types::SourceId>,
}
fn noop_runtime() -> Arc<DynGraphRuntime> {
Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>))
} }
impl Default for DynamicExecutor { impl Default for DynamicExecutor {
@@ -29,6 +49,9 @@ impl Default for DynamicExecutor {
tree: Default::default(), tree: Default::default(),
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY), typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
orphaned_nodes: HashSet::new(), orphaned_nodes: HashSet::new(),
arena: Mutex::new(new_arena()),
runtime: noop_runtime(),
live_sources: Vec::new(),
} }
} }
} }
@@ -48,25 +71,40 @@ pub struct ResolvedDocumentNodeTypesDelta {
} }
impl DynamicExecutor { impl DynamicExecutor {
pub async fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> { pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY); let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
typing_context.update(&proto_network)?; typing_context.update(&mut proto_network)?;
let output = proto_network.output; let output = proto_network.output;
let tree = BorrowTree::new(proto_network, &typing_context).await?; let sources = proto_network.source_ids();
let tree = BorrowTree::new(proto_network, &typing_context)?;
let runtime = noop_runtime();
runtime.retain_sources(&sources);
Ok(Self { Ok(Self {
tree, tree,
output, output,
typing_context, typing_context,
orphaned_nodes: HashSet::new(), orphaned_nodes: HashSet::new(),
arena: Mutex::new(new_arena()),
runtime,
live_sources: sources,
}) })
} }
pub fn set_runtime(&mut self, runtime: Arc<DynGraphRuntime>) {
runtime.retain_sources(&self.live_sources);
self.runtime = runtime;
}
pub fn take_dirty(&self) -> bool {
self.runtime.take_dirty()
}
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible. /// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
#[cfg_attr(debug_assertions, inline(never))] #[cfg_attr(debug_assertions, inline(never))]
pub async fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> { pub fn update(&mut self, mut proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
self.output = proto_network.output; self.output = proto_network.output;
self.typing_context.update(&proto_network).map_err(|e| { self.typing_context.update(&mut proto_network).map_err(|e| {
// If there is an error then get types that have been resolved before the error // If there is an error then get types that have been resolved before the error
let add = proto_network let add = proto_network
.nodes .nodes
@@ -87,11 +125,10 @@ impl DynamicExecutor {
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e) (ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
})?; })?;
let (add, orphaned) = self let sources = proto_network.source_ids();
.tree let (add, orphaned) = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
.update(proto_network, &self.typing_context) self.runtime.retain_sources(&sources);
.await self.live_sources = sources;
.map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned); let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len())); let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
for node_id in old_to_remove { for node_id in old_to_remove {
@@ -108,8 +145,17 @@ impl DynamicExecutor {
} }
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path. /// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
/// A monitor's record capture materializes its element here against the
/// arena, inside the introspection window, so consumers downcast the
/// element type directly. The captured input context stays on the
/// serialized io record for consumers that need it.
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> { pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
self.tree.introspect(node_path) let result = self.tree.introspect(node_path)?;
if let Some(io) = result.downcast_ref::<core_types::memo::IORecord<core_types::context::CtxSnapshot, core_types::record::RecordCapture>>() {
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
return io.output.materialize_element(&arena).map(Arc::from).ok_or(IntrospectError::NoData);
}
Ok(result)
} }
pub fn input_type(&self) -> Option<Type> { pub fn input_type(&self) -> Option<Type> {
@@ -135,27 +181,51 @@ impl DynamicExecutor {
} }
} }
impl<I> Executor<I, TaggedValue> for &DynamicExecutor impl<I> Executor<I, GPoll<TaggedValue>> for &DynamicExecutor
where where
I: StaticType + 'static + Send + Sync + std::panic::UnwindSafe, I: VarArg + Send + Sync + std::panic::RefUnwindSafe,
{ {
fn execute(&self, input: I) -> LocalFuture<'_, Result<TaggedValue, Box<dyn Error>>> { fn execute(&self, input: I) -> Result<GPoll<TaggedValue>, Box<dyn Error>> {
Box::pin(async move { let Some(handle) = self.tree.get(self.output) else {
use futures::FutureExt; return Err("Output node not found in executor".into());
};
let result = self.tree.eval_tagged_value(self.output, input); let mut arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
let wrapped_result = std::panic::AssertUnwindSafe(result).catch_unwind().await; core_types::record::stack::reserve(self.tree.stack_need());
let result = eval_root(&mut arena, &self.runtime, &input, |ctx| match TaggedValue::from_edge(handle.duplicate(), ctx) {
match wrapped_result { Ok(poll) => poll.map(Ok),
Ok(result) => result.map_err(|e| e.into()), Err(error) => GPoll::Final(Err(error)),
Err(e) => { });
Box::leak(e); match result {
Err("Node graph execution panicked".into()) GPoll::Final(value) => Ok(GPoll::Final(value?)),
} GPoll::Partial(value) => Ok(GPoll::Partial(value?)),
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
Ok(GPoll::Fallback(Box::new((value?, error))))
} }
}) GPoll::Pending => Ok(GPoll::Pending),
GPoll::Error(error) => Ok(GPoll::Error(error)),
}
} }
} }
pub fn eval_root<S, T>(arena: &mut Arena, runtime: &GraphRuntime<S>, call_argument: DynSlot, eval: impl FnOnce(&ContextImpl) -> GPoll<T>) -> GPoll<T> {
arena.reset();
let generations = runtime.snapshot();
let scope = EvalScope::new(None, None, None, &generations, arena);
let root = ContextImpl::root(&scope);
let link = VarArgLink {
args: VarArgSlots::Single(call_argument),
outer: None,
};
let ctx = root.with_varargs(&link);
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| eval(&ctx))) {
Ok(result) => result,
Err(_) => {
arena.reset();
GPoll::panicked()
}
}
}
pub struct InputMapping {} pub struct InputMapping {}
#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -188,85 +258,88 @@ impl std::fmt::Display for IntrospectError {
/// ///
/// # Fields /// # Fields
/// ///
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SharedNodeContainer`] and [`Path`]. /// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`EdgeHandle`] and [`Path`].
/// This stores the actual node instances and their associated paths. /// This stores the actual node instances and their associated paths.
/// ///
/// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`]. /// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`].
/// This maps document paths to node IDs and their associated type information. /// This maps document paths to node IDs and their associated type information.
/// ///
/// A store of the dynamically typed nodes and also the source map. /// A store of the dynamically typed nodes and also the source map.
#[derive(Default, Clone)] #[derive(Default)]
pub struct BorrowTree { pub struct BorrowTree {
/// A hashmap of node IDs and dynamically typed nodes. /// A hashmap of node IDs and dynamically typed nodes.
nodes: HashMap<NodeId, (SharedNodeContainer, Path)>, nodes: HashMap<NodeId, (EdgeHandle, Path)>,
/// A hashmap from the document path to the proto node ID. /// A hashmap from the document path to the proto node ID.
source_map: HashMap<Path, (NodeId, NodeTypes)>, source_map: HashMap<Path, (NodeId, NodeTypes)>,
/// The record-stack reserve, folded from the graph at construction.
stack_need: usize,
} }
impl BorrowTree { impl BorrowTree {
pub async fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> { pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
let mut nodes = BorrowTree::default(); let mut nodes = BorrowTree::default();
let output = proto_network.output;
let mut deps = HashMap::new();
for (id, node) in proto_network.nodes { for (id, node) in proto_network.nodes {
nodes.push_node(id, node, typing_context).await? if let ConstructionArgs::Nodes(ids) = &node.construction_args {
deps.insert(id, ids.clone());
}
nodes.push_node(id, node, typing_context)?
} }
nodes.stack_need = stack_peak(output, &deps, &|id| nodes.frame_bytes(id));
Ok(nodes) Ok(nodes)
} }
/// Pushes new nodes into the tree and return orphaned nodes /// Pushes new nodes into the tree and return orphaned nodes
pub async fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> { pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
let output = proto_network.output;
let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect(); let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect();
let mut new_nodes: Vec<_> = Vec::new(); let mut new_nodes: Vec<_> = Vec::new();
let mut deps = HashMap::new();
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type. // TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
for (id, node) in proto_network.nodes { for (id, node) in proto_network.nodes {
if let ConstructionArgs::Nodes(ids) = &node.construction_args {
deps.insert(id, ids.clone());
}
if !self.nodes.contains_key(&id) { if !self.nodes.contains_key(&id) {
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into()); new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
self.push_node(id, node, typing_context).await?; self.push_node(id, node, typing_context)?;
} else if self.update_source_map(id, typing_context, &node) { } else if self.update_source_map(id, typing_context, &node) {
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into()); new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
} }
old_nodes.remove(&id); old_nodes.remove(&id);
} }
self.stack_need = stack_peak(output, &deps, &|id| self.frame_bytes(id));
Ok((new_nodes, old_nodes)) Ok((new_nodes, old_nodes))
} }
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SharedNodeContainer> { fn node_deps(&self, nodes: &[NodeId]) -> Vec<EdgeHandle> {
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.clone()).collect() nodes.iter().map(|node| self.nodes.get(node).unwrap().0.duplicate()).collect()
} }
fn store_node(&mut self, node: SharedNodeContainer, id: NodeId, path: Path) { fn store_node(&mut self, node: EdgeHandle, id: NodeId, path: Path) {
self.nodes.insert(id, (node, path)); self.nodes.insert(id, (node, path));
} }
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path. /// Calls the `Node::serialize` for that specific node, returning for example the captured io record for a monitor node. The node path must match the document node path.
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> { pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?; let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?; let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
node.serialize().ok_or(IntrospectError::NoData) node.serialize().ok_or(IntrospectError::NoData)
} }
pub fn get(&self, id: NodeId) -> Option<SharedNodeContainer> { pub fn get(&self, id: NodeId) -> Option<EdgeHandle> {
self.nodes.get(&id).map(|(node, _)| node.clone()) self.nodes.get(&id).map(|(node, _)| node.duplicate())
} }
/// Evaluate the output node of the [`BorrowTree`]. /// Evaluate a node of the [`BorrowTree`], downcasting its edge to the expected output type.
pub async fn eval<'i, I, O>(&'i self, id: NodeId, input: I) -> Option<O> pub fn eval<I, T: 'static>(&self, id: NodeId, input: &I) -> Option<GPoll<T>>
where where
I: StaticType + 'i + Send + Sync, ErasedNode<T>: Node<I, Output = T>,
O: StaticType + 'i,
{ {
let (node, _path) = self.nodes.get(&id).cloned()?; let (node, _path) = self.nodes.get(&id)?;
let output = node.eval(Box::new(input)); let edge = node.duplicate().downcast::<T>().ok()?;
dyn_any::downcast::<O>(output.await).ok().map(|o| *o) Some(edge.eval(input))
}
/// Evaluate the output node of the [`BorrowTree`] and cast it to a tagged value.
/// This ensures that no borrowed data can escape the node graph.
pub async fn eval_tagged_value<I>(&self, id: NodeId, input: I) -> Result<TaggedValue, String>
where
I: StaticType + 'static + Send + Sync,
{
let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?;
let output = node.eval(Box::new(input));
TaggedValue::try_from_any(output.await)
} }
/// Removes a node from the [`BorrowTree`] and returns its associated path. /// Removes a node from the [`BorrowTree`] and returns its associated path.
@@ -293,10 +366,10 @@ impl BorrowTree {
/// use interpreted_executor::node_registry; /// use interpreted_executor::node_registry;
/// ///
/// ///
/// async fn example() -> Result<(), GraphErrors> { /// fn example() -> Result<(), GraphErrors> {
/// let (proto_network, node_id, proto_node) = ProtoNetwork::example(); /// let (proto_network, node_id, proto_node) = ProtoNetwork::example();
/// let typing_context = TypingContext::new(&node_registry::NODE_REGISTRY); /// let typing_context = TypingContext::default();
/// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context).await?; /// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context)?;
/// ///
/// // Assert that the node exists in the BorrowTree /// // Assert that the node exists in the BorrowTree
/// assert!(borrow_tree.get(node_id).is_some(), "Node should exist before removal"); /// assert!(borrow_tree.get(node_id).is_some(), "Node should exist before removal");
@@ -393,30 +466,23 @@ impl BorrowTree {
/// - `Nodes`: Constructs a node using other nodes as dependencies. /// - `Nodes`: Constructs a node using other nodes as dependencies.
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments. /// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
/// - Returns an error if no constructor is found for the given node ID. /// - Returns an error if no constructor is found for the given node ID.
async fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> { fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
self.update_source_map(id, typing_context, &proto_node); self.update_source_map(id, typing_context, &proto_node);
let path = proto_node.original_location.path.clone().unwrap_or_default(); let path = proto_node.original_location.path.clone().unwrap_or_default();
match &proto_node.construction_args { match &proto_node.construction_args {
ConstructionArgs::Value(value) => { ConstructionArgs::Value(value) => {
let node = if let TaggedValue::EditorApi(api) = &**value { let node = (**value)
let editor_api = UpcastAsRefNode::new(api.clone()); .clone()
let node = Box::new(editor_api) as TypeErasedBox<'_>; .to_edge()
NodeContainer::new(node) .map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(error))])?;
} else {
let upcasted = UpcastNode::new(value.to_owned());
let node = Box::new(upcasted) as TypeErasedBox<'_>;
NodeContainer::new(node)
};
self.store_node(node, id, path.into()); self.store_node(node, id, path.into());
} }
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"), ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
ConstructionArgs::Nodes(ids) => { ConstructionArgs::Nodes(ids) => {
let ids = ids.to_vec(); let construction_nodes = self.node_deps(ids);
let construction_nodes = self.node_deps(&ids);
let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?; let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
let node = constructor(construction_nodes).await; let node = constructor(construction_nodes).map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(format!("{error:?}")))])?;
let node = NodeContainer::new(node);
self.store_node(node, id, path.into()); self.store_node(node, id, path.into());
} }
}; };
@@ -427,22 +493,309 @@ impl BorrowTree {
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> { pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
&self.source_map &self.source_map
} }
/// The record-stack reserve of an evaluation, folded from the graph at
/// construction (see [`stack_peak`]).
pub fn stack_need(&self) -> usize {
self.stack_need
}
fn frame_bytes(&self, id: NodeId) -> usize {
self.nodes.get(&id).and_then(|(handle, _)| handle.layout()).map_or(0, |layout| layout.frame_bytes())
}
}
/// Peak record-stack bytes for evaluating `output`'s cone. A node holds its
/// inputs' frames until it returns, so its need is its own frame plus every
/// input's frame plus the deepest input's peak. Memoized over shared cones.
fn stack_peak(output: NodeId, deps: &HashMap<NodeId, Vec<NodeId>>, frame_bytes: &dyn Fn(NodeId) -> usize) -> usize {
fn peak(id: NodeId, deps: &HashMap<NodeId, Vec<NodeId>>, frame_bytes: &dyn Fn(NodeId) -> usize, memo: &mut HashMap<NodeId, usize>) -> usize {
if let Some(&cached) = memo.get(&id) {
return cached;
}
let mut held = 0;
let mut deepest = 0;
for &child in deps.get(&id).map_or(&[][..], Vec::as_slice) {
let child_frame = frame_bytes(child);
held += child_frame;
deepest = deepest.max(peak(child, deps, frame_bytes, memo).saturating_sub(child_frame));
}
let need = frame_bytes(id) + held + deepest;
memo.insert(id, need);
need
}
peak(output, deps, frame_bytes, &mut HashMap::new())
} }
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;
use core_types::arena::ArenaCell;
use core_types::context::{ExtractFootprint, ExtractVarArgs};
use core_types::runtime::{SourceFuture, Spawner};
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
struct InertSpawner;
impl Spawner for InertSpawner {
fn spawn(&self, _task: SourceFuture) -> bool {
false
}
}
#[test]
fn stack_peak_folds_a_diamond_chain() {
// S3 <- S2 <- S1 <- S0, each consuming the node below on both inputs.
let deps = HashMap::from([
(NodeId(1), vec![NodeId(0), NodeId(0)]),
(NodeId(2), vec![NodeId(1), NodeId(1)]),
(NodeId(3), vec![NodeId(2), NodeId(2)]),
]);
let frame = |_: NodeId| 1;
assert_eq!(stack_peak(NodeId(0), &deps, &frame), 1);
assert_eq!(stack_peak(NodeId(3), &deps, &frame), 7);
}
#[test]
fn eval_root_builds_the_bare_root_with_the_call_argument_as_vararg_0() {
let mut arena = Arena::new(64).unwrap();
let runtime = GraphRuntime::new(InertSpawner);
let argument = 21.5f64;
let result = eval_root(&mut arena, &runtime, &argument, |ctx| {
assert!(ctx.try_footprint().is_none(), "the bare root carries no axes");
GPoll::Final(ctx.vararg(0).ok().and_then(|slot| slot.downcast_ref::<f64>()).copied().unwrap_or(0.))
});
assert_eq!(result, GPoll::Final(21.5));
}
#[test]
fn eval_root_resets_the_arena_at_eval_start() {
let mut arena = Arena::new(64).unwrap();
let runtime = GraphRuntime::new(InertSpawner);
let cell = ArenaCell::new();
eval_root(&mut arena, &runtime, &(), |ctx| {
let (_, weak) = ctx.scope().arena().alloc(5u32).unwrap();
cell.store(weak);
GPoll::Final(())
});
assert!(cell.load(&arena).is_some(), "the introspection window spans until the next eval");
eval_root(&mut arena, &runtime, &(), |ctx| {
assert!(cell.load(ctx.scope().arena()).is_none(), "the reset at eval start reclaims the previous frame");
GPoll::Final(())
});
}
#[test]
fn a_panicking_eval_reports_the_error_and_resets_the_arena() {
let mut arena = Arena::new(64).unwrap();
let runtime = GraphRuntime::new(InertSpawner);
let cell = ArenaCell::new();
let result: GPoll<()> = eval_root(&mut arena, &runtime, &(), |ctx| {
let (_, weak) = ctx.scope().arena().alloc(5u32).unwrap();
cell.store(weak);
panic!("mid-eval");
});
assert_eq!(result, GPoll::panicked());
assert!(cell.load(&arena).is_none(), "reset-on-panic leaves no stale records");
assert_eq!(eval_root(&mut arena, &runtime, &(), |_| GPoll::Final(7u32)), GPoll::Final(7));
}
#[test] #[test]
fn push_node_sync() { fn push_node_sync() {
let mut tree = BorrowTree::default(); let mut tree = BorrowTree::default();
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]); let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
let context = TypingContext::default(); let context = TypingContext::default();
let future = tree.push_node(NodeId(0), val_1_protonode, &context); tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
futures::executor::block_on(future).unwrap(); let handle = tree.get(NodeId(0)).unwrap();
let _node = tree.get(NodeId(0)).unwrap(); let layout = handle.layout().unwrap().clone();
let result = futures::executor::block_on(tree.eval(NodeId(0), ())); let edge = handle.duplicate().downcast_record::<u32>().unwrap();
assert_eq!(result, Some(2u32));
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let GPoll::Final(value) = edge.eval(&ctx) else {
panic!("expected a final record");
};
assert_eq!(unsafe { core_types::record::read_element::<u32>(layout.rec(&value)) }, 2);
}
fn proto_node(identifier: &'static str, args: Vec<NodeId>) -> ProtoNode {
let mut node = ProtoNode::default();
node.identifier = graph_craft::ProtoNodeIdentifier::new(identifier);
node.call_argument = core_types::concrete!(core_types::context::Context);
node.construction_args = ConstructionArgs::Nodes(args);
node
}
fn string_value(value: &str) -> ProtoNode {
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(value.to_string()).into()), vec![])
}
#[test]
fn the_clone_node_clones_the_element_out_of_its_record_wire() {
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), vec![])),
(NodeId(1), proto_node("graphene_core::debug::CloneNode", vec![NodeId(0)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
let arena = Arena::new(1 << 20).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = executor
.tree()
.get(NodeId(1))
.unwrap()
.downcast_record::<graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>>()
.unwrap();
let result = edge.eval(&ctx);
assert!(matches!(result, GPoll::Final(_)), "the flipped clone must evaluate over record wires, got a non-final poll");
}
#[test]
fn a_flipped_ref_parameter_reads_the_borrow_from_its_record_wire() {
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), vec![])),
(NodeId(1), ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(4).into()), vec![])),
(NodeId(2), proto_node("raster_nodes::image_color_palette::ImageColorPaletteNode", vec![NodeId(0), NodeId(1)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = executor
.tree()
.get(NodeId(2))
.unwrap()
.downcast_record::<graphene_std::list::List<graphene_std::raster::color::Color>>()
.unwrap();
let result = edge.eval(&ctx);
assert!(matches!(result, GPoll::Final(_)), "the palette must evaluate through its record wires, got a non-final poll");
}
#[test]
fn a_value_edge_is_a_record_wire_end_to_end() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(0),
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![]))],
};
let executor = DynamicExecutor::new(network).unwrap();
let value = executor.tree().get(NodeId(0)).unwrap();
assert_eq!(value.ty(), &core_types::registry::record_edge_type::<f64>());
assert!(value.layout().is_some());
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
}
#[test]
fn a_record_monitor_row_forwards_and_introspects_through_the_executor() {
let mut monitor = proto_node("graphene_core::memo::MonitorNode", vec![NodeId(0)]);
monitor.original_location.path = Some(vec![NodeId(9)]);
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])), (NodeId(1), monitor)],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
let element = executor.introspect(&[NodeId(9)]).unwrap();
let element = element.downcast_ref::<f64>().expect("a record capture materializes to its element");
assert_eq!(*element, 7.);
}
#[test]
fn a_memoize_row_wires_generically_and_replays_over_record_wires() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(String::from("cached")).into()), vec![])),
(NodeId(1), proto_node("graphene_core::memo::MemoizeNode", vec![NodeId(0)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String(String::from("cached"))));
assert_eq!(
(&executor).execute(()).unwrap(),
GPoll::Final(TaggedValue::String(String::from("cached"))),
"the second execution replays the deep copy against a reset arena"
);
}
fn modification_value() -> ProtoNode {
let modification = core_types::ContextModification::from_sources(core_types::context::ContextFeatures::all(), &[]);
ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextModification(modification).into()), vec![])
}
#[test]
fn a_context_modification_row_wires_over_a_value_wire() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), modification_value()),
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
}
#[test]
fn nested_context_modifications_forward_the_layout() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(4),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), modification_value()),
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
(NodeId(3), modification_value()),
(NodeId(4), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(2), NodeId(3)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
}
#[test]
fn stacked_frame_memos_replay_over_record_wires() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), string_value("memoized")),
(NodeId(1), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(0)])),
(NodeId(2), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(1)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String("memoized".to_string())));
assert_eq!(
(&executor).execute(()).unwrap(),
GPoll::Final(TaggedValue::String("memoized".to_string())),
"the frame memo must replay across evaluations"
);
} }
} }
+1 -2
View File
@@ -5,7 +5,6 @@ pub mod util;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use core_types::*; use core_types::*;
use futures::executor::block_on;
use graphene_core::ops::passthrough; use graphene_core::ops::passthrough;
#[test] #[test]
@@ -47,6 +46,6 @@ mod tests {
let compiler = Compiler {}; let compiler = Compiler {};
let protograph = compiler.compile_single(network).expect("Graph should be generated"); let protograph = compiler.compile_single(network).expect("Graph should be generated");
let _exec = block_on(DynamicExecutor::new(protograph)).map(|_e| panic!("The network should not type check ")).unwrap_err(); let _exec = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
} }
} }
@@ -1,12 +1,6 @@
use dyn_any::StaticType;
use glam::{DAffine2, DVec2, IVec2}; use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::PlatformEditorApi; use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::DocumentNode;
use graph_craft::document::value::RenderOutput; use graph_craft::document::value::RenderOutput;
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
use graphene_std::any::DynAnyNode;
use graphene_std::application_io::Texture;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::gradient::GradientStops; use graphene_std::gradient::GradientStops;
use graphene_std::list::{AttributeDyn, AttributeValueDyn, List, ListDyn}; use graphene_std::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
@@ -16,19 +10,20 @@ use graphene_std::raster::GPU;
use graphene_std::raster::color::Color; use graphene_std::raster::color::Color;
use graphene_std::raster::*; use graphene_std::raster::*;
use graphene_std::raster::{CPU, Raster}; use graphene_std::raster::{CPU, Raster};
use graphene_std::registry::{ConstructionError, EdgeHandle, ErasedNode, NodeIOTypes, RegistryEntry};
use graphene_std::render_node::RenderIntermediate; use graphene_std::render_node::RenderIntermediate;
use graphene_std::runtime::RuntimeHandle;
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
use graphene_std::uuid::NodeId; use graphene_std::uuid::NodeId;
use graphene_std::vector::Vector; use graphene_std::vector::Vector;
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type_fut, future}; use graphene_std::{Artboard, Context, Graphic, ProtoNodeIdentifier, SourceId, concrete, fn_type};
use node_registry_macros::{async_node, convert_node, into_node}; use node_registry_macros::{convert_node, into_node};
use std::collections::HashMap; use std::collections::HashMap;
#[cfg(feature = "gpu")] #[cfg(feature = "gpu")]
use wgpu_executor::WgpuExecutor; use wgpu_executor::WgpuExecutorHandle;
// TODO: turn into hashmap fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> { let mut node_types: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
let mut node_types: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
// ========== // ==========
// INTO NODES // INTO NODES
// ========== // ==========
@@ -92,8 +87,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
convert_node!(from: List<Raster<GPU>>, to: AttributeValueDyn), convert_node!(from: List<Raster<GPU>>, to: AttributeValueDyn),
convert_node!(from: List<Graphic>, to: AttributeValueDyn), convert_node!(from: List<Graphic>, to: AttributeValueDyn),
// into_node!(from: List<Raster<CPU>>, to: List<Raster<SRGBA8>>), // into_node!(from: List<Raster<CPU>>, to: List<Raster<SRGBA8>>),
#[cfg(feature = "gpu")]
into_node!(from: &PlatformEditorApi, to: &WgpuExecutor),
convert_node!(from: DVec2, to: DVec2), convert_node!(from: DVec2, to: DVec2),
convert_node!(from: List<Vector>, to: List<Vector>), convert_node!(from: List<Vector>, to: List<Vector>),
convert_node!(from: DVec2, to: List<Vector>), convert_node!(from: DVec2, to: List<Vector>),
@@ -103,193 +96,19 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
convert_node!(from: IVec2, to: String), convert_node!(from: IVec2, to: String),
convert_node!(from: DAffine2, to: String), convert_node!(from: DAffine2, to: String),
#[cfg(feature = "gpu")] #[cfg(feature = "gpu")]
convert_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>, converter: &WgpuExecutor), convert_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>, converter: WgpuExecutorHandle),
#[cfg(feature = "gpu")] #[cfg(feature = "gpu")]
convert_node!(from: List<Raster<CPU>>, to: List<Raster<GPU>>, converter: &WgpuExecutor), convert_node!(from: List<Raster<CPU>>, to: List<Raster<GPU>>, converter: WgpuExecutorHandle),
#[cfg(feature = "gpu")] #[cfg(feature = "gpu")]
convert_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>, converter: &WgpuExecutor), convert_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>, converter: WgpuExecutorHandle),
#[cfg(feature = "gpu")] #[cfg(feature = "gpu")]
convert_node!(from: List<Raster<GPU>>, to: List<Raster<CPU>>, converter: &WgpuExecutor), convert_node!(from: List<Raster<GPU>>, to: List<Raster<CPU>>, converter: WgpuExecutorHandle, async),
// ============= // =============
// MONITOR NODES // MONITOR NODES
// ============= // =============
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ()]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Artboard>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Graphic>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Vector>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientStops>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Image<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => String]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => IVec2]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DVec2]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DAffine2]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<DAffine2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => bool]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => f64]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u32]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u64]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => BlendMode]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Texture]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::application_io::resource::Resource]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<f64>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<String>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<NodeId>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f64>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<u8>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<bool>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DAffine2>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BlendMode>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientType>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => AttributeDyn]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ListDyn]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Graphic]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DocumentNode]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::LuminanceCalculation]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlue]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlueAlpha]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::NoiseType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::FractalType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularDistanceFunction]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularReturnType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::DomainWarpType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RelativeAbsolute]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::SelectiveColorChoice]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
// Context nullification
#[cfg(feature = "gpu")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderOutput, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeDyn, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => graphene_std::ContextFeatures]),
#[cfg(target_family = "wasm")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => CanvasHandle, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache, Context => graphene_std::ContextFeatures]),
// ========== // ==========
// MEMO NODES // MEMO NODES
// ========== // ==========
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ()]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => bool]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Artboard>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Graphic>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Vector>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Image<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientStops>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<NodeId>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<u8>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientType>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeDyn]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ListDyn]),
#[cfg(target_family = "wasm")]
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => CanvasHandle]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f64]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f32]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u32]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u64]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DVec2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => String]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DAffine2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Footprint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderOutput]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<f64>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Graphic]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Vec2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Affine2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DocumentNode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::LuminanceCalculation]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::QRCodeErrorCorrectionLevel]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlue]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlueAlpha]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::NoiseType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::FractalType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularDistanceFunction]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularReturnType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::DomainWarpType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RelativeAbsolute]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::SelectiveColorChoice]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache]),
]; ];
// ============= // =============
// CONVERT NODES // CONVERT NODES
@@ -317,15 +136,22 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
.flatten(), .flatten(),
); );
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
for (id, entry) in graphene_std::registry::NODE_REGISTRY.lock().unwrap().iter() { let mut map: HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> = HashMap::new();
for (constructor, types) in entry.iter() { let insert = |map: &mut HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>, id: ProtoNodeIdentifier, entry: RegistryEntry| {
map.entry(id.clone()).or_default().insert(types.clone(), *constructor); let rows = map.entry(id).or_default();
if !rows.iter().any(|row| row.io == entry.io) {
rows.push(entry);
}
};
for (id, entries) in graphene_std::registry::NODE_REGISTRY.lock().unwrap().iter() {
for entry in entries {
insert(&mut map, id.clone(), entry.clone());
} }
} }
for (id, node_constructor, types) in node_types.into_iter() { for (id, entry) in node_types.into_iter() {
// TODO: this is a hack to remove the newline from the node new_name // TODO: this is a hack to remove the newline from the node new_name
// This occurs for the ChannelMixerNode presumably because of the long name. // This occurs for the ChannelMixerNode presumably because of the long name.
// This might be caused by the stringify! macro // This might be caused by the stringify! macro
@@ -338,77 +164,45 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
new_name = path.to_string(); new_name = path.to_string();
} }
map.entry(ProtoNodeIdentifier::with_owned_string(new_name)).or_default().insert(types.clone(), node_constructor); insert(&mut map, ProtoNodeIdentifier::with_owned_string(new_name), entry);
} }
map map
} }
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar // TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
pub static NODE_REGISTRY: once_cell::sync::Lazy<HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>> = once_cell::sync::Lazy::new(|| node_registry()); pub static NODE_REGISTRY: once_cell::sync::Lazy<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>> = once_cell::sync::Lazy::new(node_registry);
mod node_registry_macros { mod node_registry_macros {
macro_rules! async_node {
// TODO: we currently need to annotate the type here because the compiler would otherwise (correctly)
// TODO: assign a Pin<Box<dyn Future<Output=T>>> type to the node, which is not what we want for now.
//
// This `params` variant of the macro wraps the normal `fn_params` variant and is used as a shorthand for writing `T` instead of `() => T`
($path:ty, input: $input:ty, params: [$($type:ty),*]) => {
async_node!($path, input: $input, fn_params: [ $(() => $type),*])
};
($path:ty, input: $input:ty, fn_params: [$($arg:ty => $type:ty),*]) => {
(
ProtoNodeIdentifier::new(stringify!($path)),
|mut args| {
Box::pin(async move {
args.reverse();
let node = <$path>::new($(graphene_std::any::downcast_node::<$arg, $type>(args.pop().expect("Not enough arguments provided to construct node"))),*);
let any: DynAnyNode<$input, _, _> = graphene_std::any::DynAnyNode::new(node);
Box::new(any) as TypeErasedBox
})
},
{
let node = <$path>::new($(
graphene_std::any::PanicNode::<$arg, core::pin::Pin<Box<dyn core::future::Future<Output = $type> + Send>>>::new()
),*);
let params = vec![$(fn_type_fut!($arg, $type)),*];
let mut node_io = NodeIO::<'_, $input>::to_async_node_io(&node, params);
node_io.call_argument = concrete!(<$input as StaticType>::Static);
node_io
},
)
};
}
macro_rules! into_node { macro_rules! into_node {
(from: $from:ty, to: $to:ty) => { (from: $from:ty, to: $to:ty) => {
( (
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]), ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
|mut args| { RegistryEntry {
Box::pin(async move { io: NodeIOTypes::new(
let node = graphene_std::ops::IntoNode::new( concrete!(Context),
graphene_std::any::downcast_node::<Context, $from>(args.pop().unwrap()), core_types::registry::record_type::<$to>(),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)), vec![core_types::registry::record_edge_type::<$from>()],
); ),
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node); constructor: |inputs| {
Box::new(any) as TypeErasedBox if inputs.len() != 1 {
}) return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
}, }
{ let mut inputs = inputs.into_iter();
let node = graphene_std::ops::IntoNode::new( let handle = inputs.next().unwrap();
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(), let Some(layout) = handle.layout().cloned() else {
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)), return Err(ConstructionError::MissingLayout);
); };
let params = vec![fn_type_fut!(Context, $from)]; let node = graphene_std::ops::IntoNode::<$to, _, $from>::new(handle.downcast_record::<$from>()?, &layout);
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params); Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
node_io },
}, },
) )
}; };
} }
macro_rules! convert_node { macro_rules! convert_node {
(from: $from:ty, to: numbers) => {{ (from: $from:ty, to: numbers) => {{
let x: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let x: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
convert_node!(from: $from, to: f32), convert_node!(from: $from, to: f32),
convert_node!(from: $from, to: f64), convert_node!(from: $from, to: f64),
convert_node!(from: $from, to: i8), convert_node!(from: $from, to: i8),
@@ -427,7 +221,7 @@ mod node_registry_macros {
x x
}}; }};
(from: numbers, to: $to:ty) => {{ (from: numbers, to: $to:ty) => {{
let x: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let x: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
convert_node!(from: f32, to: $to), convert_node!(from: f32, to: $to),
convert_node!(from: f64, to: $to), convert_node!(from: f64, to: $to),
convert_node!(from: i8, to: $to), convert_node!(from: i8, to: $to),
@@ -448,37 +242,118 @@ mod node_registry_macros {
(from: $from:ty, to: $to:ty) => { (from: $from:ty, to: $to:ty) => {
convert_node!(from: $from, to: $to, converter: ()) convert_node!(from: $from, to: $to, converter: ())
}; };
(from: $from:ty, to: $to:ty, converter: $convert:ty, async) => {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
RegistryEntry {
io: NodeIOTypes::new(
concrete!(Context),
core_types::registry::record_type::<$to>(),
vec![
core_types::registry::record_edge_type::<$from>(),
core_types::registry::record_edge_type::<$convert>(),
core_types::registry::record_edge_type::<RuntimeHandle>(),
core_types::registry::record_edge_type::<SourceId>(),
],
),
constructor: |inputs| {
if inputs.len() != 4 {
return Err(ConstructionError::Arity { expected: 4, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
let mut claim = || {
let handle = inputs.next().unwrap();
let Some(layout) = handle.layout().cloned() else {
return Err(ConstructionError::MissingLayout);
};
Ok((handle, layout))
};
let (value, value_layout) = claim()?;
let (converter, converter_layout) = claim()?;
let (runtime, runtime_layout) = claim()?;
let (source, source_layout) = claim()?;
let node = graphene_std::ops::ConvertAsyncNode::<$to, _, _, _, _, $from, $convert>::new(
value.downcast_record::<$from>()?,
converter.downcast_record::<$convert>()?,
runtime.downcast_record::<RuntimeHandle>()?,
source.downcast_record::<SourceId>()?,
&value_layout,
&converter_layout,
&runtime_layout,
&source_layout,
);
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
},
},
)
};
(from: $from:ty, to: $to:ty, converter: $convert:ty) => { (from: $from:ty, to: $to:ty, converter: $convert:ty) => {
( (
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]), ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|mut args| { RegistryEntry {
Box::pin(async move { io: NodeIOTypes::new(
let mut args = args.drain(..); concrete!(Context),
let node = graphene_std::ops::ConvertNode::new( core_types::registry::record_type::<$to>(),
graphene_std::any::downcast_node::<Context, $from>(args.next().expect("Convert node did not get first argument")), vec![core_types::registry::record_edge_type::<$from>(), core_types::registry::record_edge_type::<$convert>()],
graphene_std::any::downcast_node::<Context, $convert>(args.next().expect("Convert node did not get converter argument")), ),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)) constructor: |inputs| {
if inputs.len() != 2 {
return Err(ConstructionError::Arity { expected: 2, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
let value = inputs.next().unwrap();
let Some(value_layout) = value.layout().cloned() else {
return Err(ConstructionError::MissingLayout);
};
let converter = inputs.next().unwrap();
let Some(converter_layout) = converter.layout().cloned() else {
return Err(ConstructionError::MissingLayout);
};
let node = graphene_std::ops::ConvertNode::<$to, _, _, $from, $convert>::new(
value.downcast_record::<$from>()?,
converter.downcast_record::<$convert>()?,
&value_layout,
&converter_layout,
); );
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node); Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
Box::new(any) as TypeErasedBox },
})
},
{
let node = graphene_std::ops::ConvertNode::new(
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $convert> + Send>>>::new(),
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>))
);
let params = vec![fn_type_fut!(Context, $from), fn_type_fut!(Context, $convert)];
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
node_io
}, },
) )
}; };
} }
pub(crate) use async_node;
pub(crate) use convert_node; pub(crate) use convert_node;
pub(crate) use into_node; pub(crate) use into_node;
} }
#[cfg(test)]
mod tests {
use super::*;
use graphene_std::Type;
fn is_record_edge(ty: &Type) -> bool {
match ty {
Type::Fn(_, output) => matches!(&**output, Type::Record(_)),
_ => false,
}
}
/// One wire kind: every row consumes and produces record wires. A plain
/// io type here would need a bridge adapter, and those are gone.
#[test]
fn every_registry_row_is_record_typed() {
let mut plain: Vec<String> = Vec::new();
for (id, entries) in NODE_REGISTRY.iter() {
for entry in entries {
let plain_output = !matches!(entry.io.return_value, Type::Record(_));
let plain_inputs: Vec<usize> = entry.io.inputs.iter().enumerate().filter(|(_, ty)| !is_record_edge(ty)).map(|(index, _)| index).collect();
if plain_output || !plain_inputs.is_empty() {
plain.push(format!("{} plain_output={plain_output} plain_inputs={plain_inputs:?}", id.as_str()));
}
}
}
plain.sort();
assert!(plain.is_empty(), "plain io remains in the registry:\n{}", plain.join("\n"));
}
}
+12 -27
View File
@@ -30,20 +30,14 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
call_argument: concrete!(Context), call_argument: concrete!(Context),
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)], inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
extract: ContextFeatures::VARARGS,
inject: ContextFeatures::INDEX,
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
call_argument: concrete!(Context), call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)], inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
@@ -54,20 +48,14 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(1), 0),
], ],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::VARARGS),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::VARARGS,
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
call_argument: concrete!(Context), call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)], inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
@@ -77,21 +65,18 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
NodeInput::node(NodeId(3), 0), NodeInput::node(NodeId(3), 0),
], ],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
context_features: graphene_std::ContextDependencies { context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
},
..Default::default() ..Default::default()
}, },
DocumentNode { DocumentNode {
call_argument: concrete!(graphene_std::application_io::RenderConfig), call_argument: concrete!(Context),
inputs: vec![NodeInput::node(NodeId(4), 0)], inputs: vec![NodeInput::node(NodeId(4), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER), implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
context_features: graphene_std::ContextDependencies { // We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work context_features: graphene_std::ContextDependencies::new(
extract: ContextFeatures::INDEX, ContextFeatures::INDEX | ContextFeatures::VARARGS,
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
}, ),
..Default::default() ..Default::default()
}, },
] ]
@@ -114,7 +99,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
..Default::default() ..Default::default()
}, },
]; ];
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), concrete!(&PlatformEditorApi)))]; let scope_injections = vec![("editor-api".to_string(), (NodeId(2), concrete!(std::sync::Arc<PlatformEditorApi>)))];
NodeNetwork { NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)], exports: vec![NodeInput::node(NodeId(1), 0)],
@@ -16,6 +16,7 @@ wgpu = ["dep:raster-types", "raster-types/wgpu"]
# Local dependencies # Local dependencies
dyn-any = { workspace = true } dyn-any = { workspace = true }
core-types = { workspace = true } core-types = { workspace = true }
graphene-hash = { workspace = true }
vector-types = { workspace = true } vector-types = { workspace = true }
text-nodes = { workspace = true } text-nodes = { workspace = true }
graphene-resource = { workspace = true } graphene-resource = { workspace = true }
+12 -3
View File
@@ -21,6 +21,9 @@ pub trait ApplicationIo {
fn gpu_executor(&self) -> Option<&Self::Executor> { fn gpu_executor(&self) -> Option<&Self::Executor> {
None None
} }
fn gpu_executor_arc(&self) -> Option<Arc<Self::Executor>> {
None
}
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_>; fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_>;
} }
@@ -31,6 +34,10 @@ impl<T: ApplicationIo> ApplicationIo for &T {
(**self).gpu_executor() (**self).gpu_executor()
} }
fn gpu_executor_arc(&self) -> Option<Arc<T::Executor>> {
(**self).gpu_executor_arc()
}
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> { fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
(**self).load_resource(hash) (**self).load_resource(hash)
} }
@@ -54,7 +61,7 @@ pub trait GetEditorPreferences {
fn max_render_region_area(&self) -> u32; fn max_render_region_area(&self) -> u32;
} }
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ExportFormat { pub enum ExportFormat {
#[default] #[default]
@@ -62,14 +69,14 @@ pub enum ExportFormat {
Raster, Raster,
} }
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)] #[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TimingInformation { pub struct TimingInformation {
pub time: f64, pub time: f64,
pub animation_time: Duration, pub animation_time: Duration,
} }
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)] #[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RenderConfig { pub struct RenderConfig {
pub viewport: Footprint, pub viewport: Footprint,
@@ -105,6 +112,7 @@ pub struct EditorApi<Io> {
pub node_graph_message_sender: Box<dyn NodeGraphUpdateSender + Send + Sync>, pub node_graph_message_sender: Box<dyn NodeGraphUpdateSender + Send + Sync>,
/// Editor preferences made available to the graph through the `PlatformEditorApi`. /// Editor preferences made available to the graph through the `PlatformEditorApi`.
pub editor_preferences: Box<dyn GetEditorPreferences + Send + Sync>, pub editor_preferences: Box<dyn GetEditorPreferences + Send + Sync>,
pub runtime: core_types::runtime::RuntimeHandle,
} }
impl<Io> Eq for EditorApi<Io> {} impl<Io> Eq for EditorApi<Io> {}
@@ -115,6 +123,7 @@ impl<Io: Default> Default for EditorApi<Io> {
application_io: None, application_io: None,
node_graph_message_sender: Box::new(Logger), node_graph_message_sender: Box::new(Logger),
editor_preferences: Box::new(DummyPreferences), editor_preferences: Box::new(DummyPreferences),
runtime: Default::default(),
} }
} }
} }
@@ -0,0 +1,426 @@
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
/// Handle word layout: 24 generation bits above 40 offset bits, so a 1 TiB arena is
/// addressable and generations run out after ~3 days of 60fps resets.
const OFFSET_BITS: u32 = 40;
const OFFSET_MASK: u64 = (1 << OFFSET_BITS) - 1;
const GENERATION_MASK: u64 = (1 << (64 - OFFSET_BITS)) - 1;
/// Out of the encodable range, so no handle, including `NULL`, matches it.
const PARKED_GENERATION: u64 = GENERATION_MASK + 1;
pub struct Arena {
generation: AtomicU64,
offset: AtomicUsize,
buf: Box<[UnsafeCell<MaybeUninit<u8>>]>,
drops: Mutex<Vec<DropEntry>>,
}
impl std::fmt::Debug for Arena {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Arena").field("generation", &self.generation).field("size", &self.buf.len()).finish()
}
}
struct DropEntry {
offset: usize,
drop_fn: unsafe fn(*mut u8),
}
// SAFETY: disjoint regions are handed out by an atomic bump; a region is written
// only by its allocating caller before publication, and cross-thread hand-off is
// ordered by the Release/Acquire pair on the published handle word. Payloads are
// `Send + Sync` by the bound on every allocating method.
unsafe impl Sync for Arena {}
unsafe impl Send for Arena {}
impl std::panic::UnwindSafe for Arena {}
impl std::panic::RefUnwindSafe for Arena {}
/// Shared by all arenas, so a foreign handle misses like a stale one.
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
static LIVE_ARENAS: AtomicUsize = AtomicUsize::new(0);
/// `None` past [`GENERATION_MASK`], where a reissued generation would let an ancient
/// handle upgrade against a current arena. Recovered by `reset_generation_counter`.
fn next_generation() -> Option<u64> {
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
(generation <= GENERATION_MASK).then_some(generation)
}
/// Rewinds the shared generation counter so previously issued values are reused.
/// Returns `false` without rewinding when an [`Arena`] is live at the time of the
/// check, which is a debugging aid rather than a guarantee.
///
/// # Safety
///
/// No [`ArenaWeak`] minted before this call may be upgraded afterwards. Dropping
/// every [`Arena`] is not sufficient, since nodes also hold handles in
/// [`ArenaCell`]s; those nodes must be dropped too. No arena may be constructed
/// concurrently either, since the live check and the rewind are separate steps.
pub unsafe fn reset_generation_counter() -> bool {
if LIVE_ARENAS.load(Ordering::Acquire) != 0 {
return false;
}
NEXT_GENERATION.store(1, Ordering::Release);
true
}
impl Arena {
pub fn new(capacity: usize) -> Option<Self> {
let generation = next_generation()?;
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
LIVE_ARENAS.fetch_add(1, Ordering::Release);
Some(Self {
generation: AtomicU64::new(generation),
offset: AtomicUsize::new(0),
buf,
drops: Mutex::new(Vec::new()),
})
}
/// An arena that refuses every allocation and resolves no handle, so a caller that
/// cannot fail can degrade instead of propagating exhaustion.
pub fn parked() -> Self {
LIVE_ARENAS.fetch_add(1, Ordering::Release);
Self {
generation: AtomicU64::new(PARKED_GENERATION),
offset: AtomicUsize::new(0),
buf: Box::new([]),
drops: Mutex::new(Vec::new()),
}
}
pub fn generation(&self) -> u64 {
self.generation.load(Ordering::Acquire)
}
fn base(&self) -> *mut u8 {
self.buf.as_ptr() as *mut u8
}
fn reserve(&self, size: usize, align: usize) -> Option<usize> {
debug_assert!(align.is_power_of_two());
let base = self.base() as usize;
let mut start = 0;
self.offset
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
// Alignment is computed on the absolute address; the backbone
// allocation itself has no alignment guarantee.
let addr = (base.checked_add(current)?.checked_add(align - 1)?) & !(align - 1);
start = addr - base;
let end = start.checked_add(size)?;
(end <= self.buf.len()).then_some(end)
})
.ok()?;
Some(start)
}
pub fn alloc<T: Send + Sync>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
// Built before the write so an unencodable offset drops `value` here
// rather than stranding it in the arena without drop glue.
let weak = ArenaWeak::new(self.generation(), offset)?;
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
unsafe { ptr.write(value) };
if std::mem::needs_drop::<T>() {
unsafe fn glue<T>(p: *mut u8) {
unsafe { p.cast::<T>().drop_in_place() }
}
self.drops.lock().unwrap().push(DropEntry { offset, drop_fn: glue::<T> });
}
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
Some((unsafe { &*ptr }, weak))
}
pub fn alloc_slice_copy<T: Copy + Send + Sync>(&self, src: &[T]) -> Option<&[T]> {
let buf = self.alloc_scratch::<T>(src.len())?;
for (slot, &value) in buf.iter_mut().zip(src) {
slot.write(value);
}
// SAFETY: every lane written above from `src`.
Some(unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::<T>(), src.len()) })
}
// Not drop-tracked: callers must either consume every written lane or
// restrict themselves to `Copy` payloads (leak, not UB, otherwise).
#[allow(clippy::mut_from_ref)]
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
let size = size_of::<T>().checked_mul(len)?;
let offset = self.reserve(size, align_of::<T>())?;
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
// SAFETY: exclusive region; lifetime tied to `&self`, and `reset` takes
// `&mut self`, so the slice cannot outlive the generation.
Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
}
/// `false` once generations are exhausted, parking the arena on [`PARKED_GENERATION`]
/// where every handle misses and further allocation is refused.
pub fn reset(&mut self) -> bool {
let base = self.base();
let entries = std::mem::take(self.drops.get_mut().unwrap());
self.generation.store(PARKED_GENERATION, Ordering::Release);
for entry in entries.into_iter().rev() {
// SAFETY: registered at alloc time; insert-only means the region was
// never overwritten within this generation.
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
}
*self.offset.get_mut() = 0;
let Some(generation) = next_generation() else { return false };
self.generation.store(generation, Ordering::Release);
true
}
}
impl Drop for Arena {
fn drop(&mut self) {
self.reset();
LIVE_ARENAS.fetch_sub(1, Ordering::Release);
}
}
pub struct ArenaWeak<T> {
word: u64,
_marker: PhantomData<fn() -> T>,
}
impl<T> Clone for ArenaWeak<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for ArenaWeak<T> {}
impl<T> ArenaWeak<T> {
pub const NULL: Self = ArenaWeak { word: 0, _marker: PhantomData };
/// `None` once either field leaves its encodable range, so an oversized or parked
/// arena refuses to hand out a handle rather than truncating it to a live address.
fn new(generation: u64, offset: usize) -> Option<Self> {
let offset = u64::try_from(offset).ok().filter(|offset| *offset <= OFFSET_MASK)?;
(generation <= GENERATION_MASK).then_some(Self {
word: (generation << OFFSET_BITS) | offset,
_marker: PhantomData,
})
}
pub fn upgrade(self, arena: &Arena) -> Option<&T> {
let generation = self.word >> OFFSET_BITS;
if generation != arena.generation() {
return None;
}
let offset = (self.word & OFFSET_MASK) as usize;
// SAFETY: same generation means the entry was fully written before its
// word was published (Release) and cannot move or be overwritten within
// a generation (insert-only); the Acquire load that produced this word
// ordered the payload writes.
Some(unsafe { &*arena.base().add(offset).cast::<T>() })
}
}
pub struct ArenaCell<T> {
word: AtomicU64,
_marker: PhantomData<fn() -> T>,
}
impl<T> Clone for ArenaCell<T> {
fn clone(&self) -> Self {
Self {
word: AtomicU64::new(self.word.load(Ordering::Acquire)),
_marker: PhantomData,
}
}
}
impl<T> std::fmt::Debug for ArenaCell<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ArenaCell").field("word", &self.word.load(Ordering::Relaxed)).finish()
}
}
impl<T> Default for ArenaCell<T> {
fn default() -> Self {
Self {
word: AtomicU64::new(0),
_marker: PhantomData,
}
}
}
impl<T> ArenaCell<T> {
pub fn new() -> Self {
Self::default()
}
pub fn load<'e>(&self, arena: &'e Arena) -> Option<&'e T> {
let weak = ArenaWeak::<T> {
word: self.word.load(Ordering::Acquire),
_marker: PhantomData,
};
weak.upgrade(arena)
}
pub fn store(&self, weak: ArenaWeak<T>) {
self.word.store(weak.word, Ordering::Release);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::PoisonError;
use std::sync::atomic::AtomicU32;
#[test]
fn alloc_upgrade_reset_miss() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let (value, weak) = arena.alloc(41u32).unwrap();
assert_eq!(*value, 41);
cell.store(weak);
assert_eq!(cell.load(&arena), Some(&41));
arena.reset();
assert_eq!(cell.load(&arena), None, "stale handle must miss");
}
#[test]
fn capacity_survives_reset() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(64 + align_of::<u32>() - 1).unwrap();
for _ in 0..10 {
for _ in 0..16 {
assert!(arena.alloc(0u32).is_some());
}
assert!(arena.alloc(0u32).is_none(), "exhausted within generation");
arena.reset();
}
}
#[test]
fn panics_leave_the_arena_coherent() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
fn assert_ref_unwind_safe<T: std::panic::RefUnwindSafe>() {}
assert_ref_unwind_safe::<Arena>();
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let result = std::panic::catch_unwind(|| {
let (_, weak) = arena.alloc(Probe("pre-panic".into())).unwrap();
cell.store(weak);
panic!("mid-eval");
});
assert!(result.is_err());
assert!(cell.load(&arena).is_some(), "the generation is still live after the caught panic");
arena.reset();
assert_eq!(DROPS.load(Ordering::Relaxed), 1, "reset reclaims pre-panic allocations");
assert!(cell.load(&arena).is_none(), "the bump kills stale handles");
assert!(arena.alloc(0u32).is_some(), "the arena stays usable");
}
#[test]
fn a_panicking_destructor_leaves_no_resolvable_handle() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
panic!("payload destructor");
}
}
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let (_, weak) = arena.alloc(Bomb).unwrap();
cell.store(weak);
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
assert!(unwound.is_err(), "the panic must propagate out of reset");
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
}
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
/// is never observed by a concurrently constructing test.
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
#[test]
fn an_exhausted_reset_parks_the_arena_and_refuses_handles() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
let (_, weak) = arena.alloc(41u32).unwrap();
let restore = NEXT_GENERATION.swap(GENERATION_MASK + 1, Ordering::Relaxed);
assert!(!arena.reset(), "an exhausted counter must report failure");
NEXT_GENERATION.store(restore, Ordering::Relaxed);
assert_eq!(weak.upgrade(&arena), None, "a parked arena resolves no handle");
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&arena), None, "not even the null handle");
assert!(arena.alloc(0u32).is_none(), "a parked arena refuses allocation");
}
#[test]
fn the_generation_counter_rewinds_only_without_live_arenas() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let arena = Arena::new(64).unwrap();
assert!(!unsafe { reset_generation_counter() }, "a live arena must block the rewind");
drop(arena);
}
#[test]
fn handles_do_not_upgrade_against_a_foreign_arena() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let first = Arena::new(1024).unwrap();
let second = Arena::new(1024).unwrap();
let (_, weak) = first.alloc(41u32).unwrap();
assert_eq!(weak.upgrade(&first), Some(&41));
assert_eq!(weak.upgrade(&second), None, "a handle must not resolve against another arena");
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&second), None, "the null handle never upgrades");
}
#[test]
fn reset_drops_dependents_before_their_dependencies() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static ORDER: Mutex<Vec<u32>> = Mutex::new(Vec::new());
struct Probe(u32);
impl Drop for Probe {
fn drop(&mut self) {
ORDER.lock().unwrap().push(self.0);
}
}
let mut arena = Arena::new(1024).unwrap();
for id in 0..3 {
arena.alloc(Probe(id)).unwrap();
}
arena.reset();
assert_eq!(*ORDER.lock().unwrap(), vec![2, 1, 0], "later allocations may borrow earlier ones, so they drop first");
}
#[test]
fn drop_glue_runs_on_reset() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let mut arena = Arena::new(1024).unwrap();
arena.alloc(Probe("owns heap".into())).unwrap();
arena.alloc(Probe("me too".into())).unwrap();
assert_eq!(DROPS.load(Ordering::Relaxed), 0);
arena.reset();
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
}
}
@@ -0,0 +1,310 @@
//! Attribute markers and their census. A marker declares an attribute name
//! once, fixing its value type and its name-specific default; the census
//! collects every declaration so name resolution, defaults, and diagnostics
//! run at graph compile time. One name belongs to one marker, so a name can
//! never mean two different types.
//!
//! Values are `Copy` and pack directly into record fields. Data with drop
//! glue rides the arena instead: the marker declares a reference value
//! (`&str`), the writing kernel parks the payload in the arena, and the
//! record field carries the eval-lifetime reference.
use crate::list::AnyAttributeValue;
use glam::{DAffine2, DVec2};
use std::any::TypeId;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::{LazyLock, Mutex};
/// Declares an attribute name: one marker per name, fixing the value type and
/// the name-specific default. Declare markers through the [`attribute!`]
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`].
pub trait Attribute: 'static {
/// The name as it appears in documents and diagnostics.
const NAME: &'static str;
/// The value type every read and write of this name shares. The lifetime
/// is the evaluation the value flows in; non-reference values ignore it.
type Value<'e>: Copy + Default + std::fmt::Debug;
/// The name-specific default, filled where an item lacks the attribute.
/// Producing a value for any `'e` from no inputs, reference defaults can
/// only point at `'static` data, which is what lets the census fill them
/// as plain bytes.
fn default<'e>() -> Self::Value<'e> {
Default::default()
}
/// # Safety
/// `ptr` must point at a live field of this marker's value type.
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue>;
/// Re-parks the owned clone [`Self::read_erased`] produced into fresh
/// field storage; `None` for plain values, which ride the byte copy.
const REPARK: Option<unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>> = None;
}
/// A kernel-facing attribute value. A parameter `Attr<A>` is a read of `A`
/// (yielding the declared default where the attribute is absent upstream), an
/// `Attr<A>` in the return tuple is a write, and the same marker on both
/// sides is a modify.
pub struct Attr<'e, A: Attribute>(pub A::Value<'e>);
impl<'e, A: Attribute> Deref for Attr<'e, A> {
type Target = A::Value<'e>;
fn deref(&self) -> &A::Value<'e> {
&self.0
}
}
impl<'e, A: Attribute> Clone for Attr<'e, A> {
fn clone(&self) -> Self {
*self
}
}
impl<'e, A: Attribute> Copy for Attr<'e, A> {}
impl<'e, A: Attribute> std::fmt::Debug for Attr<'e, A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple(A::NAME).field(&self.0).finish()
}
}
/// A deletion of `A` in a node's return tuple: the name leaves the output
/// layout, so downstream reads yield the declared default again. Functionally
/// a write of the default; the value carries nothing.
pub struct RemoveAttr<A: Attribute>(PhantomData<A>);
impl<A: Attribute> RemoveAttr<A> {
pub const fn new() -> Self {
RemoveAttr(PhantomData)
}
}
impl<A: Attribute> Default for RemoveAttr<A> {
fn default() -> Self {
Self::new()
}
}
/// A census row: what is known about one declared attribute name.
#[derive(Clone, Copy, Debug)]
pub struct AttributeInfo {
pub name: &'static str,
pub value_type: TypeId,
pub value_type_name: &'static str,
pub default: fn() -> Box<dyn AnyAttributeValue>,
pub size: usize,
pub align: usize,
/// Writes the declared default's bytes into a `size`-long slice.
pub write_default_bytes: fn(&mut [u8]),
}
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
assert_eq!(out.len(), size_of::<A::Value<'static>>());
let value: A::Value<'static> = A::default();
unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
}
/// All declared attribute names, keyed by name.
pub static ATTRIBUTE_REGISTRY: LazyLock<Mutex<HashMap<&'static str, AttributeInfo>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
/// Registers `A` into the census. Called by the [`attribute!`] expansion at
/// startup (ctor natively, a `__node_registry_attribute_*` export on wasm).
/// Re-registration at the same value type is idempotent; a second marker
/// claiming the name at a different value type panics.
pub fn register<A: Attribute>()
where
A::Value<'static>: AnyAttributeValue,
{
let info = AttributeInfo {
name: A::NAME,
value_type: TypeId::of::<A::Value<'static>>(),
value_type_name: std::any::type_name::<A::Value<'static>>(),
default: || Box::new(A::default()),
size: size_of::<A::Value<'static>>(),
align: align_of::<A::Value<'static>>(),
write_default_bytes: write_default_bytes::<A>,
};
let conflict = match ATTRIBUTE_REGISTRY.lock().unwrap().entry(A::NAME) {
Entry::Vacant(vacant) => {
vacant.insert(info);
None
}
Entry::Occupied(occupied) => (occupied.get().value_type != info.value_type).then(|| occupied.get().value_type_name),
};
if let Some(existing) = conflict {
panic!("attribute `{}` is declared at two value types: {existing} and {}", A::NAME, info.value_type_name);
}
}
/// Looks up a declared name.
pub fn info(name: &str) -> Option<AttributeInfo> {
ATTRIBUTE_REGISTRY.lock().unwrap().get(name).copied()
}
/// The name-specific default for `name`, if the name is declared.
pub fn default_value(name: &str) -> Option<Box<dyn AnyAttributeValue>> {
info(name).map(|info| (info.default)())
}
/// Declares attribute markers: for each entry, the marker struct, its
/// [`Attribute`] impl, and the census registration.
///
/// ```
/// core_types::attribute! {
/// /// How visible the content is.
/// pub Opacity("opacity"): f64 = 1.;
/// /// The item's label, parked in the arena by the writer.
/// pub Label("label"): &str;
/// }
/// ```
///
/// The trailing `= expr` is the name-specific default; without it the value
/// type's `Default` applies. A `&T` value carries the eval lifetime, so its
/// default must be `'static` data.
#[macro_export]
macro_rules! attribute {
() => {};
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): &$value:ty $(= $default:expr)?; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $marker;
impl $crate::attribute::Attribute for $marker {
const NAME: &'static str = $name;
type Value<'e> = &'e $value;
$(
fn default<'e>() -> Self::Value<'e> {
$default
}
)?
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<&$value>().read() }.to_owned())
}
const REPARK: ::core::option::Option<unsafe fn(&dyn $crate::list::AnyAttributeValue, *mut u8, &$crate::arena::Arena) -> ::core::option::Option<()>> = {
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
let owned: &<$value as ::std::borrow::ToOwned>::Owned = value.as_any().downcast_ref().expect("a reference attribute replays its owned clone");
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
unsafe { dst.cast::<&$value>().write(::std::borrow::Borrow::borrow(parked)) };
::core::option::Option::Some(())
}
::core::option::Option::Some(repark)
};
}
$crate::attribute!(@register $marker);
$crate::attribute!($($rest)*);
};
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): $value:ty $(= $default:expr)?; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $marker;
impl $crate::attribute::Attribute for $marker {
const NAME: &'static str = $name;
type Value<'e> = $value;
$(
fn default<'e>() -> Self::Value<'e> {
$default
}
)?
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<$value>().read() })
}
}
$crate::attribute!(@register $marker);
$crate::attribute!($($rest)*);
};
(@register $marker:ident) => {
const _: () = {
#[cfg(not(target_family = "wasm"))]
#[$crate::ctor::ctor]
fn register() {
$crate::attribute::register::<$marker>();
}
#[cfg(target_family = "wasm")]
#[unsafe(export_name = concat!("__node_registry_attribute_", stringify!($marker)))]
extern "C" fn register() {
$crate::attribute::register::<$marker>();
}
};
};
}
attribute! {
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
pub Transform("transform"): DAffine2;
/// Item's `BlendMode`, controlling how it composites with content beneath it.
pub BlendMode("blend_mode"): crate::blending::BlendMode;
/// Item's opacity multiplier, composed multiplicatively through nested groups.
/// Affects content clipped to the item.
pub Opacity("opacity"): f64 = 1.;
/// Item's fill opacity multiplier. Like opacity but does not affect content clipped to the item.
pub OpacityFill("opacity_fill"): f64 = 1.;
/// Whether an item inherits the alpha of the content beneath it (clipping mask).
pub ClippingMask("clipping_mask"): bool;
/// Artboard's top-left corner in document coordinates.
pub Location("location"): DVec2;
/// A regex named-capture-group's name, or empty for unnamed groups.
pub Name("name"): &str;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn census_carries_declared_names() {
let row = info("opacity").unwrap();
assert_eq!(row.value_type, TypeId::of::<f64>());
assert_eq!(info("transform").unwrap().value_type, TypeId::of::<DAffine2>());
assert!(info("never_declared").is_none());
}
#[test]
fn name_specific_default_overrides_the_type_default() {
assert_eq!(<Opacity as Attribute>::default(), 1.);
assert_eq!(<Name as Attribute>::default(), "");
}
#[test]
fn erased_default_downcasts_to_the_declared_type() {
let value = default_value("opacity_fill").unwrap();
assert_eq!(*value.as_any().downcast_ref::<f64>().unwrap(), 1.);
}
#[test]
fn reference_values_register_at_the_static_instantiation() {
let row = info("name").unwrap();
assert_eq!(row.value_type, TypeId::of::<&'static str>());
assert_eq!(row.size, size_of::<&str>());
}
#[test]
fn reregistration_at_the_same_type_is_idempotent() {
register::<Opacity>();
register::<Opacity>();
assert_eq!(info("opacity").unwrap().value_type, TypeId::of::<f64>());
}
#[test]
#[should_panic(expected = "two value types")]
fn a_second_marker_at_a_different_type_panics() {
struct Conflict;
impl Attribute for Conflict {
const NAME: &'static str = "opacity";
type Value<'e> = bool;
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue> {
Box::new(unsafe { ptr.cast::<bool>().read() })
}
}
register::<Conflict>();
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,198 @@
use crate::gpoll::Finality;
use std::cell::UnsafeCell;
use std::mem::{ManuallyDrop, MaybeUninit};
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
const SLOT_EMPTY: u8 = 0;
const SLOT_FINAL: u8 = 1;
const SLOT_PARTIAL: u8 = 2;
pub struct FrameTable<T, const CAP: usize> {
slots: [FrameSlot<T>; CAP],
}
struct FrameSlot<T> {
key: AtomicU64,
state: AtomicU8,
value: UnsafeCell<MaybeUninit<T>>,
}
// SAFETY: the key CAS reserves a slot for one writer, and the Release store of its
// state publishes the value to every Acquire load in `lookup`, so concurrent access
// is ordered. Sharing the table hands out `&T` and drops `T` on whichever thread
// drops the table, which is what the `Send + Sync` bounds cover.
unsafe impl<T: Send + Sync, const CAP: usize> Sync for FrameTable<T, CAP> {}
unsafe impl<T: Send, const CAP: usize> Send for FrameTable<T, CAP> {}
pub enum Lookup<'t, T> {
Hit(Finality, &'t T),
Vacant(VacantSlot<'t, T>),
Full,
}
pub struct VacantSlot<'t, T> {
slot: &'t FrameSlot<T>,
}
impl<T, const CAP: usize> Default for FrameTable<T, CAP> {
fn default() -> Self {
Self::new()
}
}
impl<T, const CAP: usize> FrameTable<T, CAP> {
pub fn new() -> Self {
Self {
slots: std::array::from_fn(|_| FrameSlot {
key: AtomicU64::new(0),
state: AtomicU8::new(SLOT_EMPTY),
value: UnsafeCell::new(MaybeUninit::uninit()),
}),
}
}
pub fn lookup(&self, hash: u64) -> Lookup<'_, T> {
// Only hash 0 is remapped, so distinct hashes stay distinct keys.
let key = if hash == 0 { 1 } else { hash };
for probe in 0..CAP {
let slot = &self.slots[(key as usize).wrapping_add(probe) % CAP];
let stored = slot.key.load(Ordering::Acquire);
if stored == key {
return match slot.state.load(Ordering::Acquire) {
// SAFETY: a published state was stored with Release after the
// value write; the Acquire load above ordered that write.
SLOT_FINAL => Lookup::Hit(Finality::AllFinal, unsafe { (*slot.value.get()).assume_init_ref() }),
SLOT_PARTIAL => Lookup::Hit(Finality::Partial, unsafe { (*slot.value.get()).assume_init_ref() }),
_ => Lookup::Full,
};
}
if stored == 0 && slot.key.compare_exchange(0, key, Ordering::AcqRel, Ordering::Acquire).is_ok() {
return Lookup::Vacant(VacantSlot { slot });
}
}
Lookup::Full
}
}
impl<T, const CAP: usize> Drop for FrameTable<T, CAP> {
fn drop(&mut self) {
for slot in &self.slots {
if slot.state.load(Ordering::Acquire) != SLOT_EMPTY {
// SAFETY: a non-empty state is only ever stored after the value
// write in `publish`.
unsafe { (*slot.value.get()).assume_init_drop() }
}
}
}
}
impl<'t, T> VacantSlot<'t, T> {
pub fn publish(self, value: T, finality: Finality) -> &'t T {
let slot = ManuallyDrop::new(self).slot;
// SAFETY: the CAS in `lookup` reserved this slot exclusively for us and
// its state is still SLOT_EMPTY, so nobody reads the value yet.
let lent = unsafe { &*(*slot.value.get()).write(value) };
let state = match finality {
Finality::AllFinal => SLOT_FINAL,
Finality::Partial => SLOT_PARTIAL,
};
slot.state.store(state, Ordering::Release);
lent
}
pub fn release(self) {
drop(self);
}
}
/// Frees the reservation, so an early return or panic between `lookup` and
/// `publish` cannot retire the slot for the rest of the table's life.
impl<T> Drop for VacantSlot<'_, T> {
fn drop(&mut self) {
self.slot.key.store(0, Ordering::Release);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::AtomicU32;
#[test]
fn publish_then_hit_with_finality() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(7) else {
panic!("fresh table must be vacant");
};
assert_eq!(*slot.publish(41, Finality::Partial), 41);
let Lookup::Hit(finality, value) = table.lookup(7) else {
panic!("published key must hit");
};
assert_eq!((finality, *value), (Finality::Partial, 41));
}
#[test]
fn released_slot_is_vacant_again() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
slot.release();
assert!(matches!(table.lookup(7), Lookup::Vacant(_)));
}
#[test]
fn a_dropped_reservation_frees_the_slot() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
drop(slot);
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an abandoned reservation must not retire the slot");
}
#[test]
fn neighboring_hashes_do_not_share_an_entry() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(6) else { unreachable!() };
slot.publish(600, Finality::AllFinal);
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an even hash must not answer for its odd neighbor");
}
#[test]
fn the_zero_hash_round_trips() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(0) else { unreachable!() };
slot.publish(11, Finality::AllFinal);
let Lookup::Hit(_, value) = table.lookup(0) else {
panic!("the remapped sentinel hash must still hit");
};
assert_eq!(*value, 11);
}
#[test]
fn distinct_keys_probe_past_collisions_until_full() {
let table = FrameTable::<u32, 4>::new();
for hash in [2, 4, 6, 8] {
let Lookup::Vacant(slot) = table.lookup(hash) else {
panic!("hash {hash} should find a vacant slot");
};
slot.publish(hash as u32, Finality::AllFinal);
}
assert!(matches!(table.lookup(100), Lookup::Full));
}
#[test]
fn drop_runs_glue_for_published_values_only() {
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe;
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let table = FrameTable::<Probe, 8>::new();
let Lookup::Vacant(slot) = table.lookup(1) else { unreachable!() };
slot.publish(Probe, Finality::AllFinal);
let Lookup::Vacant(reserved_but_unpublished) = table.lookup(2) else { unreachable!() };
reserved_but_unpublished.release();
drop(table);
assert_eq!(DROPS.load(Ordering::Relaxed), 1);
}
}
@@ -1,17 +0,0 @@
use crate::Node;
use std::marker::PhantomData;
#[derive(Clone)]
pub struct FnNode<T: Fn(I) -> O, I, O>(T, PhantomData<(I, O)>);
impl<'i, T: Fn(I) -> O + 'i, O: 'i, I: 'i> Node<'i, I> for FnNode<T, I, O> {
type Output = O;
fn eval(&'i self, input: I) -> Self::Output {
self.0(input)
}
}
impl<T: Fn(I) -> O, I, O> FnNode<T, I, O> {
pub fn new(f: T) -> Self {
FnNode(f, PhantomData)
}
}
@@ -0,0 +1,235 @@
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorKind {
Node(&'static str),
ArenaExhausted,
Panic,
}
impl PartialEq<&str> for ErrorKind {
fn eq(&self, other: &&str) -> bool {
matches!(self, ErrorKind::Node(kind) if kind == other)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphError {
pub kind: ErrorKind,
pub trace: Vec<usize>,
}
impl GraphError {
pub fn new(kind: &'static str) -> Self {
Self {
kind: ErrorKind::Node(kind),
trace: Vec::new(),
}
}
pub fn traced(mut self, input_index: usize) -> Self {
self.trace.push(input_index);
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum GPoll<T> {
Pending,
Final(T),
Partial(T),
Fallback(Box<(T, GraphError)>),
Error(Box<GraphError>),
}
impl<T> GPoll<T> {
#[inline(always)]
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> GPoll<U> {
match self {
GPoll::Pending => GPoll::Pending,
GPoll::Final(value) => GPoll::Final(f(value)),
GPoll::Partial(value) => GPoll::Partial(f(value)),
GPoll::Fallback(boxed) => {
let (value, e) = *boxed;
GPoll::Fallback(Box::new((f(value), e)))
}
GPoll::Error(e) => GPoll::Error(e),
}
}
#[inline(always)]
pub fn and_then<U>(self, f: impl FnOnce(T) -> GPoll<U>) -> GPoll<U> {
match self {
GPoll::Pending => GPoll::Pending,
GPoll::Final(value) => f(value),
GPoll::Partial(value) => match f(value) {
GPoll::Final(result) => GPoll::Partial(result),
other => other,
},
GPoll::Fallback(boxed) => {
let (value, e) = *boxed;
match f(value) {
GPoll::Pending => GPoll::Pending,
GPoll::Final(result) | GPoll::Partial(result) => GPoll::Fallback(Box::new((result, e))),
GPoll::Fallback(inner) => {
let (result, _) = *inner;
GPoll::Fallback(Box::new((result, e)))
}
GPoll::Error(inner) => GPoll::Error(inner),
}
}
GPoll::Error(e) => GPoll::Error(e),
}
}
#[inline(always)]
pub fn zip<U>(self, other: GPoll<U>) -> GPoll<(T, U)> {
match (self, other) {
(GPoll::Error(e), _) | (_, GPoll::Error(e)) => GPoll::Error(e),
(GPoll::Pending, _) | (_, GPoll::Pending) => GPoll::Pending,
(GPoll::Final(a), GPoll::Final(b)) => GPoll::Final((a, b)),
(GPoll::Fallback(boxed), GPoll::Final(b) | GPoll::Partial(b)) => {
let (a, e) = *boxed;
GPoll::Fallback(Box::new(((a, b), e)))
}
(GPoll::Final(a) | GPoll::Partial(a), GPoll::Fallback(boxed)) => {
let (b, e) = *boxed;
GPoll::Fallback(Box::new(((a, b), e)))
}
(GPoll::Fallback(first), GPoll::Fallback(second)) => {
let (a, e) = *first;
let (b, _) = *second;
GPoll::Fallback(Box::new(((a, b), e)))
}
(GPoll::Partial(a), GPoll::Final(b) | GPoll::Partial(b)) | (GPoll::Final(a), GPoll::Partial(b)) => GPoll::Partial((a, b)),
}
}
#[inline(always)]
pub fn trace(self, input: usize) -> Self {
match self {
GPoll::Fallback(mut boxed) => {
boxed.1.trace.push(input);
GPoll::Fallback(boxed)
}
GPoll::Error(mut e) => {
e.trace.push(input);
GPoll::Error(e)
}
other => other,
}
}
pub fn fallback(value: T, kind: &'static str) -> Self {
GPoll::Fallback(Box::new((value, GraphError::new(kind))))
}
pub fn error(kind: &'static str) -> Self {
GPoll::Error(Box::new(GraphError::new(kind)))
}
pub fn arena_exhausted() -> Self {
GPoll::Error(Box::new(GraphError {
kind: ErrorKind::ArenaExhausted,
trace: Vec::new(),
}))
}
pub fn panicked() -> Self {
GPoll::Error(Box::new(GraphError {
kind: ErrorKind::Panic,
trace: Vec::new(),
}))
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Interrupt {
Pending,
Error(Box<GraphError>),
}
impl From<GraphError> for Interrupt {
fn from(error: GraphError) -> Self {
Interrupt::Error(Box::new(error))
}
}
impl<T> From<Interrupt> for GPoll<T> {
fn from(interrupt: Interrupt) -> Self {
match interrupt {
Interrupt::Pending => GPoll::Pending,
Interrupt::Error(e) => GPoll::Error(e),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Extent {
Free,
Exactly(usize),
}
impl Extent {
pub fn meet(a: GPoll<Extent>, b: GPoll<Extent>) -> GPoll<Extent> {
a.zip(b).and_then(|(a, b)| match (a, b) {
(Extent::Free, other) | (other, Extent::Free) => GPoll::Final(other),
(Extent::Exactly(n), Extent::Exactly(m)) if n == m => GPoll::Final(Extent::Exactly(n)),
(Extent::Exactly(n), Extent::Exactly(m)) => GPoll::fallback(Extent::Exactly(n.min(m)), "extent mismatch"),
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Finality {
AllFinal,
Partial,
}
impl Finality {
pub fn meet(self, other: Finality) -> Finality {
match (self, other) {
(Finality::AllFinal, Finality::AllFinal) => Finality::AllFinal,
_ => Finality::Partial,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn free_is_the_meet_identity() {
let meet = Extent::meet(GPoll::Final(Extent::Free), GPoll::Final(Extent::Exactly(4)));
assert_eq!(meet, GPoll::Final(Extent::Exactly(4)));
}
#[test]
fn extent_mismatch_truncates_and_reports() {
let meet = Extent::meet(GPoll::Final(Extent::Exactly(3)), GPoll::Final(Extent::Exactly(5)));
let GPoll::Fallback(boxed) = meet else {
panic!("expected fallback, got {meet:?}");
};
assert_eq!(boxed.0, Extent::Exactly(3));
assert!(boxed.1.kind == "extent mismatch");
}
#[test]
fn error_dominates_pending_in_zip() {
let zipped = GPoll::<u32>::error("boom").zip(GPoll::<u32>::Pending);
assert!(matches!(zipped, GPoll::Error(_)));
}
#[test]
fn trace_builds_root_to_source_path() {
let poll = GPoll::<u32>::error("boom").trace(2).trace(0);
let GPoll::Error(e) = poll else { unreachable!() };
assert_eq!(e.trace, vec![2, 0]);
}
#[test]
fn interrupt_round_trips_to_gpoll() {
assert_eq!(GPoll::<u32>::from(Interrupt::Pending), GPoll::Pending);
let interrupt = Interrupt::from(GraphError::new("boom"));
assert!(matches!(GPoll::<u32>::from(interrupt), GPoll::Error(e) if e.kind == "boom"));
}
}
+8 -100
View File
@@ -1,16 +1,22 @@
extern crate log; extern crate log;
pub mod arena;
pub mod attribute;
pub mod bounds; pub mod bounds;
pub mod consts; pub mod consts;
pub mod context; pub mod context;
pub mod generic; pub mod frame_table;
pub mod gpoll;
pub mod list; pub mod list;
pub mod math; pub mod math;
pub mod memo; pub mod memo;
pub mod misc; pub mod misc;
pub mod node;
pub mod ops; pub mod ops;
pub mod record;
pub mod registry; pub mod registry;
pub mod render_complexity; pub mod render_complexity;
pub mod runtime;
pub mod transform; pub mod transform;
pub mod uuid; pub mod uuid;
pub mod value; pub mod value;
@@ -34,113 +40,15 @@ pub use no_std_types::blending;
pub use no_std_types::choice_type; pub use no_std_types::choice_type;
pub use no_std_types::color; pub use no_std_types::color;
pub use no_std_types::shaders; pub use no_std_types::shaders;
pub use node::Node;
pub use num_traits; pub use num_traits;
use std::any::TypeId;
use std::future::Future;
use std::pin::Pin;
#[cfg(feature = "wasm")] #[cfg(feature = "wasm")]
pub use tsify; pub use tsify;
pub use types::Cow; pub use types::Cow;
// pub trait Node: for<'n> NodeIO<'n> {
/// The node trait allows for defining any node. Nodes can only take one call argument input, however they can store references to other nodes inside the struct.
/// See `node-graph/README.md` for information on how to define a new node.
pub trait Node<'i, Input> {
type Output: 'i;
/// Evaluates the node with the single specified input.
fn eval(&'i self, input: Input) -> Self::Output;
/// Resets the node, e.g. the LetNode's cache is set to None.
fn reset(&self) {}
/// Returns the name of the node for diagnostic purposes.
fn node_name(&self) -> &'static str {
std::any::type_name::<Self>()
}
/// Serialize the node which is used for the `introspect` function which can retrieve values from monitor nodes.
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
log::warn!("Node::serialize not implemented for {}", std::any::type_name::<Self>());
None
}
}
mod types; mod types;
pub use types::*; pub use types::*;
pub trait NodeIO<'i, Input>: Node<'i, Input>
where
Self::Output: 'i + StaticTypeSized,
Input: StaticTypeSized,
{
fn input_type(&self) -> TypeId {
TypeId::of::<Input::Static>()
}
fn input_type_name(&self) -> &'static str {
std::any::type_name::<Input>()
}
fn output_type(&self) -> TypeId {
TypeId::of::<<Self::Output as StaticTypeSized>::Static>()
}
fn output_type_name(&self) -> &'static str {
std::any::type_name::<Self::Output>()
}
fn to_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes {
NodeIOTypes {
call_argument: concrete!(<Input as StaticTypeSized>::Static),
return_value: concrete!(<Self::Output as StaticTypeSized>::Static),
inputs,
}
}
fn to_async_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes
where
<Self::Output as Future>::Output: StaticTypeSized,
Self::Output: Future,
{
NodeIOTypes {
call_argument: concrete!(<Input as StaticTypeSized>::Static),
return_value: future!(<<Self::Output as Future>::Output as StaticTypeSized>::Static),
inputs,
}
}
}
impl<'i, N: Node<'i, I>, I> NodeIO<'i, I> for N
where
N::Output: 'i + StaticTypeSized,
I: StaticTypeSized,
{
}
impl<'i, I: 'i, N: Node<'i, I> + ?Sized> Node<'i, I> for &'i N {
type Output = N::Output;
fn eval(&'i self, input: I) -> N::Output {
(*self).eval(input)
}
}
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for Box<N> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for std::sync::Arc<N> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
impl<'i, I, O: 'i> Node<'i, I> for Pin<Box<dyn Node<'i, I, Output = O> + 'i>> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
impl<'i, I, O: 'i> Node<'i, I> for Pin<&'i (dyn NodeIO<'i, I, Output = O> + 'i)> {
type Output = O;
fn eval(&'i self, input: I) -> O {
(**self).eval(input)
}
}
pub trait InputAccessorSource<'a, T>: InputAccessorSourceIdentifier + std::fmt::Debug { pub trait InputAccessorSource<'a, T>: InputAccessorSourceIdentifier + std::fmt::Debug {
fn get_input(&'a self, index: usize) -> Option<&'a T>; fn get_input(&'a self, index: usize) -> Option<&'a T>;
fn set_input(&'a mut self, index: usize, value: T); fn set_input(&'a mut self, index: usize, value: T);
+563
View File
@@ -0,0 +1,563 @@
use crate::context::InjectIndex;
use crate::gpoll::{Extent, Finality, GPoll, GraphError, Interrupt};
use std::cell::Cell;
use std::mem::MaybeUninit;
use std::ops::Range;
#[derive(Debug)]
pub enum BatchStatus<'a, T> {
Lent(RecordBatch<'a, T>, Finality),
Filled(RecordBatch<'a, T>, Finality),
Pending,
Error(GraphError),
NeedBuffer,
InvalidRange,
}
/// Owns the initialized prefix of a caller-supplied scratch buffer, dropping every
/// lane unless [`FilledBatch::into_values`] hands the obligation back to the caller.
#[derive(Debug)]
pub struct FilledBatch<'a, T> {
values: &'a mut [T],
}
impl<'a, T> FilledBatch<'a, T> {
/// # Safety
///
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
pub unsafe fn new(scratch: &'a mut [MaybeUninit<T>], len: usize) -> Self {
Self {
values: unsafe { assume_init_prefix_mut(scratch, len) },
}
}
pub fn values(&self) -> &[T] {
self.values
}
pub fn into_values(self) -> &'a mut [T] {
let mut guard = std::mem::ManuallyDrop::new(self);
std::mem::take(&mut guard.values)
}
}
impl<T> Drop for FilledBatch<'_, T> {
fn drop(&mut self) {
// SAFETY: every lane was initialized when the guard was built and none has
// been moved out, since `into_values` consumes the guard instead.
unsafe { std::ptr::drop_in_place(self.values as *mut [T]) }
}
}
/// # Safety
///
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
pub unsafe fn assume_init_prefix_mut<T>(scratch: &mut [MaybeUninit<T>], len: usize) -> &mut [T] {
debug_assert!(len <= scratch.len());
unsafe { std::slice::from_raw_parts_mut(scratch.as_mut_ptr().cast::<T>(), len) }
}
/// A borrow-for-scope view over a batch of records whose element type is `T`,
/// paired with their shared [`Layout`](crate::record::Layout). Row-major backed
/// today; the interface (`len`/`layout`/`get`/`for_each`) is storage-agnostic so
/// a columnar backing can replace it without touching consumers.
#[derive(Debug)]
pub struct RecordBatch<'a, T> {
lanes: LaneStore<'a, T>,
layout: &'a crate::record::Layout,
}
#[derive(Debug)]
enum LaneStore<'a, T> {
/// Borrows resident storage (the `Lent` status): no drop obligation.
Borrowed(&'a [T]),
/// Owns the caller scratch's initialized prefix (the `Filled` status).
Owned(FilledBatch<'a, T>),
}
impl<'a, T> RecordBatch<'a, T> {
pub fn lent(values: &'a [T], layout: &'a crate::record::Layout) -> Self {
Self { lanes: LaneStore::Borrowed(values), layout }
}
pub fn filled(filled: FilledBatch<'a, T>, layout: &'a crate::record::Layout) -> Self {
Self { lanes: LaneStore::Owned(filled), layout }
}
fn lanes(&self) -> &[T] {
match &self.lanes {
LaneStore::Borrowed(values) => values,
LaneStore::Owned(filled) => filled.values(),
}
}
pub fn len(&self) -> usize {
self.lanes().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn layout(&self) -> &crate::record::Layout {
self.layout
}
/// Lends lane `lane`'s record to `f` for the callback's scope only.
pub fn get<R>(&self, lane: usize, f: impl FnOnce(RecordLane<'_, T>) -> R) -> R {
f(RecordLane { value: &self.lanes()[lane], layout: self.layout })
}
/// Lends every lane's record in order, each for its callback's scope only.
pub fn for_each(&self, mut f: impl FnMut(usize, RecordLane<'_, T>)) {
for (lane, value) in self.lanes().iter().enumerate() {
f(lane, RecordLane { value, layout: self.layout });
}
}
/// Hands the owned scratch prefix back to the caller, cancelling the drop
/// obligation. Panics on a lent batch, which owns nothing to return.
pub fn into_values(self) -> &'a mut [T] {
match self.lanes {
LaneStore::Owned(filled) => filled.into_values(),
LaneStore::Borrowed(_) => panic!("into_values on a lent batch"),
}
}
}
/// One lane's record, lent for a callback scope. Derefs to the raw lane value;
/// for record elements, [`rec`](RecordLane::rec) and [`attr`](RecordLane::attr)
/// read the record through its layout.
#[derive(Debug)]
pub struct RecordLane<'r, T> {
value: &'r T,
layout: &'r crate::record::Layout,
}
impl<T> std::ops::Deref for RecordLane<'_, T> {
type Target = T;
fn deref(&self) -> &T {
self.value
}
}
impl<T> RecordLane<'_, T> {
pub fn layout(&self) -> &crate::record::Layout {
self.layout
}
}
impl<'e> RecordLane<'_, crate::record::RecordValue<'e>> {
/// The record pointer, resolved through the layout.
pub fn rec(&self) -> crate::record::Rec {
self.layout.rec(self.value)
}
/// The element at offset 0.
///
/// # Safety
/// `U` must be the record's element type, proven at the consumer's wiring.
pub unsafe fn element<U: Copy>(&self) -> U {
unsafe { self.rec().element::<U>() }
}
/// Attribute `A` at the record's top level, or its census default when the
/// layout does not carry it.
pub fn attr<A: crate::attribute::Attribute>(&self) -> A::Value<'e> {
match self.layout.offset_of(A::NAME, 0) {
Some(offset) => unsafe { self.rec().read::<A::Value<'e>>(offset) },
None => A::default(),
}
}
}
pub trait Node<Input> {
type Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output>;
fn extent(&self, _input: &Input) -> GPoll<Extent> {
GPoll::Final(Extent::Free)
}
/// Introspection access to node-resident records; `None` for ordinary nodes.
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
None
}
/// The record layout of this node's output; the shared empty layout for
/// element-only producers. Consumers read their carrier's layout through
/// this at wiring, and the wiring layer derives stack sizing from the same
/// layouts, in the dynamic executor and exported source alike.
fn layout(&self) -> &crate::record::Layout {
crate::record::empty_layout()
}
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
let Some(scratch) = scratch else {
return BatchStatus::NeedBuffer;
};
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
return BatchStatus::InvalidRange;
};
if scratch.len() < len {
return BatchStatus::InvalidRange;
}
let mut local = *input;
let mut finality = Finality::AllFinal;
for offset in 0..len {
local.set_index(range.start + offset as u64);
let abort = match self.eval(&local) {
GPoll::Final(value) => {
scratch[offset].write(value);
None
}
GPoll::Partial(value) => {
scratch[offset].write(value);
finality = Finality::Partial;
None
}
GPoll::Pending => Some(BatchStatus::Pending),
GPoll::Fallback(boxed) => Some(BatchStatus::Error(boxed.1)),
GPoll::Error(e) => Some(BatchStatus::Error(*e)),
};
if let Some(status) = abort {
for written in scratch[..offset].iter_mut() {
// SAFETY: every lane before `offset` was written by this loop.
unsafe { written.assume_init_drop() };
}
return status;
}
}
// SAFETY: all `len` lanes were written by the loop above.
BatchStatus::Filled(RecordBatch::filled(unsafe { FilledBatch::new(scratch, len) }, self.layout()), finality)
}
}
impl<Input, N> Node<Input> for &N
where
N: Node<Input> + ?Sized,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
(**self).eval(input)
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
(**self).extent(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
fn layout(&self) -> &crate::record::Layout {
(**self).layout()
}
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
(**self).eval_batch(input, range, scratch)
}
}
impl<Input, N> Node<Input> for Box<N>
where
N: Node<Input> + ?Sized,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
(**self).eval(input)
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
(**self).extent(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
fn layout(&self) -> &crate::record::Layout {
(**self).layout()
}
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
(**self).eval_batch(input, range, scratch)
}
}
impl<Input, N> Node<Input> for std::sync::Arc<N>
where
N: Node<Input> + ?Sized,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
(**self).eval(input)
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
(**self).extent(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
fn layout(&self) -> &crate::record::Layout {
(**self).layout()
}
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
(**self).eval_batch(input, range, scratch)
}
}
pub struct StatusCell {
finality: Cell<Finality>,
error: Cell<Option<GraphError>>,
no_partial: bool,
}
impl Default for StatusCell {
fn default() -> Self {
Self::new()
}
}
impl StatusCell {
pub fn new() -> Self {
Self {
finality: Cell::new(Finality::AllFinal),
error: Cell::new(None),
no_partial: false,
}
}
pub fn no_partial() -> Self {
Self { no_partial: true, ..Self::new() }
}
pub fn eval_input<Input, N: Node<Input>>(&self, input_index: usize, node: &N, input: &Input) -> Result<N::Output, Interrupt> {
match node.eval(input) {
GPoll::Final(value) => Ok(value),
GPoll::Partial(_) if self.no_partial => Err(Interrupt::Pending),
GPoll::Partial(value) => {
self.finality.set(Finality::Partial);
Ok(value)
}
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
let first = self.error.take();
self.error.set(first.or(Some(error.traced(input_index))));
Ok(value)
}
GPoll::Pending => Err(Interrupt::Pending),
GPoll::Error(mut error) => {
error.trace.push(input_index);
Err(Interrupt::Error(error))
}
}
}
pub fn finish<T>(self, value: T) -> GPoll<T> {
match (self.error.take(), self.finality.get()) {
(Some(error), _) => GPoll::Fallback(Box::new((value, error))),
(None, Finality::AllFinal) => GPoll::Final(value),
(None, Finality::Partial) => GPoll::Partial(value),
}
}
pub fn merge<T>(self, poll: GPoll<T>) -> GPoll<T> {
match poll {
GPoll::Final(value) => self.finish(value),
GPoll::Partial(_) if self.no_partial => GPoll::Pending,
GPoll::Partial(value) => match self.finish(value) {
GPoll::Final(value) => GPoll::Partial(value),
other => other,
},
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
let first = self.error.take().unwrap_or(error);
GPoll::Fallback(Box::new((value, first)))
}
interrupted => interrupted,
}
}
}
#[derive(Clone, Copy)]
pub struct LazyInput<'a, N> {
node: &'a N,
cell: &'a StatusCell,
input_index: usize,
}
impl<'a, N> LazyInput<'a, N> {
pub fn new(node: &'a N, cell: &'a StatusCell, input_index: usize) -> Self {
Self { node, cell, input_index }
}
pub fn eval<Input>(&self, ctx: &Input) -> Result<N::Output, Interrupt>
where
N: Node<Input>,
{
self.cell.eval_input(self.input_index, self.node, ctx)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU32, Ordering};
#[derive(Clone, Copy)]
struct TestInput {
index: u64,
}
impl InjectIndex for TestInput {
fn set_index(&mut self, index: u64) {
self.index = index;
}
}
struct Double;
impl Node<TestInput> for Double {
type Output = u64;
fn eval(&self, input: &TestInput) -> GPoll<u64> {
GPoll::Final(input.index * 2)
}
}
#[test]
fn spec_loop_fills_scratch_per_lane() {
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = Double.eval_batch(&input, 2..6, Some(&mut scratch));
let BatchStatus::Filled(batch, finality) = status else {
panic!("expected filled, got {status:?}");
};
let mut got = Vec::new();
batch.for_each(|_, lane| got.push(*lane));
assert_eq!(got, vec![4, 6, 8, 10]);
assert_eq!(finality, Finality::AllFinal);
}
#[test]
fn a_dropped_filled_batch_reclaims_every_lane() {
static DROPS: AtomicU32 = AtomicU32::new(0);
#[derive(Clone)]
struct Probe;
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
struct Probes;
impl Node<TestInput> for Probes {
type Output = Probe;
fn eval(&self, _input: &TestInput) -> GPoll<Probe> {
GPoll::Final(Probe)
}
}
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 3];
let status = Probes.eval_batch(&input, 0..3, Some(&mut scratch));
assert!(matches!(status, BatchStatus::Filled(..)));
drop(status);
assert_eq!(DROPS.load(Ordering::Relaxed), 3, "an unconsumed batch must not leak its lanes");
}
#[test]
fn probe_without_scratch_requests_a_buffer() {
let input = TestInput { index: 0 };
assert!(matches!(Double.eval_batch(&input, 0..4, None), BatchStatus::NeedBuffer));
}
#[test]
fn undersized_scratch_is_an_invalid_range() {
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 2];
assert!(matches!(Double.eval_batch(&input, 0..4, Some(&mut scratch)), BatchStatus::InvalidRange));
}
#[test]
fn partial_lane_downgrades_batch_finality() {
struct PartialAtThree;
impl Node<TestInput> for PartialAtThree {
type Output = u64;
fn eval(&self, input: &TestInput) -> GPoll<u64> {
match input.index {
3 => GPoll::Partial(input.index),
index => GPoll::Final(index),
}
}
}
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = PartialAtThree.eval_batch(&input, 0..4, Some(&mut scratch));
let BatchStatus::Filled(batch, finality) = status else {
panic!("expected filled, got {status:?}");
};
let mut got = Vec::new();
batch.for_each(|_, lane| got.push(*lane));
assert_eq!(got, vec![0, 1, 2, 3]);
assert_eq!(finality, Finality::Partial);
}
#[test]
fn abort_drops_already_written_lanes() {
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe;
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
struct PendingAtTwo;
impl Node<TestInput> for PendingAtTwo {
type Output = Probe;
fn eval(&self, input: &TestInput) -> GPoll<Probe> {
match input.index {
2 => GPoll::Pending,
_ => GPoll::Final(Probe),
}
}
}
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = PendingAtTwo.eval_batch(&input, 0..4, Some(&mut scratch));
assert!(matches!(status, BatchStatus::Pending));
assert_eq!(DROPS.load(Ordering::Relaxed), 2);
}
#[test]
fn trait_is_object_safe_across_erased_edges() {
let erased: Box<dyn Node<TestInput, Output = u64>> = Box::new(Double);
let input = TestInput { index: 21 };
assert_eq!(erased.eval(&input), GPoll::Final(42));
let mut scratch = [const { MaybeUninit::uninit() }; 2];
let status = erased.eval_batch(&input, 0..2, Some(&mut scratch));
assert!(matches!(status, BatchStatus::Filled(_, Finality::AllFinal)));
}
}
+16 -46
View File
@@ -1,56 +1,26 @@
use crate::Node;
use crate::list::{Attribute, AttributeDyn, AttributeValueDyn, Item, List, ListDyn}; use crate::list::{Attribute, AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
use crate::transform::Footprint; use crate::transform::Footprint;
use glam::DVec2; use glam::DVec2;
use graphene_hash::CacheHash; use graphene_hash::CacheHash;
use std::future::Future;
use std::marker::PhantomData;
// Type
// TODO: Document this
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct TypeNode<N: for<'a> Node<'a, I>, I, O>(pub N, pub PhantomData<(I, O)>);
impl<'i, N, I: 'i, O: 'i> Node<'i, I> for TypeNode<N, I, O>
where
N: for<'n> Node<'n, I, Output = O>,
{
type Output = O;
fn eval(&'i self, input: I) -> Self::Output {
self.0.eval(input)
}
fn reset(&self) {
self.0.reset();
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
self.0.serialize()
}
}
impl<'i, N: for<'a> Node<'a, I>, I: 'i> TypeNode<N, I, <N as Node<'i, I>>::Output> {
pub fn new(node: N) -> Self {
Self(node, PhantomData)
}
}
impl<'i, N: for<'a> Node<'a, I> + Clone, I: 'i> Clone for TypeNode<N, I, <N as Node<'i, I>>::Output> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1)
}
}
impl<'i, N: for<'a> Node<'a, I> + Copy, I: 'i> Copy for TypeNode<N, I, <N as Node<'i, I>>::Output> {}
/// The [`Convert`] trait allows for conversion between Rust primitive numeric types. /// The [`Convert`] trait allows for conversion between Rust primitive numeric types.
/// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types. /// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types.
pub trait Convert<T, C>: Sized { pub trait Convert<T, C>: Sized {
/// Converts this type into the (usually inferred) output type. /// Converts this type into the (usually inferred) output type.
#[must_use] #[must_use]
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send; fn convert(self, footprint: Footprint, converter: C) -> T;
}
/// The asynchronous counterpart of [`Convert`]; a conversion pair implements exactly one of the two traits.
pub trait ConvertAsync<T, C>: Sized {
#[must_use]
fn convert(self, footprint: Footprint, converter: C) -> crate::runtime::SourceFuture<T>;
} }
impl<T: ToString + Send> Convert<String, ()> for T { impl<T: ToString + Send> Convert<String, ()> for T {
/// Converts this type into a `String` using its `ToString` implementation. /// Converts this type into a `String` using its `ToString` implementation.
#[inline] #[inline]
async fn convert(self, _: Footprint, _converter: ()) -> String { fn convert(self, _: Footprint, _converter: ()) -> String {
self.to_string() self.to_string()
} }
} }
@@ -60,7 +30,7 @@ pub trait ListConvert<U> {
} }
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> { impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
async fn convert(self, _: Footprint, _: ()) -> List<U> { fn convert(self, _: Footprint, _: ()) -> List<U> {
let list: List<U> = self let list: List<U> = self
.into_iter() .into_iter()
.map(|row| { .map(|row| {
@@ -76,7 +46,7 @@ impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
/// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing /// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing
/// over `U`; the compiler inserts this convert to bridge concrete-typed graph wires to the dyn input. /// over `U`; the compiler inserts this convert to bridge concrete-typed graph wires to the dyn input.
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeDyn, ()> for List<T> { impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeDyn, ()> for List<T> {
async fn convert(self, _: Footprint, _: ()) -> AttributeDyn { fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect(); let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
AttributeDyn(Box::new(Attribute(values))) AttributeDyn(Box::new(Attribute(values)))
} }
@@ -86,7 +56,7 @@ impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash
/// (such as `write_attribute`'s value-producing input) be generic over the destination list type /// (such as `write_attribute`'s value-producing input) be generic over the destination list type
/// alone, with the compiler-inserted convert handling each concrete value type at the wire level. /// alone, with the compiler-inserted convert handling each concrete value type at the wire level.
impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeValueDyn, ()> for T { impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static> Convert<AttributeValueDyn, ()> for T {
async fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn { fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
AttributeValueDyn(Box::new(self)) AttributeValueDyn(Box::new(self))
} }
} }
@@ -95,13 +65,13 @@ impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash
/// only need attribute access (such as the `read_attribute_*` family) take a single `ListDyn` input /// only need attribute access (such as the `read_attribute_*` family) take a single `ListDyn` input
/// instead of monomorphizing over every possible carrier list type. /// instead of monomorphizing over every possible carrier list type.
impl<T: Send> Convert<ListDyn, ()> for List<T> { impl<T: Send> Convert<ListDyn, ()> for List<T> {
async fn convert(self, _: Footprint, _: ()) -> ListDyn { fn convert(self, _: Footprint, _: ()) -> ListDyn {
self.into() self.into()
} }
} }
impl Convert<DVec2, ()> for DVec2 { impl Convert<DVec2, ()> for DVec2 {
async fn convert(self, _: Footprint, _: ()) -> DVec2 { fn convert(self, _: Footprint, _: ()) -> DVec2 {
self self
} }
} }
@@ -115,7 +85,7 @@ pub trait FromAnchorPosition {
// Converts a position into a vector path composed of a single anchor point // Converts a position into a vector path composed of a single anchor point
impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 { impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
async fn convert(self, _: Footprint, _: ()) -> List<T> { fn convert(self, _: Footprint, _: ()) -> List<T> {
List::new_from_item(Item::new_from_element(T::from_anchor_position(self))) List::new_from_item(Item::new_from_element(T::from_anchor_position(self)))
} }
} }
@@ -124,7 +94,7 @@ impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
macro_rules! impl_convert { macro_rules! impl_convert {
($from:ty, $to:ty) => { ($from:ty, $to:ty) => {
impl Convert<$to, ()> for $from { impl Convert<$to, ()> for $from {
async fn convert(self, _: Footprint, _: ()) -> $to { fn convert(self, _: Footprint, _: ()) -> $to {
self as $to self as $to
} }
} }
@@ -146,7 +116,7 @@ macro_rules! impl_convert {
impl_convert!(usize, $to); impl_convert!(usize, $to);
impl Convert<DVec2, ()> for $to { impl Convert<DVec2, ()> for $to {
async fn convert(self, _: Footprint, _: ()) -> DVec2 { fn convert(self, _: Footprint, _: ()) -> DVec2 {
DVec2::splat(self as f64) DVec2::splat(self as f64)
} }
} }
File diff suppressed because it is too large. Load diff
+458 -208
View File
@@ -1,10 +1,12 @@
use crate::{ContextFeature, Node, NodeIO, NodeIOTypes, ProtoNodeIdentifier, Type, WasmNotSend}; use crate::concrete;
use dyn_any::{DynAny, StaticType}; use crate::context::{Context, ContextImpl};
use crate::node::Node;
use crate::{ContextFeature, ProtoNodeIdentifier, Type, WasmNotSend, WasmNotSync};
use dyn_any::DynAny;
use graphene_hash::CacheHash;
pub use no_std_types::registry::types; pub use no_std_types::registry::types;
use std::collections::HashMap; use std::collections::HashMap;
use std::marker::PhantomData; use std::hash::Hasher;
use std::ops::Deref;
use std::pin::Pin;
use std::sync::{LazyLock, Mutex}; use std::sync::{LazyLock, Mutex};
// Translation struct between macro and definition // Translation struct between macro and definition
@@ -18,6 +20,8 @@ pub struct NodeMetadata {
pub context_features: Vec<ContextFeature>, pub context_features: Vec<ContextFeature>,
pub memoize: bool, pub memoize: bool,
pub inject_scope: bool, pub inject_scope: bool,
/// The macro appended its hidden `_runtime` and `_source` fields as the last two entries of `fields`.
pub async_source_fields: bool,
} }
// Translation struct between macro and definition // Translation struct between macro and definition
@@ -55,239 +59,485 @@ pub enum RegistryValueSource {
None, None,
Default(&'static str), Default(&'static str),
Scope(&'static str), Scope(&'static str),
SourceId,
} }
type NodeRegistry = LazyLock<Mutex<HashMap<ProtoNodeIdentifier, Vec<(NodeConstructor, NodeIOTypes)>>>>; type NodeRegistry = LazyLock<Mutex<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>>>;
pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::new())); pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::new()));
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new())); pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
pub use crate::NodeIOTypes;
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
pub type DynFuture<'n, T> = Pin<Box<dyn Future<Output = T> + 'n + Send>>; pub type ErasedNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = T> + Send + Sync;
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
pub type DynFuture<'n, T> = Pin<Box<dyn std::future::Future<Output = T> + 'n>>; pub type ErasedNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = T>;
pub type LocalFuture<'n, T> = Pin<Box<dyn Future<Output = T> + 'n>>;
/// Element-independent by erasure; the wire's `Type::Record(El)` keeps element reads proven at wiring.
#[cfg(not(target_family = "wasm"))]
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>, Output = crate::record::RecordValue<'c>> + Send + Sync;
#[cfg(target_family = "wasm")]
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>, Output = crate::record::RecordValue<'c>>;
#[cfg(not(target_family = "wasm"))]
type DynEdge = dyn std::any::Any + Send + Sync;
#[cfg(target_family = "wasm")]
type DynEdge = dyn std::any::Any;
pub fn edge_type<T: 'static>() -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(T)))
}
pub fn record_type<T: 'static>() -> Type {
Type::Record(Box::new(concrete!(T)))
}
pub fn record_edge_type<T: 'static>() -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(record_type::<T>()))
}
/// The record edge type of a token row, generic over the element.
pub fn generic_record_edge_type(name: &'static str) -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Record(Box::new(Type::Generic(std::borrow::Cow::Borrowed(name))))))
}
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
let mut hasher = graphene_hash::FxHasher64::new();
ctx.cache_hash(&mut hasher);
hasher.finish()
}
#[derive(Debug, PartialEq)]
pub enum ConstructionError {
Arity { expected: usize, got: usize },
Type { expected: Box<Type>, found: Box<Type> },
MissingLayout,
}
pub struct SharedEdge<N: ?Sized> {
ptr: std::ptr::NonNull<N>,
own: std::sync::Arc<N>,
}
impl<N: ?Sized> SharedEdge<N> {
pub fn new(own: std::sync::Arc<N>) -> Self {
Self {
ptr: std::ptr::NonNull::from(&*own),
own,
}
}
pub fn share(&self) -> Self {
Self { ptr: self.ptr, own: self.own.clone() }
}
}
// SAFETY: `ptr` is derived from the owned Arc and never mutated through, so the edge is exactly as
// thread safe as the payload it shares.
unsafe impl<N: ?Sized + Send + Sync> Send for SharedEdge<N> {}
// SAFETY: as in Send.
unsafe impl<N: ?Sized + Send + Sync> Sync for SharedEdge<N> {}
impl<Input, N> Node<Input> for SharedEdge<N>
where
N: Node<Input> + ?Sized,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> crate::gpoll::GPoll<Self::Output> {
// Every node advances the record stack by exactly its own frame: it keeps
// its output and reclaims its inputs. A mismatch is a leaked or
// over-released frame.
#[cfg(debug_assertions)]
let sp_before = crate::record::stack::sp();
// SAFETY: `own` keeps the payload alive for `self`'s lifetime and Arc
// payloads are address stable.
let result = unsafe { self.ptr.as_ref() }.eval(input);
#[cfg(debug_assertions)]
debug_assert_eq!(
crate::record::stack::sp(),
sp_before + self.layout().frame_bytes(),
"{} left the record stack misaligned",
std::any::type_name::<N>(),
);
result
}
fn extent(&self, input: &Input) -> crate::gpoll::GPoll<crate::gpoll::Extent> {
// SAFETY: as in eval.
unsafe { self.ptr.as_ref() }.extent(input)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
// SAFETY: as in eval.
unsafe { self.ptr.as_ref() }.serialize()
}
fn layout(&self) -> &crate::record::Layout {
// SAFETY: as in eval.
unsafe { self.ptr.as_ref() }.layout()
}
fn eval_batch<'a>(&'a self, input: &'a Input, range: std::ops::Range<u64>, scratch: Option<&'a mut [std::mem::MaybeUninit<Self::Output>]>) -> crate::node::BatchStatus<'a, Self::Output>
where
Input: crate::context::InjectIndex + Copy,
{
// SAFETY: as in eval.
unsafe { self.ptr.as_ref() }.eval_batch(input, range, scratch)
}
}
pub struct EdgeHandle {
node: Box<DynEdge>,
share: fn(&DynEdge) -> Box<DynEdge>,
serialize: fn(&DynEdge) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
layout: fn(&DynEdge) -> Option<&crate::record::Layout>,
ty: Type,
}
impl std::fmt::Debug for EdgeHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EdgeHandle").field("ty", &self.ty).finish_non_exhaustive()
}
}
// SAFETY: wasm is single threaded, so the marker-free payload never actually crosses a thread.
#[cfg(target_family = "wasm")]
unsafe impl Send for EdgeHandle {}
// SAFETY: as in Send.
#[cfg(target_family = "wasm")]
unsafe impl Sync for EdgeHandle {}
impl EdgeHandle {
pub fn new<T: 'static>(node: std::sync::Arc<ErasedNode<T>>) -> Self {
Self::new_erased(node, edge_type::<T>())
}
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
Self::new_erased(node, record_edge_type::<T>())
}
pub fn new_erased<N>(node: std::sync::Arc<N>, ty: Type) -> Self
where
N: ?Sized + 'static + for<'c> Node<ContextImpl<'c>>,
SharedEdge<N>: WasmNotSend + WasmNotSync,
{
Self {
node: Box::new(SharedEdge::new(node)),
share: |edge| Box::new(edge.downcast_ref::<SharedEdge<N>>().expect("share hook matches the stored edge type").share()),
serialize: |edge| Node::<ContextImpl>::serialize(edge.downcast_ref::<SharedEdge<N>>().expect("serialize hook matches the stored edge type")),
layout: |edge| Some(Node::<ContextImpl>::layout(edge.downcast_ref::<SharedEdge<N>>().expect("layout hook matches the stored edge type"))),
ty,
}
}
pub fn ty(&self) -> &Type {
&self.ty
}
pub fn duplicate(&self) -> Self {
Self {
node: (self.share)(&*self.node),
share: self.share,
serialize: self.serialize,
layout: self.layout,
ty: self.ty.clone(),
}
}
pub fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(self.serialize)(&*self.node)
}
pub fn layout(&self) -> Option<&crate::record::Layout> {
(self.layout)(&*self.node)
}
pub fn downcast<T: 'static>(self) -> Result<SharedEdge<ErasedNode<T>>, ConstructionError> {
self.downcast_erased(edge_type::<T>())
}
pub fn downcast_record<T: 'static>(self) -> Result<SharedEdge<ErasedRecordNode>, ConstructionError> {
self.downcast_erased(record_edge_type::<T>())
}
pub fn downcast_erased<N: ?Sized + 'static>(self, expected: Type) -> Result<SharedEdge<N>, ConstructionError> {
let found = self.ty;
self.node.downcast::<SharedEdge<N>>().map(|edge| *edge).map_err(|_| ConstructionError::Type {
expected: Box::new(expected),
found: Box::new(found),
})
}
}
pub type NodeConstructor = fn(Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError>;
#[derive(Clone)]
pub struct RegistryEntry {
pub io: NodeIOTypes,
pub constructor: NodeConstructor,
}
pub fn construct(entry: &RegistryEntry, inputs: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
if inputs.len() != entry.io.inputs.len() {
return Err(ConstructionError::Arity {
expected: entry.io.inputs.len(),
got: inputs.len(),
});
}
for (handle, expected) in inputs.iter().zip(&entry.io.inputs) {
if handle.ty() != expected {
return Err(ConstructionError::Type {
expected: Box::new(expected.clone()),
found: Box::new(handle.ty().clone()),
});
}
}
(entry.constructor)(inputs)
}
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
pub type Any<'n> = Box<dyn DynAny<'n> + 'n + Send>; pub type Any<'n> = Box<dyn DynAny<'n> + 'n + Send>;
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
pub type Any<'n> = Box<dyn DynAny<'n> + 'n>; pub type Any<'n> = Box<dyn DynAny<'n> + 'n>;
pub type FutureAny<'n> = DynFuture<'n, Any<'n>>;
// TODO: is this safe? This is assumed to be send+sync.
#[cfg(not(target_family = "wasm"))]
pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n + Send + Sync;
#[cfg(target_family = "wasm")]
pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n;
pub type TypeErasedPinnedRef<'n> = Pin<&'n TypeErasedNode<'n>>;
pub type TypeErasedRef<'n> = &'n TypeErasedNode<'n>;
pub type TypeErasedBox<'n> = Box<TypeErasedNode<'n>>;
pub type TypeErasedPinned<'n> = Pin<Box<TypeErasedNode<'n>>>;
pub type SharedNodeContainer = std::sync::Arc<NodeContainer>; #[cfg(test)]
mod tests {
use super::*;
use crate::SourceId;
use crate::arena::Arena;
use crate::context::{Ctx, EvalScope, ExtractArena};
use crate::gpoll::GPoll;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
pub type NodeConstructor = fn(Vec<SharedNodeContainer>) -> DynFuture<'static, TypeErasedBox<'static>>; struct CountingNode(AtomicU32);
#[derive(Clone)] impl<Input> Node<Input> for CountingNode {
pub struct NodeContainer { type Output = u32;
#[cfg(feature = "dealloc_nodes")]
pub node: *const TypeErasedNode<'static>,
#[cfg(not(feature = "dealloc_nodes"))]
pub node: TypeErasedRef<'static>,
}
impl Deref for NodeContainer { fn eval(&self, _input: &Input) -> GPoll<u32> {
type Target = TypeErasedNode<'static>; GPoll::Final(self.0.fetch_add(1, Ordering::Relaxed) + 1)
#[cfg(feature = "dealloc_nodes")]
fn deref(&self) -> &Self::Target {
unsafe { &*(self.node) }
#[cfg(not(feature = "dealloc_nodes"))]
self.node
}
#[cfg(not(feature = "dealloc_nodes"))]
fn deref(&self) -> &Self::Target {
self.node
}
}
/// # Safety
/// Marks NodeContainer as Sync. This dissallows the use of threadlocal storage for nodes as this would invalidate references to them.
// TODO: implement this on a higher level wrapper to avoid missuse
#[cfg(feature = "dealloc_nodes")]
unsafe impl Send for NodeContainer {}
#[cfg(feature = "dealloc_nodes")]
unsafe impl Sync for NodeContainer {}
#[cfg(feature = "dealloc_nodes")]
impl Drop for NodeContainer {
fn drop(&mut self) {
unsafe { self.dealloc_unchecked() }
}
}
impl std::fmt::Debug for NodeContainer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NodeContainer").finish()
}
}
impl NodeContainer {
pub fn new(node: TypeErasedBox<'static>) -> SharedNodeContainer {
let node = Box::leak(node);
Self { node }.into()
}
#[cfg(feature = "dealloc_nodes")]
unsafe fn dealloc_unchecked(&mut self) {
unsafe {
drop(Box::from_raw(self.node as *mut TypeErasedNode));
} }
} }
}
/// Boxes the input and downcasts the output. struct ValueNode<T>(T);
/// Wraps around a node taking Box<dyn DynAny> and returning Box<dyn DynAny>
#[derive(Clone)] impl<T: Clone, Input> Node<Input> for ValueNode<T> {
pub struct DowncastBothNode<I, O> { type Output = T;
node: SharedNodeContainer,
_i: PhantomData<I>, fn eval(&self, _input: &Input) -> GPoll<T> {
_o: PhantomData<O>, GPoll::Final(self.0.clone())
} }
impl<'input, O, I> Node<'input, I> for DowncastBothNode<I, O> }
where
O: 'input + StaticType + WasmNotSend, struct LendNode(String);
I: 'input + StaticType + WasmNotSend,
{ impl<'e, Input: Ctx + ExtractArena<ArenaRef = &'e Arena>> Node<Input> for LendNode {
type Output = DynFuture<'input, O>; type Output = &'e String;
#[inline]
#[track_caller] fn eval(&self, input: &Input) -> GPoll<&'e String> {
fn eval(&'input self, input: I) -> Self::Output { match input.arena().alloc(self.0.clone()) {
Some((parked, _)) => GPoll::Final(parked),
None => GPoll::arena_exhausted(),
}
}
}
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
EvalScope::new(Some(0.5), None, None, generations, arena)
}
#[test]
fn borrow_carrying_value_types_wire_through_the_general_constructor() {
struct SplitBorrow<'c>(&'c str, usize);
struct SplitNode<Node0> {
content: Node0,
}
impl<'e, Input, Node0> Node<Input> for SplitNode<Node0>
where
Input: Ctx,
Node0: Node<Input, Output = &'e String>,
{ {
let node_name = self.node.node_name(); type Output = SplitBorrow<'e>;
let input = Box::new(input);
let future = self.node.eval(input); fn eval(&self, input: &Input) -> GPoll<SplitBorrow<'e>> {
Box::pin(async move { self.content.eval(input).map(|value| SplitBorrow(value, value.len()))
let out = dyn_any::downcast(future.await).unwrap_or_else(|e| panic!("DowncastBothNode wrong output type: {e} in: \n{node_name}")); }
*out
})
} }
}
fn reset(&self) {
self.node.reset();
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> { type ErasedSplitEdge = dyn for<'c> Node<ContextImpl<'c>, Output = SplitBorrow<'c>> + Send + Sync;
self.node.serialize()
}
}
impl<I, O> DowncastBothNode<I, O> {
pub const fn new(node: SharedNodeContainer) -> Self {
Self {
node,
_i: PhantomData,
_o: PhantomData,
}
}
}
pub struct FutureWrapperNode<Node> {
node: Node,
}
impl<'i, T: 'i + WasmNotSend, N> Node<'i, T> for FutureWrapperNode<N> let arena = Arena::new(4096).unwrap();
where let generations = [];
N: Node<'i, T, Output: WasmNotSend> + WasmNotSend, let scope = scope_fixture(&generations, &arena);
{ let ctx = ContextImpl::root(&scope);
type Output = DynFuture<'i, N::Output>;
#[inline(always)]
fn eval(&'i self, input: T) -> Self::Output {
let result = self.node.eval(input);
Box::pin(async move { result })
}
#[inline(always)]
fn reset(&self) {
self.node.reset();
}
#[inline(always)] let node: Arc<ErasedSplitEdge> = Arc::new(SplitNode {
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> { content: LendNode("held".to_string()),
self.node.serialize() });
} let handle = EdgeHandle::new_erased(node, concrete!(SplitBorrow<'static>));
} assert_eq!(*handle.ty(), concrete!(SplitBorrow<'static>));
impl<N> FutureWrapperNode<N> { let wired = handle.downcast_erased::<ErasedSplitEdge>(concrete!(SplitBorrow<'static>)).unwrap();
pub const fn new(node: N) -> Self { let GPoll::Final(split) = wired.eval(&ctx) else {
Self { node } panic!("borrow-carrying output must eval through the erased edge");
}
}
pub struct DynAnyNode<I, O, Node> {
node: Node,
_i: PhantomData<I>,
_o: PhantomData<O>,
}
impl<'input, I, O, N> Node<'input, Any<'input>> for DynAnyNode<I, O, N>
where
I: 'input + StaticType + WasmNotSend,
O: 'input + StaticType + WasmNotSend,
N: 'input + Node<'input, I, Output = DynFuture<'input, O>>,
{
type Output = FutureAny<'input>;
#[inline]
fn eval(&'input self, input: Any<'input>) -> Self::Output {
let node_name = std::any::type_name::<N>();
let output = |input| {
let result = self.node.eval(input);
async move { Box::new(result.await) as Any<'input> }
}; };
match dyn_any::downcast(input) { assert_eq!(split.0, "held");
Ok(input) => Box::pin(output(*input)), assert_eq!(split.1, 4);
Err(e) => panic!("DynAnyNode Input, {e} in:\n{node_name}"), }
#[test]
fn derive_ctx_repeat_pushes_index_levels_through_the_erased_edge() {
use crate::context::{DeriveCtx, Derived, ExtractIndex};
struct RepeatNode<Node0> {
content: Node0,
} }
}
fn reset(&self) { impl<C, T, Node0> Node<C> for RepeatNode<Node0>
self.node.reset(); where
} C: Ctx + DeriveCtx,
Node0: for<'x> Node<Derived<'x, C>, Output = T>,
{
type Output = Vec<T>;
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> { fn eval(&self, input: &C) -> GPoll<Vec<T>> {
self.node.serialize() let spilled = input.index_head();
} let mut result = Vec::new();
} for index in 0..3 {
impl<'input, I, O, N> DynAnyNode<I, O, N> let derived = input.promoted(&spilled, index);
where match self.content.eval(&derived) {
I: 'input + StaticType, GPoll::Final(value) => result.push(value),
O: 'input + StaticType, other => return other.map(|_| Vec::new()),
N: 'input + Node<'input, I, Output = DynFuture<'input, O>>, }
{ }
pub const fn new(node: N) -> Self { GPoll::Final(result)
Self { }
node,
_i: PhantomData,
_o: PhantomData,
} }
struct LevelsNode;
impl<Input: ExtractIndex> Node<Input> for LevelsNode {
type Output = Vec<usize>;
fn eval(&self, input: &Input) -> GPoll<Vec<usize>> {
GPoll::Final(input.try_index().map(|levels| levels.collect()).unwrap_or_default())
}
}
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let nested = RepeatNode {
content: RepeatNode { content: LevelsNode },
};
let erased: Box<ErasedNode<Vec<Vec<Vec<usize>>>>> = Box::new(nested);
let GPoll::Final(outer) = erased.eval(&ctx) else {
panic!("nested repeat must evaluate");
};
assert_eq!(outer.len(), 3);
assert_eq!(outer[2][1], vec![1, 2, 0]);
assert_eq!(outer[0][0], vec![0, 0, 0]);
}
#[test]
fn derive_ctx_footprint_replace_reaches_the_content() {
use crate::context::{DeriveCtx, Derived, ExtractFootprint};
use crate::transform::Footprint;
struct ShiftFootprintNode<Node0> {
content: Node0,
}
impl<C, T, Node0> Node<C> for ShiftFootprintNode<Node0>
where
C: Ctx + DeriveCtx + ExtractFootprint,
Node0: for<'x> Node<Derived<'x, C>, Output = T>,
{
type Output = T;
fn eval(&self, input: &C) -> GPoll<T> {
let mut footprint = input.try_footprint().copied().unwrap_or(Footprint::DEFAULT);
footprint.resolution.x += 7;
let derived = input.with_footprint(&footprint);
self.content.eval(&derived)
}
}
struct ResolutionNode;
impl<Input: ExtractFootprint> Node<Input> for ResolutionNode {
type Output = u32;
fn eval(&self, input: &Input) -> GPoll<u32> {
GPoll::Final(input.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0))
}
}
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let graph: Box<ErasedNode<u32>> = Box::new(ShiftFootprintNode {
content: ShiftFootprintNode { content: ResolutionNode },
});
assert_eq!(graph.eval(&ctx), GPoll::Final(Footprint::DEFAULT.resolution.x + 14));
}
#[test]
fn construct_checks_arity_and_types() {
fn construct_strlen(args: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
let mut args = args.into_iter();
let value = args.next().ok_or(ConstructionError::Arity { expected: 1, got: 0 })?.downcast::<String>()?;
drop(value);
Ok(EdgeHandle::new(Arc::new(ValueNode(0u32)) as Arc<ErasedNode<u32>>))
}
let entry = RegistryEntry {
io: NodeIOTypes::new(concrete!(Context), concrete!(u32), vec![edge_type::<String>()]),
constructor: construct_strlen,
};
let owned = EdgeHandle::new(Arc::new(ValueNode("typed".to_string())) as Arc<ErasedNode<String>>);
assert!(construct(&entry, vec![owned]).is_ok());
assert_eq!(construct(&entry, vec![]).unwrap_err(), ConstructionError::Arity { expected: 1, got: 0 });
let mistyped = EdgeHandle::new(Arc::new(ValueNode(1.0f64)) as Arc<ErasedNode<f64>>);
assert_eq!(
construct(&entry, vec![mistyped]).unwrap_err(),
ConstructionError::Type {
expected: Box::new(edge_type::<String>()),
found: Box::new(edge_type::<f64>()),
}
);
}
#[test]
fn duplicated_edges_share_one_instance_and_outlive_each_other() {
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let handle = EdgeHandle::new(Arc::new(CountingNode(AtomicU32::new(0))) as Arc<ErasedNode<u32>>);
let duplicate = handle.duplicate();
assert_eq!(*duplicate.ty(), edge_type::<u32>());
let first = handle.downcast::<u32>().unwrap();
let second = duplicate.downcast::<u32>().unwrap();
assert_eq!(first.eval(&ctx), GPoll::Final(1));
assert_eq!(second.eval(&ctx), GPoll::Final(2));
drop(first);
assert_eq!(second.eval(&ctx), GPoll::Final(3));
} }
} }
pub struct PanicNode<I: WasmNotSend, O: WasmNotSend>(PhantomData<I>, PhantomData<O>);
impl<'i, I: 'i + WasmNotSend, O: 'i + WasmNotSend> Node<'i, I> for PanicNode<I, O> {
type Output = O;
fn eval(&'i self, _: I) -> Self::Output {
unimplemented!("This node should never be evaluated")
}
}
impl<I: WasmNotSend, O: WasmNotSend> PanicNode<I, O> {
pub const fn new() -> Self {
Self(PhantomData, PhantomData)
}
}
impl<I: WasmNotSend, O: WasmNotSend> Default for PanicNode<I, O> {
fn default() -> Self {
Self::new()
}
}
// TODO: Evaluate safety
unsafe impl<I: WasmNotSend, O: WasmNotSend> Sync for PanicNode<I, O> {}
@@ -0,0 +1,665 @@
use crate::SourceId;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
#[cfg(not(target_family = "wasm"))]
pub type SourceFuture<T = ()> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
#[cfg(target_family = "wasm")]
pub type SourceFuture<T = ()> = Pin<Box<dyn Future<Output = T> + 'static>>;
#[cfg(not(target_family = "wasm"))]
pub type DynRuntime = dyn Runtime + Send + Sync;
#[cfg(target_family = "wasm")]
pub type DynRuntime = dyn Runtime;
pub trait Runtime {
/// Returns true when the future completed during the call, so its result is already observable.
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool;
}
#[derive(Clone)]
pub struct RuntimeHandle(pub Arc<DynRuntime>);
// SAFETY: wasm is single threaded, so the handle never actually crosses a thread.
#[cfg(target_family = "wasm")]
unsafe impl Send for RuntimeHandle {}
// SAFETY: as in Send.
#[cfg(target_family = "wasm")]
unsafe impl Sync for RuntimeHandle {}
impl std::fmt::Debug for RuntimeHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RuntimeHandle").finish_non_exhaustive()
}
}
impl graphene_hash::CacheHash for RuntimeHandle {
fn cache_hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
}
pub trait Spawner {
/// Returns true when the task completed during the call, so its result is already observable.
fn spawn(&self, task: SourceFuture) -> bool;
}
/// Polls `task` once with a no-op waker, returning true if it completed.
pub fn poll_once(task: &mut SourceFuture) -> bool {
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
task.as_mut().poll(&mut context).is_ready()
}
#[cfg(not(target_family = "wasm"))]
pub type DynSpawner = dyn Spawner + Send + Sync;
#[cfg(target_family = "wasm")]
pub type DynSpawner = dyn Spawner;
#[cfg(not(target_family = "wasm"))]
pub type DynNotifier = dyn Fn() + Send + Sync;
#[cfg(target_family = "wasm")]
pub type DynNotifier = dyn Fn();
impl<S: Spawner + ?Sized> Spawner for Box<S> {
fn spawn(&self, task: SourceFuture) -> bool {
(**self).spawn(task)
}
}
/// Polls each task once inline. Tasks that are not immediately ready never complete.
pub struct NoopSpawner;
impl Spawner for NoopSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
log::warn!("async source is not immediately ready and no host spawner is wired; the task is dropped");
false
}
}
pub type DynGraphRuntime = GraphRuntime<Box<DynSpawner>>;
impl Default for RuntimeHandle {
fn default() -> Self {
Self(Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>)))
}
}
pub struct GraphRuntime<S> {
generations: Arc<Mutex<HashMap<SourceId, u64>>>,
dirty: Arc<AtomicBool>,
notifier: Arc<Mutex<Arc<DynNotifier>>>,
spawner: S,
}
// SAFETY: wasm is single threaded, so the runtime never actually crosses a thread.
#[cfg(target_family = "wasm")]
unsafe impl<S> Send for GraphRuntime<S> {}
// SAFETY: as in Send.
#[cfg(target_family = "wasm")]
unsafe impl<S> Sync for GraphRuntime<S> {}
impl<S> GraphRuntime<S> {
pub fn new(spawner: S) -> Self {
Self {
generations: Arc::default(),
dirty: Arc::default(),
notifier: Arc::new(Mutex::new(Arc::new(|| {}))),
spawner,
}
}
pub fn set_notifier(&self, notifier: Arc<DynNotifier>) {
*self.notifier.lock().unwrap_or_else(PoisonError::into_inner) = notifier;
}
pub fn retain_sources(&self, live: &[SourceId]) {
let mut generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
generations.retain(|source, _| live.contains(source));
for source in live {
generations.entry(*source).or_insert(0);
}
}
pub fn snapshot(&self) -> Vec<(SourceId, u64)> {
let generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect();
snapshot.sort_unstable();
snapshot
}
pub fn take_dirty(&self) -> bool {
self.dirty.swap(false, Ordering::Acquire)
}
pub fn spawner(&self) -> &S {
&self.spawner
}
}
impl<S: Spawner> Runtime for GraphRuntime<S> {
fn spawn(&self, source: SourceId, mut future: SourceFuture) -> bool {
let generations = Arc::clone(&self.generations);
let dirty = Arc::clone(&self.dirty);
let notifier = Arc::clone(&self.notifier);
let mut first = true;
self.spawner.spawn(Box::pin(std::future::poll_fn(move |task_context| {
let poll = future.as_mut().poll(task_context);
if poll.is_ready() && !first {
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(generation) = generations.get_mut(&source) {
*generation += 1;
dirty.store(true, Ordering::Release);
drop(generations);
let notifier = Arc::clone(&notifier.lock().unwrap_or_else(PoisonError::into_inner));
notifier();
}
}
first = false;
poll
})))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::arena::Arena;
use crate::context::{ContextImpl, Ctx, CtxSnapshot, EvalScope, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots};
use crate::gpoll::GPoll;
use crate::node::Node;
use crate::record::{Layout, RecordExtract, RecordLift, element_write, stack};
use crate::transform::Footprint;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, Ordering};
#[derive(Default)]
struct MockRuntime {
futures: Mutex<Vec<(SourceId, SourceFuture)>>,
}
impl Runtime for MockRuntime {
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool {
self.futures.lock().unwrap().push((source, future));
false
}
}
impl MockRuntime {
fn drain(&self) -> Vec<SourceId> {
let futures = std::mem::take(&mut *self.futures.lock().unwrap());
let mut task_ctx = std::task::Context::from_waker(std::task::Waker::noop());
futures
.into_iter()
.map(|(source, mut future)| {
assert!(future.as_mut().poll(&mut task_ctx).is_ready());
source
})
.collect()
}
}
#[derive(Default)]
struct CollectSpawner {
tasks: Mutex<Vec<SourceFuture>>,
}
impl Spawner for CollectSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
self.tasks.lock().unwrap().push(task);
false
}
}
struct YieldOnce(bool);
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, task_context: &mut std::task::Context<'_>) -> std::task::Poll<()> {
if self.0 {
return std::task::Poll::Ready(());
}
self.0 = true;
task_context.waker().wake_by_ref();
std::task::Poll::Pending
}
}
fn yield_once() -> YieldOnce {
YieldOnce(false)
}
impl CollectSpawner {
fn drain(&self) -> usize {
let tasks = std::mem::take(&mut *self.tasks.lock().unwrap());
let mut task_ctx = std::task::Context::from_waker(std::task::Waker::noop());
let count = tasks.len();
for mut task in tasks {
assert!(task.as_mut().poll(&mut task_ctx).is_ready());
}
count
}
}
struct SourceNode<T>(T);
impl<T: Clone, Input> Node<Input> for SourceNode<T> {
type Output = T;
fn eval(&self, _input: &Input) -> GPoll<T> {
GPoll::Final(self.0.clone())
}
}
fn element_layout<T: Clone + Send + Sync + 'static>() -> Layout {
Layout::default().with_writes(0, element_write::<T>(), &[])
}
fn lifted<T: Clone + Send + Sync + 'static>(value: T) -> RecordLift<T, SourceNode<T>> {
RecordLift::new(SourceNode(value))
}
fn extract<El: Clone + Send + Sync + 'static, N>(graph: N) -> RecordExtract<El, N> {
stack::reserve(1 << 12);
RecordExtract::new(graph, &element_layout::<El>())
}
static SLOW_DOUBLE_RUNS: AtomicU32 = AtomicU32::new(0);
#[node_macro::node(category(""))]
async fn slow_double(_: impl Ctx, value: f64) -> f64 {
SLOW_DOUBLE_RUNS.fetch_add(1, Ordering::Relaxed);
value * 2.
}
fn stand_in(_value: &f64) -> f64 {
-1.
}
#[node_macro::node(category(""), placeholder(stand_in))]
async fn preview_double(_: impl Ctx, value: f64) -> f64 {
value * 2.
}
#[node_macro::node(category(""), placeholder(stand_in), no_partial)]
async fn strict_double(_: impl Ctx, value: f64) -> f64 {
value * 2.
}
#[node_macro::node(category(""))]
async fn snapshot_resolution(ctx: CtxSnapshot, _primary: ()) -> u32 {
ctx.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0)
}
#[node_macro::node(category(""))]
async fn snapshot_vararg(ctx: CtxSnapshot, _primary: ()) -> f64 {
ctx.vararg(0).ok().and_then(|slot| slot.downcast_ref::<f64>()).copied().unwrap_or(0.)
}
static STAGED_RUNS: AtomicU32 = AtomicU32::new(0);
#[node_macro::node(category(""))]
fn staged_double(_: impl Ctx, value: f64) -> SourceFuture<f64> {
STAGED_RUNS.fetch_add(1, Ordering::Relaxed);
Box::pin(async move { value * 2. })
}
#[node_macro::node(category(""))]
fn staged_sum(ctx: impl Ctx, value: f64, addend: impl Node<Context<'_>, Output = f64>) -> Result<SourceFuture<f64>, crate::gpoll::Interrupt> {
let addend = addend.eval(ctx)?;
Ok(Box::pin(async move { value + addend }))
}
struct GatedSource(Arc<std::sync::atomic::AtomicBool>, f64);
impl<Input> Node<Input> for GatedSource {
type Output = f64;
fn eval(&self, _input: &Input) -> GPoll<f64> {
match self.0.load(Ordering::Relaxed) {
true => GPoll::Final(self.1),
false => GPoll::Pending,
}
}
}
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
EvalScope::new(None, None, None, generations, arena)
}
#[test]
fn async_source_spawns_once_and_lands_via_the_slot() {
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(SlowDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(7u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 0);
assert_eq!(runtime.drain(), vec![7]);
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 1);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 1);
}
#[test]
fn async_source_reports_the_placeholder_while_in_flight() {
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(PreviewDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(1u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Partial(-1.0));
runtime.drain();
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
}
#[test]
fn no_partial_maps_the_placeholder_frame_to_pending() {
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(StrictDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(2u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
}
#[test]
fn prologue_runs_sync_and_spawns_once() {
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(StagedDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(8u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "the prologue runs synchronously on the miss");
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "in flight must not rerun the prologue");
assert_eq!(runtime.drain(), vec![8]);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1);
}
#[test]
fn prologue_interrupt_defers_the_spawn() {
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let gate = Arc::new(std::sync::atomic::AtomicBool::new(false));
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(StagedSumNode::new(
lifted(40.0f64),
RecordLift::<f64, _>::new(GatedSource(gate.clone(), 2.0)),
lifted(RuntimeHandle(runtime.clone())),
lifted(9u64),
&element_layout::<f64>(),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(runtime.drain(), Vec::<SourceId>::new(), "an interrupted prologue must not spawn or claim the slot");
gate.store(true, Ordering::Relaxed);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(runtime.drain(), vec![9]);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
}
#[test]
fn async_kernels_read_captured_varargs() {
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let payload = 21.5f64;
let link = VarArgLink {
args: VarArgSlots::Single(&payload),
outer: None,
};
let ctx = root.with_varargs(&link);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(SnapshotVarargNode::new(
lifted(()),
lifted(RuntimeHandle(runtime.clone())),
lifted(5u64),
&element_layout::<()>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(21.5));
}
#[test]
fn async_kernels_read_the_captured_context_snapshot() {
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let footprint = Footprint::DEFAULT;
let ctx = root.with_footprint(&footprint);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<u32, _>(SnapshotResolutionNode::new(
lifted(()),
lifted(RuntimeHandle(runtime.clone())),
lifted(3u64),
&element_layout::<()>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(Footprint::DEFAULT.resolution.x));
}
#[test]
fn the_epilogue_bumps_the_generation_and_sets_dirty() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
assert_eq!(runtime.snapshot(), vec![(7, 0)], "no bump before the future completes");
assert!(!runtime.take_dirty());
assert_eq!(runtime.spawner().drain(), 1);
assert_eq!(runtime.snapshot(), vec![(7, 1)]);
assert!(runtime.take_dirty());
assert!(!runtime.take_dirty(), "take_dirty drains the flag");
}
#[test]
fn the_epilogue_notifies_after_setting_dirty() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
let observed_dirty = Arc::new(AtomicBool::new(false));
let dirty_at_notify = Arc::clone(&runtime.dirty);
let observed = Arc::clone(&observed_dirty);
runtime.set_notifier(Arc::new(move || {
observed.store(dirty_at_notify.load(Ordering::Acquire), Ordering::Relaxed);
}));
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
assert_eq!(runtime.spawner().drain(), 1);
assert!(observed_dirty.load(Ordering::Relaxed), "the notifier must observe the dirty flag already set");
}
#[test]
fn the_epilogue_of_a_removed_source_does_not_notify() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
let notified = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&notified);
runtime.set_notifier(Arc::new(move || flag.store(true, Ordering::Relaxed)));
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
runtime.retain_sources(&[]);
assert_eq!(runtime.spawner().drain(), 1);
assert!(!notified.load(Ordering::Relaxed));
}
#[test]
fn the_epilogue_of_a_removed_source_is_inert() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
runtime.retain_sources(&[]);
assert_eq!(runtime.spawner().drain(), 1);
assert_eq!(runtime.snapshot(), Vec::<(SourceId, u64)>::new());
assert!(!runtime.take_dirty(), "a removed source must not invalidate");
}
#[test]
fn retain_sources_preserves_live_generations() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
runtime.spawner().drain();
runtime.retain_sources(&[7, 9]);
assert_eq!(runtime.snapshot(), vec![(7, 1), (9, 0)]);
runtime.retain_sources(&[9]);
assert_eq!(runtime.snapshot(), vec![(9, 0)]);
}
#[node_macro::node(category(""))]
async fn epilogue_double(_: impl Ctx, value: f64) -> f64 {
yield_once().await;
value * 2.
}
#[node_macro::node(category(""))]
async fn inline_double(_: impl Ctx, value: f64) -> f64 {
value * 2.
}
#[test]
fn an_immediately_ready_task_completes_inline_without_invalidating() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
assert!(Runtime::spawn(&runtime, 7, Box::pin(async {})));
assert_eq!(runtime.spawner().drain(), 0);
assert_eq!(runtime.snapshot(), vec![(7, 0)], "inline completion must not bump the generation");
assert!(!runtime.take_dirty());
}
#[test]
fn an_immediately_ready_kernel_returns_final_on_the_first_eval() {
let arena = Arena::new(64).unwrap();
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
runtime.retain_sources(&[13]);
let graph = extract::<f64, _>(InlineDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(13u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let snapshot = runtime.snapshot();
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
let ctx = ContextImpl::root(&scope);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
assert!(!runtime.take_dirty());
assert_eq!(runtime.snapshot(), vec![(13, 0)]);
assert_eq!(runtime.spawner().drain(), 0);
}
#[test]
fn a_source_slot_lands_through_the_runtime_while_downstream_keys_invalidate() {
let arena = Arena::new(64).unwrap();
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
runtime.retain_sources(&[11]);
let graph = extract::<f64, _>(EpilogueDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(11u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let snapshot = runtime.snapshot();
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
let ctx = ContextImpl::root(&scope);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert!(!runtime.take_dirty());
assert_eq!(runtime.spawner().drain(), 1);
assert!(runtime.take_dirty());
let bumped = runtime.snapshot();
assert_eq!(bumped, vec![(11, 1)]);
let bumped_scope = EvalScope::new(None, None, None, &bumped, &arena);
let bumped_ctx = ContextImpl::root(&bumped_scope);
assert_eq!(Node::eval(&graph, &bumped_ctx), GPoll::Final(42.0), "the own-generation-excluded key replays the landed slot");
assert_eq!(runtime.spawner().drain(), 0, "a slot hit must not respawn");
let downstream_key = crate::registry::cache_key(&ContextImpl::root(&scope));
let bumped_downstream_key = crate::registry::cache_key(&ContextImpl::root(&bumped_scope));
assert_ne!(downstream_key, bumped_downstream_key, "unretained keys see the bump");
}
}
+9 -1
View File
@@ -235,6 +235,8 @@ pub enum Type {
Fn(Box<Type>, Box<Type>), Fn(Box<Type>, Box<Type>),
/// Represents a future which promises to return the inner type. /// Represents a future which promises to return the inner type.
Future(Box<Type>), Future(Box<Type>),
/// A packed record wire over the element type; the layout stays node-resident metadata.
Record(Box<Type>),
} }
impl Default for Type { impl Default for Type {
@@ -308,6 +310,7 @@ impl Type {
Self::Concrete(ty) => Some(ty.size), Self::Concrete(ty) => Some(ty.size),
Self::Fn(_, _) => None, Self::Fn(_, _) => None,
Self::Future(_) => None, Self::Future(_) => None,
Self::Record(_) => None,
} }
} }
@@ -317,6 +320,7 @@ impl Type {
Self::Concrete(ty) => Some(ty.align), Self::Concrete(ty) => Some(ty.align),
Self::Fn(_, _) => None, Self::Fn(_, _) => None,
Self::Future(_) => None, Self::Future(_) => None,
Self::Record(_) => None,
} }
} }
@@ -326,6 +330,7 @@ impl Type {
Self::Concrete(_) => self, Self::Concrete(_) => self,
Self::Fn(_, output) => output.nested_type(), Self::Fn(_, output) => output.nested_type(),
Self::Future(output) => output.nested_type(), Self::Future(output) => output.nested_type(),
Self::Record(inner) => inner.nested_type(),
} }
} }
@@ -338,6 +343,7 @@ impl Type {
Self::Concrete(_) => None, Self::Concrete(_) => None,
Self::Fn(_, output) => output.replace_nested(f), Self::Fn(_, output) => output.replace_nested(f),
Self::Future(output) => output.replace_nested(f), Self::Future(output) => output.replace_nested(f),
Self::Record(inner) => inner.replace_nested(f),
} }
} }
@@ -347,6 +353,7 @@ impl Type {
Type::Concrete(ty) => simplify_identifier_name(&ty.name), Type::Concrete(ty) => simplify_identifier_name(&ty.name),
Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()), Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()),
Type::Future(ty) => ty.identifier_name(), Type::Future(ty) => ty.identifier_name(),
Type::Record(ty) => ty.identifier_name(),
} }
} }
} }
@@ -361,7 +368,7 @@ pub fn simplify_identifier_name(ty: &str) -> String {
/// Converts a Rust-internal type name to its user-facing form. /// Converts a Rust-internal type name to its user-facing form.
pub fn make_type_user_readable(ty: &str) -> String { pub fn make_type_user_readable(ty: &str) -> String {
let ty = ty let ty = ty
.replace("Option<Arc<OwnedContextImpl>>", "Context") .replace("ContextImpl", "Context")
.replace("Raster<CPU>", "Raster") .replace("Raster<CPU>", "Raster")
.replace("Raster<GPU>", "Raster") .replace("Raster<GPU>", "Raster")
.replace("DAffine2", "Transform") .replace("DAffine2", "Transform")
@@ -441,6 +448,7 @@ impl std::fmt::Display for Type {
Type::Concrete(ty) => write!(f, "{ty}"), Type::Concrete(ty) => write!(f, "{ty}"),
Type::Fn(_, return_value) => write!(f, "{return_value}"), Type::Fn(_, return_value) => write!(f, "{return_value}"),
Type::Future(ty) => write!(f, "{ty}"), Type::Future(ty) => write!(f, "{ty}"),
Type::Record(ty) => write!(f, "{ty}"),
} }
} }
} }
+45 -193
View File
@@ -1,103 +1,55 @@
use crate::Node;
use std::cell::{Cell, RefCell, RefMut};
use std::marker::PhantomData;
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct IntNode<const N: u32>;
impl<'i, const N: u32, I> Node<'i, I> for IntNode<N> {
type Output = u32;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
N
}
}
#[derive(Default, Debug, Clone, Copy)]
pub struct ValueNode<T>(pub T);
impl<'i, T: 'i, I> Node<'i, I> for ValueNode<T> {
type Output = &'i T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
&self.0
}
}
impl<T> ValueNode<T> {
pub const fn new(value: T) -> ValueNode<T> {
ValueNode(value)
}
}
impl<T> From<T> for ValueNode<T> {
fn from(value: T) -> Self {
ValueNode::new(value)
}
}
#[derive(Default, Debug, Clone, Copy)]
pub struct AsRefNode<T: AsRef<U>, U>(pub T, PhantomData<U>);
impl<'i, T: 'i + AsRef<U>, U: 'i> Node<'i, ()> for AsRefNode<T, U> {
type Output = &'i U;
#[inline(always)]
fn eval(&'i self, _input: ()) -> Self::Output {
self.0.as_ref()
}
}
impl<T: AsRef<U>, U> AsRefNode<T, U> {
pub const fn new(value: T) -> AsRefNode<T, U> {
AsRefNode(value, PhantomData)
}
}
#[derive(Default, Debug, Clone)]
pub struct RefCellMutNode<T>(pub RefCell<T>);
impl<'i, T: 'i> Node<'i, ()> for RefCellMutNode<T> {
type Output = RefMut<'i, T>;
#[inline(always)]
fn eval(&'i self, _input: ()) -> Self::Output {
self.0.borrow_mut()
}
}
impl<T> RefCellMutNode<T> {
pub const fn new(value: T) -> RefCellMutNode<T> {
RefCellMutNode(RefCell::new(value))
}
}
#[derive(Default)]
pub struct OnceCellNode<T>(pub Cell<T>);
impl<'i, T: Default + 'i, I> Node<'i, I> for OnceCellNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
self.0.replace(T::default())
}
}
impl<T> OnceCellNode<T> {
pub const fn new(value: T) -> OnceCellNode<T> {
OnceCellNode(Cell::new(value))
}
}
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct ClonedNode<T: Clone>(pub T); pub struct ClonedNode<T: Clone>(pub T);
impl<'i, T: Clone + 'i, I> Node<'i, I> for ClonedNode<T> { impl<T: Clone, Input> crate::node::Node<Input> for ClonedNode<T> {
type Output = T; type Output = T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output { fn eval(&self, _input: &Input) -> crate::gpoll::GPoll<T> {
self.0.clone() crate::gpoll::GPoll::Final(self.0.clone())
} }
} }
pub fn value_edge<T: Clone + crate::WasmNotSend + crate::WasmNotSync + 'static>(value: T) -> crate::registry::EdgeHandle {
crate::registry::EdgeHandle::new(std::sync::Arc::new(ClonedNode(value)) as std::sync::Arc<crate::registry::ErasedNode<T>>)
}
/// The node behind every value edge: clones its constant onto the record
/// wire per evaluation.
pub struct ValueSource<T> {
value: T,
layout: crate::record::Layout,
}
impl<T: Clone + Send + Sync + 'static> ValueSource<T> {
pub fn new(value: T) -> Self {
Self {
value,
layout: crate::record::Layout::default().with_writes(0, crate::record::element_write::<T>(), &[]),
}
}
}
impl<'e, C, T> crate::node::Node<C> for ValueSource<T>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
T: Clone + Send + Sync + 'static,
{
type Output = crate::record::RecordValue<'e>;
fn eval(&self, input: &C) -> crate::gpoll::GPoll<crate::record::RecordValue<'e>> {
crate::record::lift_poll(crate::gpoll::GPoll::Final(self.value.clone()), &self.layout, input.arena())
}
fn layout(&self) -> &crate::record::Layout {
&self.layout
}
}
/// The native record edge of a constant.
pub fn record_value_edge<T: Clone + Send + Sync + 'static>(value: T) -> crate::registry::EdgeHandle {
crate::registry::EdgeHandle::new_record::<T>(std::sync::Arc::new(ValueSource::new(value)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
}
impl<T: Clone> ClonedNode<T> { impl<T: Clone> ClonedNode<T> {
pub const fn new(value: T) -> ClonedNode<T> { pub const fn new(value: T) -> ClonedNode<T> {
ClonedNode(value) ClonedNode(value)
@@ -109,103 +61,3 @@ impl<T: Clone> From<T> for ClonedNode<T> {
ClonedNode::new(value) ClonedNode::new(value)
} }
} }
#[derive(Clone, Copy)]
/// The DebugClonedNode logs every time it is evaluated.
/// This is useful for debugging.
pub struct DebugClonedNode<T: Clone>(pub T);
impl<'i, T: Clone + 'i> Node<'i, ()> for DebugClonedNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: ()) -> Self::Output {
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
log::debug!("DebugClonedNode::eval");
self.0.clone()
}
}
impl<T: Clone> DebugClonedNode<T> {
pub const fn new(value: T) -> DebugClonedNode<T> {
DebugClonedNode(value)
}
}
#[derive(Clone, Copy)]
pub struct CopiedNode<T: Copy>(pub T);
impl<'i, T: Copy + 'i, I> Node<'i, I> for CopiedNode<T> {
type Output = T;
#[inline(always)]
fn eval(&'i self, _input: I) -> Self::Output {
self.0
}
}
impl<T: Copy> CopiedNode<T> {
pub const fn new(value: T) -> CopiedNode<T> {
CopiedNode(value)
}
}
#[derive(Default)]
pub struct DefaultNode<T>(PhantomData<T>);
impl<'i, T: Default + 'i, I> Node<'i, I> for DefaultNode<T> {
type Output = T;
fn eval(&'i self, _input: I) -> Self::Output {
T::default()
}
}
impl<T> DefaultNode<T> {
pub fn new() -> Self {
Self(PhantomData)
}
}
#[repr(C)]
/// Return the unit value
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct ForgetNode;
impl<'i, T: 'i> Node<'i, T> for ForgetNode {
type Output = ();
fn eval(&'i self, _input: T) -> Self::Output {}
}
impl ForgetNode {
pub const fn new() -> Self {
ForgetNode
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_int_node() {
let node = IntNode::<5>;
assert_eq!(node.eval(()), 5);
}
#[test]
fn test_value_node() {
let node = ValueNode::new(5);
assert_eq!(node.eval(()), &5);
let type_erased = &node as &dyn for<'a> Node<'a, (), Output = &'a i32>;
assert_eq!(type_erased.eval(()), &5);
}
#[test]
fn test_default_node() {
let node = DefaultNode::<u32>::new();
assert_eq!(node.eval(42), 0);
}
#[test]
#[allow(clippy::unit_cmp)]
fn test_unit_node() {
let node = ForgetNode::new();
assert_eq!(node.eval(()), ());
}
}
@@ -68,6 +68,7 @@ impl_via_hash! {
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl_via_hash! { impl_via_hash! {
String, String,
core::time::Duration,
} }
impl<'a> CacheHash for std::borrow::Cow<'a, str> { impl<'a> CacheHash for std::borrow::Cow<'a, str> {
@@ -235,3 +236,142 @@ impl_tuple!(A, B, C);
impl_tuple!(A, B, C, D); impl_tuple!(A, B, C, D);
impl_tuple!(A, B, C, D, E); impl_tuple!(A, B, C, D, E);
impl_tuple!(A, B, C, D, E, F); impl_tuple!(A, B, C, D, E, F);
/// rustc-hash's polynomial hash with the state pinned to u64, so keys match across native and wasm targets.
/// The state starts at a nonzero seed: zero-initialized fx absorbs leading zero words, which produced
/// a real wrong-value memo hit in the prototype.
#[derive(Clone)]
pub struct FxHasher64 {
hash: u64,
}
const K: u64 = 0xf1357aea2e62a9c5;
const SEED: u64 = 0x517cc1b727220a95;
const SEED1: u64 = 0x243f6a8885a308d3;
const SEED2: u64 = 0x13198a2e03707344;
const PREVENT_TRIVIAL_ZERO_COLLAPSE: u64 = 0xa4093822299f31d0;
impl Default for FxHasher64 {
fn default() -> Self {
Self::new()
}
}
impl FxHasher64 {
pub const fn new() -> Self {
Self { hash: SEED }
}
#[inline]
fn add_to_hash(&mut self, i: u64) {
self.hash = self.hash.wrapping_add(i).wrapping_mul(K);
}
}
impl core::hash::Hasher for FxHasher64 {
#[inline]
fn write(&mut self, bytes: &[u8]) {
self.add_to_hash(hash_bytes(bytes));
}
#[inline]
fn write_u8(&mut self, i: u8) {
self.add_to_hash(i as u64);
}
#[inline]
fn write_u16(&mut self, i: u16) {
self.add_to_hash(i as u64);
}
#[inline]
fn write_u32(&mut self, i: u32) {
self.add_to_hash(i as u64);
}
#[inline]
fn write_u64(&mut self, i: u64) {
self.add_to_hash(i);
}
#[inline]
fn write_u128(&mut self, i: u128) {
self.add_to_hash(i as u64);
self.add_to_hash((i >> 64) as u64);
}
#[inline]
fn write_usize(&mut self, i: usize) {
self.add_to_hash(i as u64);
}
#[inline]
fn finish(&self) -> u64 {
self.hash.rotate_left(26)
}
}
#[inline]
fn multiply_mix(x: u64, y: u64) -> u64 {
let full = (x as u128) * (y as u128);
(full as u64) ^ ((full >> 64) as u64)
}
#[inline]
fn hash_bytes(bytes: &[u8]) -> u64 {
let len = bytes.len();
let mut s0 = SEED1;
let mut s1 = SEED2;
if len <= 16 {
if len >= 8 {
s0 ^= u64::from_le_bytes(bytes[0..8].try_into().unwrap());
s1 ^= u64::from_le_bytes(bytes[len - 8..].try_into().unwrap());
} else if len >= 4 {
s0 ^= u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as u64;
s1 ^= u32::from_le_bytes(bytes[len - 4..].try_into().unwrap()) as u64;
} else if len > 0 {
let lo = bytes[0];
let mid = bytes[len / 2];
let hi = bytes[len - 1];
s0 ^= lo as u64;
s1 ^= ((hi as u64) << 8) | mid as u64;
}
} else {
let mut off = 0;
while off < len - 16 {
let x = u64::from_le_bytes(bytes[off..off + 8].try_into().unwrap());
let y = u64::from_le_bytes(bytes[off + 8..off + 16].try_into().unwrap());
let t = multiply_mix(s0 ^ x, PREVENT_TRIVIAL_ZERO_COLLAPSE ^ y);
s0 = s1;
s1 = t;
off += 16;
}
let suffix = &bytes[len - 16..];
s0 ^= u64::from_le_bytes(suffix[0..8].try_into().unwrap());
s1 ^= u64::from_le_bytes(suffix[8..16].try_into().unwrap());
}
multiply_mix(s0, s1) ^ (len as u64)
}
#[cfg(test)]
mod tests {
use super::FxHasher64;
use core::hash::Hasher;
#[test]
fn leading_zero_words_are_not_absorbed() {
let hash_words = |words: &[u64]| {
let mut hasher = FxHasher64::new();
for &word in words {
hasher.write_u64(word);
}
hasher.finish()
};
assert_ne!(hash_words(&[]), hash_words(&[0]), "a zero word must change the hash of the empty input");
assert_ne!(hash_words(&[0]), hash_words(&[0, 0]), "zero words must accumulate distinct states");
assert_ne!(hash_words(&[0, 7]), hash_words(&[7]), "a leading zero word must not be absorbed");
}
}
+18 -7
View File
@@ -9,17 +9,16 @@ use crate::texture_cache::TextureCache;
use anyhow::Result; use anyhow::Result;
use core_types::Color; use core_types::Color;
use core_types::color::SRGBA8; use core_types::color::SRGBA8;
use futures::lock::Mutex;
use glam::UVec2; use glam::UVec2;
use graphene_application_io::{ApplicationIo, EditorApi}; use graphene_application_io::{ApplicationIo, EditorApi};
use raster_types::Texture; use raster_types::Texture;
use std::sync::Arc; use std::sync::Arc;
use std::sync::Mutex;
use vello::{AaConfig, AaSupport, RenderParams, Renderer, RendererOptions, Scene}; use vello::{AaConfig, AaSupport, RenderParams, Renderer, RendererOptions, Scene};
use wgpu::{Origin3d, TextureAspect}; use wgpu::{Origin3d, TextureAspect};
pub use context::Context as WgpuContext; pub use context::Context as WgpuContext;
pub use context::ContextBuilder as WgpuContextBuilder; pub use context::ContextBuilder as WgpuContextBuilder;
pub use pipeline::AsyncPipeline as AsyncWgpuPipeline;
pub use pipeline::Pipeline as WgpuPipeline; pub use pipeline::Pipeline as WgpuPipeline;
pub use pipeline::PipelineCache as WgpuPipelineCache; pub use pipeline::PipelineCache as WgpuPipelineCache;
pub use rendering::RenderContext; pub use rendering::RenderContext;
@@ -61,6 +60,18 @@ impl std::fmt::Debug for WgpuExecutor {
} }
} }
/// Owned Arc handle carrying the executor as an ordinary wire value.
#[derive(Clone, Debug)]
pub struct WgpuExecutorHandle(pub std::sync::Arc<WgpuExecutor>);
impl std::ops::Deref for WgpuExecutorHandle {
type Target = WgpuExecutor;
fn deref(&self) -> &WgpuExecutor {
&self.0
}
}
impl<'a, T: ApplicationIo<Executor = WgpuExecutor>> From<&'a EditorApi<T>> for &'a WgpuExecutor { impl<'a, T: ApplicationIo<Executor = WgpuExecutor>> From<&'a EditorApi<T>> for &'a WgpuExecutor {
fn from(editor_api: &'a EditorApi<T>) -> Self { fn from(editor_api: &'a EditorApi<T>) -> Self {
editor_api.application_io.as_ref().unwrap().gpu_executor().unwrap() editor_api.application_io.as_ref().unwrap().gpu_executor().unwrap()
@@ -68,8 +79,8 @@ impl<'a, T: ApplicationIo<Executor = WgpuExecutor>> From<&'a EditorApi<T>> for &
} }
impl WgpuExecutor { impl WgpuExecutor {
pub async fn render_vello_scene(&self, scene: &Scene, size: UVec2, context: &RenderContext, background: Option<Color>) -> Result<Texture> { pub fn render_vello_scene(&self, scene: &Scene, size: UVec2, context: &RenderContext, background: Option<Color>) -> Result<Texture> {
let texture = self.request_texture(size).await; let texture = self.request_texture(size);
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default()); let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
@@ -82,7 +93,7 @@ impl WgpuExecutor {
}; };
{ {
let mut renderer = self.inner.vello_renderer.lock().await; let mut renderer = self.inner.vello_renderer.lock().unwrap();
for (image_brush, texture) in context.resource_overrides.iter() { for (image_brush, texture) in context.resource_overrides.iter() {
let texture_view = wgpu::TexelCopyTextureInfoBase { let texture_view = wgpu::TexelCopyTextureInfoBase {
texture: (**texture).clone(), texture: (**texture).clone(),
@@ -109,8 +120,8 @@ impl WgpuExecutor {
pipeline.init::<P>(self); pipeline.init::<P>(self);
} }
pub async fn request_texture(&self, size: UVec2) -> Texture { pub fn request_texture(&self, size: UVec2) -> Texture {
self.inner.texture_cache.lock().await.request_texture(&self.context().device, size) self.inner.texture_cache.lock().unwrap().request_texture(&self.context().device, size)
} }
} }
@@ -1,42 +1,16 @@
use dyn_any::DynAny; use dyn_any::DynAny;
use std::any::Any; use std::any::Any;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, OnceLock}; use std::sync::{Arc, OnceLock};
use crate::WgpuExecutor; use crate::WgpuExecutor;
pub type PipelineFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub trait Pipeline: Any + Send + Sync + Sized { pub trait Pipeline: Any + Send + Sync + Sized {
type Args<'a>; type Args<'a>;
type Out: Send; type Out: Send;
fn create(executor: &WgpuExecutor) -> Self; fn create(executor: &WgpuExecutor) -> Self;
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> PipelineFuture<'a, Self::Out>; fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out;
}
pub trait AsyncPipeline: Any + Send + Sync + Sized {
type Args<'a>;
type Out: Send;
fn create(executor: &WgpuExecutor) -> Self;
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> impl Future<Output = Self::Out> + Send + 'a;
}
impl<P: AsyncPipeline> Pipeline for P {
type Args<'a> = <P as AsyncPipeline>::Args<'a>;
type Out = <P as AsyncPipeline>::Out;
fn create(executor: &WgpuExecutor) -> Self {
<P as AsyncPipeline>::create(executor)
}
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> PipelineFuture<'a, Self::Out> {
Box::pin(<P as AsyncPipeline>::run(self, executor, args))
}
} }
#[derive(Default, Clone, DynAny)] #[derive(Default, Clone, DynAny)]
@@ -51,13 +25,13 @@ impl PipelineCache {
self.pipeline.get_or_init(|| Box::new(P::create(executor))); self.pipeline.get_or_init(|| Box::new(P::create(executor)));
} }
pub async fn run<P: Pipeline>(&self, args: &P::Args<'_>) -> P::Out { pub fn run<P: Pipeline>(&self, args: &P::Args<'_>) -> P::Out {
let executor = self.executor.get().expect("PipelineCache not initialized"); let executor = self.executor.get().expect("PipelineCache not initialized");
let entry = self.pipeline.get().expect("PipelineCache not initialized"); let entry = self.pipeline.get().expect("PipelineCache not initialized");
let pipeline = (&**entry) let pipeline = (**entry)
.downcast_ref::<P>() .downcast_ref::<P>()
.unwrap_or_else(|| panic!("PipelineCache type mismatch: run::<{}>() but init used a different pipeline type", std::any::type_name::<P>(),)); .unwrap_or_else(|| panic!("PipelineCache type mismatch: run::<{}>() but init used a different pipeline type", std::any::type_name::<P>(),));
pipeline.run(executor, args).await pipeline.run(executor, args)
} }
} }
@@ -2,10 +2,10 @@ use crate::WgpuContext;
use crate::shader_runtime::{FULLSCREEN_VERTEX_SHADER_NAME, ShaderRuntime}; use crate::shader_runtime::{FULLSCREEN_VERTEX_SHADER_NAME, ShaderRuntime};
use core_types::list::{Item, List}; use core_types::list::{Item, List};
use core_types::shaders::buffer_struct::BufferStruct; use core_types::shaders::buffer_struct::BufferStruct;
use futures::lock::Mutex;
use raster_types::{GPU, Raster}; use raster_types::{GPU, Raster};
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::{Mutex, PoisonError};
use wgpu::util::{BufferInitDescriptor, DeviceExt}; use wgpu::util::{BufferInitDescriptor, DeviceExt};
use wgpu::{ use wgpu::{
BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingType, Buffer, BufferBinding, BufferBindingType, BufferUsages, ColorTargetState, Face, BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingType, Buffer, BufferBinding, BufferBindingType, BufferUsages, ColorTargetState, Face,
@@ -33,8 +33,8 @@ impl PerPixelAdjustShaderRuntime {
} }
impl ShaderRuntime { impl ShaderRuntime {
pub async fn run_per_pixel_adjust<T: BufferStruct>(&self, shaders: &Shaders<'_>, textures: List<Raster<GPU>>, args: Option<&T>) -> List<Raster<GPU>> { pub fn run_per_pixel_adjust<T: BufferStruct>(&self, shaders: &Shaders<'_>, textures: List<Raster<GPU>>, args: Option<&T>) -> List<Raster<GPU>> {
let mut cache = self.per_pixel_adjust.pipeline_cache.lock().await; let mut cache = self.per_pixel_adjust.pipeline_cache.lock().unwrap_or_else(PoisonError::into_inner);
let pipeline = cache let pipeline = cache
.entry(shaders.fragment_shader_name.to_owned()) .entry(shaders.fragment_shader_name.to_owned())
.or_insert_with(|| PerPixelAdjustGraphicsPipeline::new(&self.context, shaders)); .or_insert_with(|| PerPixelAdjustGraphicsPipeline::new(&self.context, shaders));
@@ -1,9 +1,10 @@
use crate::WgpuExecutor; use crate::WgpuExecutorHandle;
use core_types::Color; use core_types::Color;
use core_types::Ctx; use core_types::Ctx;
use core_types::color::SRGBA8; use core_types::color::SRGBA8;
use core_types::list::{Item, List}; use core_types::list::{Item, List};
use core_types::ops::Convert; use core_types::ops::{Convert, ConvertAsync};
use core_types::runtime::SourceFuture;
use core_types::transform::Footprint; use core_types::transform::Footprint;
use raster_types::Image; use raster_types::Image;
use raster_types::{CPU, GPU, Raster}; use raster_types::{CPU, GPU, Raster};
@@ -38,6 +39,52 @@ fn upload_to_texture(device: &wgpu::Device, queue: &wgpu::Queue, image: &Raster<
) )
} }
/// Passthrough conversion for GPU `List`s - no conversion needed
impl Convert<List<Raster<GPU>>, WgpuExecutorHandle> for List<Raster<GPU>> {
fn convert(self, _: Footprint, _converter: WgpuExecutorHandle) -> List<Raster<GPU>> {
self
}
}
/// Converts a `List<Raster<CPU>>` to `List<Raster<GPU>>` by uploading each image to a texture
impl Convert<List<Raster<GPU>>, WgpuExecutorHandle> for List<Raster<CPU>> {
fn convert(self, _: Footprint, executor: WgpuExecutorHandle) -> List<Raster<GPU>> {
let device = &executor.context().device;
let queue = executor.context().queue.lock();
let list = self
.into_iter()
.map(|row| {
let (image, attributes) = row.into_parts();
let texture = upload_to_texture(device, &queue, &image);
Item::from_parts(Raster::new_gpu(texture), attributes)
})
.collect();
queue.submit([]);
list
}
}
/// Converts single CPU raster to GPU by uploading to texture
impl Convert<Raster<GPU>, WgpuExecutorHandle> for Raster<CPU> {
fn convert(self, _: Footprint, executor: WgpuExecutorHandle) -> Raster<GPU> {
let device = &executor.context().device;
let queue = executor.context().queue.lock();
let texture = upload_to_texture(device, &queue, &self);
queue.submit([]);
Raster::new_gpu(texture)
}
}
/// Passthrough conversion for CPU `List`s - no conversion needed
impl Convert<List<Raster<CPU>>, WgpuExecutorHandle> for List<Raster<CPU>> {
fn convert(self, _: Footprint, _converter: WgpuExecutorHandle) -> List<Raster<CPU>> {
self
}
}
/// Converts a Raster<GPU> texture to Raster<CPU> by downloading the underlying texture data. /// Converts a Raster<GPU> texture to Raster<CPU> by downloading the underlying texture data.
/// ///
/// Assumptions: /// Assumptions:
@@ -142,57 +189,11 @@ impl RasterGpuToRasterCpuConverter {
} }
} }
/// Passthrough conversion for GPU `List`s - no conversion needed
impl<'i> Convert<List<Raster<GPU>>, &'i WgpuExecutor> for List<Raster<GPU>> {
async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<GPU>> {
self
}
}
/// Converts a `List<Raster<CPU>>` to `List<Raster<GPU>>` by uploading each image to a texture
impl<'i> Convert<List<Raster<GPU>>, &'i WgpuExecutor> for List<Raster<CPU>> {
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> List<Raster<GPU>> {
let device = &executor.context().device;
let queue = executor.context().queue.lock();
let list = self
.into_iter()
.map(|row| {
let (image, attributes) = row.into_parts();
let texture = upload_to_texture(device, &queue, &image);
Item::from_parts(Raster::new_gpu(texture), attributes)
})
.collect();
queue.submit([]);
list
}
}
/// Converts single CPU raster to GPU by uploading to texture
impl<'i> Convert<Raster<GPU>, &'i WgpuExecutor> for Raster<CPU> {
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<GPU> {
let device = &executor.context().device;
let queue = executor.context().queue.lock();
let texture = upload_to_texture(device, &queue, &self);
queue.submit([]);
Raster::new_gpu(texture)
}
}
/// Passthrough conversion for CPU `List`s - no conversion needed
impl<'i> Convert<List<Raster<CPU>>, &'i WgpuExecutor> for List<Raster<CPU>> {
async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<CPU>> {
self
}
}
/// Converts a `List<Raster<GPU>>` to `List<Raster<CPU>>` by downloading texture data in one go then asynchronously maps all buffers and processes the results. /// Converts a `List<Raster<GPU>>` to `List<Raster<CPU>>` by downloading texture data in one go then asynchronously maps all buffers and processes the results.
impl<'i> Convert<List<Raster<CPU>>, &'i WgpuExecutor> for List<Raster<GPU>> { impl ConvertAsync<List<Raster<CPU>>, WgpuExecutorHandle> for List<Raster<GPU>> {
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> List<Raster<CPU>> { fn convert(self, _: Footprint, executor: WgpuExecutorHandle) -> SourceFuture<List<Raster<CPU>>> {
let device = &executor.context().device; let device = executor.context().device.clone();
let queue = &executor.context().queue; let queue = executor.context().queue.lock();
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("batch_texture_download_encoder"), label: Some("batch_texture_download_encoder"),
@@ -203,48 +204,50 @@ impl<'i> Convert<List<Raster<CPU>>, &'i WgpuExecutor> for List<Raster<GPU>> {
for row in self { for row in self {
let (element, attributes) = row.into_parts(); let (element, attributes) = row.into_parts();
converters.push(RasterGpuToRasterCpuConverter::new(device, &mut encoder, element)); converters.push(RasterGpuToRasterCpuConverter::new(&device, &mut encoder, element));
rows_meta.push(Item::from_parts((), attributes)); rows_meta.push(Item::from_parts((), attributes));
} }
queue.submit([encoder.finish()]); queue.submit([encoder.finish()]);
let mut map_futures = Vec::new(); Box::pin(async move {
for converter in converters { let mut map_futures = Vec::new();
map_futures.push(converter.convert(device)); for converter in converters {
} map_futures.push(converter.convert(&device));
}
let map_results = futures::future::try_join_all(map_futures) let map_results = futures::future::try_join_all(map_futures)
.await .await
.map_err(|_| "Failed to receive map result") .map_err(|_| "Failed to receive map result")
.expect("Buffer mapping communication failed"); .expect("Buffer mapping communication failed");
map_results map_results
.into_iter() .into_iter()
.zip(rows_meta) .zip(rows_meta)
.map(|(element, row)| { .map(|(element, row)| {
let (_, attributes) = row.into_parts(); let (_, attributes) = row.into_parts();
Item::from_parts(element, attributes) Item::from_parts(element, attributes)
}) })
.collect() .collect()
})
} }
} }
/// Converts single GPU raster to CPU by downloading texture data /// Converts single GPU raster to CPU by downloading texture data
impl<'i> Convert<Raster<CPU>, &'i WgpuExecutor> for Raster<GPU> { impl ConvertAsync<Raster<CPU>, WgpuExecutorHandle> for Raster<GPU> {
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<CPU> { fn convert(self, _: Footprint, executor: WgpuExecutorHandle) -> SourceFuture<Raster<CPU>> {
let device = &executor.context().device; let device = executor.context().device.clone();
let queue = &executor.context().queue; let queue = executor.context().queue.lock();
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("single_texture_download_encoder"), label: Some("single_texture_download_encoder"),
}); });
let converter = RasterGpuToRasterCpuConverter::new(device, &mut encoder, self); let converter = RasterGpuToRasterCpuConverter::new(&device, &mut encoder, self);
queue.submit([encoder.finish()]); queue.submit([encoder.finish()]);
converter.convert(device).await.expect("Failed to download texture data") Box::pin(async move { converter.convert(&device).await.expect("Failed to download texture data") })
} }
} }
@@ -252,10 +255,10 @@ impl<'i> Convert<Raster<CPU>, &'i WgpuExecutor> for Raster<GPU> {
/// ///
/// Accepts either individual raster data or a `List` of raster elements and converts it to the GPU format using the WgpuExecutor's device and queue. /// Accepts either individual raster data or a `List` of raster elements and converts it to the GPU format using the WgpuExecutor's device and queue.
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
pub async fn upload_texture<'a: 'n, T: Convert<List<Raster<GPU>>, &'a WgpuExecutor>>( pub fn upload_texture<T: Convert<List<Raster<GPU>>, WgpuExecutorHandle>>(
_: impl Ctx, _: impl Ctx,
#[implementations(List<Raster<CPU>>, List<Raster<GPU>>)] input: T, #[implementations(List<Raster<CPU>>, List<Raster<GPU>>)] input: T,
executor: &'a WgpuExecutor, executor: WgpuExecutorHandle,
) -> List<Raster<GPU>> { ) -> List<Raster<GPU>> {
input.convert(Footprint::DEFAULT, executor).await input.convert(Footprint::DEFAULT, executor)
} }
-3
View File
@@ -13,9 +13,6 @@ license = "Apache-2.0"
[lib] [lib]
proc-macro = true proc-macro = true
[features]
disable-registration = []
[dependencies] [dependencies]
# Workspace dependencies # Workspace dependencies
syn = { workspace = true } syn = { workspace = true }
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,715 @@
use super::*;
/// How a record node's primary input lowers.
#[derive(Clone)]
pub(crate) enum RecordCarrier {
/// `_: ()`: no carrier edge, the kernel writes a fresh record.
None,
/// An unbounded generic returned in the element position: the element
/// bytes carry through the copy plan and the kernel sees `ElToken`.
Token(Ident),
/// An element type read at offset 0, monomorphized per its
/// implementations list where generic.
Read(Type),
}
/// The record io of a node fn: how the carrier lowers, the element write,
/// and the markers written and removed. Present exactly when the signature
/// declares attribute reads or writes in a shape the record tier supports;
/// malformed record io is reported by validation and generates no node impl.
#[derive(Clone)]
pub(crate) struct RecordShape {
pub(crate) carrier: RecordCarrier,
pub(crate) element_write: Option<Type>,
pub(crate) write_markers: Vec<Type>,
pub(crate) removes: Vec<Type>,
}
impl RecordShape {
pub(crate) fn skips_carrier(&self) -> bool {
matches!(self.carrier, RecordCarrier::None)
}
pub(crate) fn carries_element(&self) -> bool {
self.element_write.is_none()
}
}
/// The record-tier lowering a node fn resolves to. Exactly one class per node,
/// computed once by [`analyze`]; every downstream fragment reads the class
/// instead of recomputing the classification predicates.
pub(crate) enum Class {
RecordIo(RecordShape),
Routing(RoutingIo),
Flip { carrier: bool },
Opaque,
}
/// The effect/return axis of a node's kernel, resolved once from the signature.
/// Orthogonal to [`Class`]: it selects the eval tail (finish / merge / spawn)
/// and the kernel signature wrapping across every class.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Dialect {
Sync,
Interrupt,
Poll,
AsyncFn,
Future,
FutureInterrupt,
}
pub(crate) fn dialect(parsed: &ParsedNodeFn) -> Dialect {
if parsed.is_async {
return Dialect::AsyncFn;
}
match kernel_kind(&parsed.output_type) {
KernelKind::Plain => Dialect::Sync,
KernelKind::Interrupt(_) => Dialect::Interrupt,
KernelKind::Poll(_) => Dialect::Poll,
KernelKind::Future(_) => Dialect::Future,
KernelKind::FutureInterrupt(_) => Dialect::FutureInterrupt,
}
}
/// The result of classifying a node fn. A node with no supported lowering
/// (an async node with lazy inputs, malformed record io, or a signature no
/// class accepts) yields `None` and generates a struct and metadata but no
/// `Node` impl.
pub(crate) struct NodeModel {
pub(crate) class: Class,
pub(crate) dialect: Dialect,
}
pub(crate) fn analyze(parsed: &ParsedNodeFn) -> Option<NodeModel> {
if parsed.is_async && parsed.fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_))) {
return None;
}
let class = if let Some(shape) = record_shape(parsed) {
Class::RecordIo(shape)
} else if has_record_io(parsed) {
return None;
} else if let Some(routing) = routing_io(parsed) {
Class::Routing(routing)
} else if record_flip(parsed) {
Class::Flip { carrier: flip_carrier(parsed) }
} else if record_opaque(parsed) {
Class::Opaque
} else {
return None;
};
Some(NodeModel { class, dialect: dialect(parsed) })
}
/// The per-field binding role, resolved once per regular field from the node
/// class and field shape. Drives the eval bindings and the lazy-edge input
/// types. The `lend` and `reads` axes stay field properties the value arms of
/// `kernel_params`/`call_args`/`value_args` consult, since they cross roles.
#[derive(Clone, Copy)]
pub(crate) enum InputRole {
RecordCarrier,
FlipCarrier,
ReadingSecondary,
LendBorrow,
RecordValue,
PlainValue,
DeriveRoutingSource,
OpaqueRecordEdge,
FlipRawLazyEdge,
FlipLazy,
RawLazy,
Lazy,
}
impl InputRole {
/// A role that copies an element out of a record edge, so its record frame
/// must be reclaimed after the read. The step lowering wraps such a bind in
/// `mark`/`rewind`, making the stack discipline structural rather than
/// hand-threaded through each read-out arm.
pub(crate) fn reads_out(self) -> bool {
matches!(self, InputRole::ReadingSecondary | InputRole::RecordValue)
}
}
/// The tail form of a node's eval, selected from its class and dialect: forward
/// the kernel's own record, assemble a record (io or flip carrier), or spawn a
/// source and lift its completion.
#[derive(Clone, Copy)]
pub(crate) enum Tail {
Forward,
Record,
Flip,
SpawnAsyncFn,
SpawnFuture,
}
/// One statement group of a node's `eval` body, lowered in order: the input
/// binds first (one per input), then the numeric clamps, then the tail that
/// assembles the output record and closes the dialect.
pub(crate) enum EvalStep<'a> {
Bind(usize, &'a ParsedField),
Clamp(&'a ParsedField),
Tail(Tail),
}
/// Whether the signature declares record-tier attribute io: value-input reads
/// or return-tuple writes. Reads on lazy inputs belong to the record lowering
/// of the flip class instead.
pub(crate) fn has_record_io(parsed: &ParsedNodeFn) -> bool {
let value_reads = parsed
.fields
.iter()
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
value_reads || record_writes(&slot_value_type(&parsed.output_type)).is_some()
}
pub(crate) fn has_lazy_reads(parsed: &ParsedNodeFn) -> bool {
parsed
.fields
.iter()
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Node(_)))
}
/// The value inputs of a routing node (every regular field that is not a
/// routing source), with their indices into the regular fields.
pub(crate) fn routing_value_indices(regular_fields: &[&ParsedField], routing: &RoutingIo) -> Vec<usize> {
regular_fields
.iter()
.enumerate()
.filter(|(_, field)| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => !matches!(ty, Type::Path(path) if path.path.get_ident() == Some(&routing.generic)),
ParsedFieldType::Node(_) => false,
})
.map(|(index, _)| index)
.collect()
}
/// The lazy inputs declaring attribute reads, with their indices into the
/// unit-skipped regular fields.
pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(usize, &'a ParsedField)> {
regular_fields
.iter()
.enumerate()
.filter(|(_, field)| matches!(field.ty, ParsedFieldType::Node(_)) && !field.attribute_reads.is_empty())
.map(|(index, field)| (index, *field))
.collect()
}
/// The indices (into the unit-skipped regular fields) of value inputs whose
/// reads resolve against their own wire rather than the carrier's.
pub(crate) fn reading_secondary_indices(regular_fields: &[&ParsedField], shape: &RecordShape) -> Vec<usize> {
regular_fields
.iter()
.enumerate()
.filter(|(index, field)| !field.attribute_reads.is_empty() && (shape.skips_carrier() || *index != 0))
.map(|(index, _)| index)
.collect()
}
/// Every attribute read in field order with the owning field's index, flat so
/// read slots are numbered across inputs.
pub(crate) fn field_reads<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(usize, &'a AttributeRead)> {
regular_fields
.iter()
.enumerate()
.flat_map(|(index, field)| field.attribute_reads.iter().map(move |read| (index, read)))
.collect()
}
/// Substitutes bare generic idents with their row-assigned types.
pub(crate) fn substitute_ident_types(ty: &Type, assignments: &[(Ident, Type)]) -> Type {
struct Subst<'a> {
assignments: &'a [(Ident, Type)],
}
impl VisitMut for Subst<'_> {
fn visit_type_mut(&mut self, ty: &mut Type) {
if let Type::Path(path) = ty
&& path.qself.is_none()
&& let Some(ident) = path.path.get_ident()
&& let Some((_, replacement)) = self.assignments.iter().find(|(generic, _)| generic == ident)
{
*ty = replacement.clone();
return;
}
syn::visit_mut::visit_type_mut(self, ty);
}
}
let mut ty = ty.clone();
Subst { assignments }.visit_type_mut(&mut ty);
ty
}
/// Replaces the routing generic in a derive-routing kernel's return type with
/// the routing record value, since the kernel's edges rebind to '__record.
pub(crate) fn substitute_routing_record(output: &Type, generic: &Ident, core_types: &TokenStream2) -> Type {
struct Subst<'a> {
generic: &'a Ident,
replacement: Type,
}
impl VisitMut for Subst<'_> {
fn visit_type_mut(&mut self, ty: &mut Type) {
if let Type::Path(path) = ty
&& path.qself.is_none()
&& path.path.get_ident() == Some(self.generic)
{
*ty = self.replacement.clone();
return;
}
syn::visit_mut::visit_type_mut(self, ty);
}
}
let mut ty = output.clone();
let mut subst = Subst {
generic,
replacement: syn::parse_quote!(#core_types::record::RecordValue<'__record>),
};
subst.visit_type_mut(&mut ty);
ty
}
pub(crate) fn inject_attr_lifetimes(output: &Type) -> Option<Type> {
struct Injector {
changed: bool,
}
impl VisitMut for Injector {
fn visit_path_segment_mut(&mut self, segment: &mut syn::PathSegment) {
if segment.ident == "Attr"
&& let PathArguments::AngleBracketed(args) = &mut segment.arguments
&& !args.args.iter().any(|arg| matches!(arg, GenericArgument::Lifetime(_)))
{
args.args.insert(0, GenericArgument::Lifetime(Lifetime::new("'__attr", proc_macro2::Span::call_site())));
self.changed = true;
}
syn::visit_mut::visit_path_segment_mut(self, segment);
}
}
let mut ty = output.clone();
let mut injector = Injector { changed: false };
injector.visit_type_mut(&mut ty);
injector.changed.then_some(ty)
}
pub(crate) fn contains_open_generic(parsed: &ParsedNodeFn, ty: &Type) -> bool {
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
parsed
.fn_generics
.iter()
.any(|param| matches!(param, GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() && type_contains_ident(ty, &type_param.ident)))
}
pub(crate) fn unbounded_generic(parsed: &ParsedNodeFn, ty: &Type) -> Option<Ident> {
let ident = bare_ident(ty)?.clone();
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
parsed
.fn_generics
.iter()
.find(|param| matches!(param, GenericParam::Type(type_param) if type_param.ident == ident && type_param.bounds.is_empty() && Some(&type_param.ident) != ctx_ident.as_ref()))?;
if let Some(where_clause) = &parsed.where_clause
&& tokens_contain_ident(where_clause.to_token_stream(), &ident)
{
return None;
}
Some(ident)
}
pub(crate) fn record_shape(parsed: &ParsedNodeFn) -> Option<RecordShape> {
let value = match kernel_kind(&parsed.output_type) {
KernelKind::Plain => parsed.output_type.clone(),
KernelKind::Interrupt(inner) => inner,
_ => return None,
};
let writes = record_writes(&value);
let has_reads = parsed
.fields
.iter()
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
if !has_reads && writes.is_none() {
return None;
}
if parsed.is_async || parsed.fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_))) {
return None;
}
let reads_well_placed = parsed.fields.iter().all(|field| {
field.attribute_reads.is_empty() || (!field.is_data_field && matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: None, .. })))
});
if !reads_well_placed {
return None;
}
let carrier_field = parsed.fields.first()?;
if carrier_field.is_data_field {
return None;
}
let ParsedFieldType::Regular(RegularParsedField { ty, lend: None, implementations, .. }) = &carrier_field.ty else {
return None;
};
let carrier = match ty {
Type::Tuple(tuple) if tuple.elems.is_empty() => RecordCarrier::None,
ty => match implementations.is_empty().then(|| unbounded_generic(parsed, ty)).flatten() {
Some(token) => RecordCarrier::Token(token),
None => {
if contains_open_generic(parsed, ty) {
return None;
}
RecordCarrier::Read(ty.clone())
}
},
};
let (element, write_markers, removes) = match writes {
Some(RecordWrites { element, markers, removes }) => (element, markers, removes),
None => (value, Vec::new(), Vec::new()),
};
let element_write = match &carrier {
RecordCarrier::Token(token) => match bare_ident(&element) {
Some(ident) if ident == token => None,
_ => return None,
},
_ => {
if contains_open_generic(parsed, &element) {
return None;
}
Some(element)
}
};
if matches!(carrier, RecordCarrier::None) && !removes.is_empty() {
return None;
}
Some(RecordShape {
carrier,
element_write,
write_markers,
removes,
})
}
pub(crate) fn is_poll_kernel(output: &Type) -> bool {
matches!(kernel_kind(output), KernelKind::Poll(_))
}
/// A routing family: an unbounded generic shared by lazy inputs (and
/// optionally the first parameter) and returned whole, instantiated at
/// `RecordValue` so opaque records flow through the kernel. Detected only
/// when the family's fields carry no implementations lists, so the existing
/// per-type row spelling keeps its meaning.
#[derive(Clone)]
pub(crate) struct RoutingIo {
pub(crate) generic: Ident,
}
/// Whether a flipped node's primary input is a carrier: the first parameter
/// after the context, when it is an owned or lent value input. A carrier's
/// fields pass through to the output; every production layout is element-only
/// until attribute adoption, so the copy plan is empty and behavior is
/// unchanged. Async kernels carry fields per eval around the slot (only the
/// element crosses the future boundary), so their carrier must be owned: the
/// future captures the element by value.
pub(crate) fn flip_carrier(parsed: &ParsedNodeFn) -> bool {
if !record_flip(parsed) {
return false;
}
let Some(first) = parsed.fields.first() else { return false };
if first.is_data_field {
return false;
}
let ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) = &first.ty else {
return false;
};
if matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty()) {
return false;
}
let async_kernel = parsed.is_async || matches!(kernel_kind(&parsed.output_type), KernelKind::Future(_) | KernelKind::FutureInterrupt(_));
!(async_kernel && lend.is_some())
}
/// Whether a plain node's lowering flips onto record wires: sync,
/// fully-concrete value-input nodes in this cut; batch, shader, async, lend,
/// lazy, and generic nodes keep the plain lowering until their record forms
/// land.
pub(crate) fn record_flip(parsed: &ParsedNodeFn) -> bool {
if record_shape(parsed).is_some() || has_record_io(parsed) || routing_io(parsed).is_some() {
return false;
}
// Shader nodes flip like any value node: the kernel doubles as the
// shader body on the spirv target, but the struct and Node impl are
// std-gated, so the record machinery never reaches the shader build.
if parsed.attributes.batch.is_some() || parsed.attributes.plain {
return false;
}
if type_disqualifies(&slot_value_type(&parsed.output_type)) {
return false;
}
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
for param in &parsed.fn_generics {
match param {
GenericParam::Type(type_param) if Some(&type_param.ident) == ctx_ident.as_ref() => {}
// Registry rows assign a generic by unifying a field's type with
// the row's, so a generic without an extractable position keeps
// the plain lowering. A `skip_impl` node's rows are hand-written
// with explicit types, so no extractable position is needed.
GenericParam::Type(type_param) => {
let extractable = parsed.fields.iter().filter(|field| !field.is_data_field).any(|field| {
let ty = match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
};
generic_extractable(ty, &type_param.ident)
});
if !extractable && !parsed.attributes.skip_impl {
return false;
}
}
GenericParam::Lifetime(_) | GenericParam::Const(_) => return false,
}
}
true
}
/// Whether unifying a value of `field_ty`'s shape can bind `generic`: the
/// generic sits bare or under path type arguments, the shapes
/// [`generic_assignment`] walks.
pub(crate) fn generic_extractable(field_ty: &Type, generic: &Ident) -> bool {
match field_ty {
Type::Path(path) if path.qself.is_none() && path.path.get_ident() == Some(generic) => true,
Type::Path(path) => path.path.segments.iter().any(|segment| match &segment.arguments {
PathArguments::AngleBracketed(args) => args.args.iter().any(|argument| match argument {
GenericArgument::Type(inner) => generic_extractable(inner, generic),
_ => false,
}),
_ => false,
}),
_ => false,
}
}
/// Binds `generic` by unifying `field_ty` against `row_ty`: where the field
/// names the generic, the row's corresponding subtree is the assignment.
pub(crate) fn generic_assignment(field_ty: &Type, row_ty: &Type, generic: &Ident) -> Option<Type> {
if matches!(field_ty, Type::Path(path) if path.qself.is_none() && path.path.get_ident() == Some(generic)) {
return Some(row_ty.clone());
}
let (Type::Path(field_path), Type::Path(row_path)) = (field_ty, row_ty) else {
return None;
};
let field_segment = field_path.path.segments.last()?;
let row_segment = row_path.path.segments.last()?;
let (PathArguments::AngleBracketed(field_args), PathArguments::AngleBracketed(row_args)) = (&field_segment.arguments, &row_segment.arguments) else {
return None;
};
field_args.args.iter().zip(row_args.args.iter()).find_map(|(field_arg, row_arg)| match (field_arg, row_arg) {
(GenericArgument::Type(field_inner), GenericArgument::Type(row_inner)) => generic_assignment(field_inner, row_inner, generic),
_ => None,
})
}
pub(crate) fn is_record_value(ty: &Type) -> bool {
matches!(ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "RecordValue"))
}
/// Whether a kernel operates on whole records: it names `RecordValue` in its
/// output, receives raw record edges paired with the node's layout, and
/// takes on the record APIs' unsafe contracts itself.
pub(crate) fn record_opaque(parsed: &ParsedNodeFn) -> bool {
is_record_value(&slot_value_type(&parsed.output_type))
}
pub(crate) fn routing_io(parsed: &ParsedNodeFn) -> Option<RoutingIo> {
if has_record_io(parsed) || parsed.is_async {
return None;
}
if !matches!(kernel_kind(&parsed.output_type), KernelKind::Plain | KernelKind::Interrupt(_)) {
return None;
}
let value = slot_value_type(&parsed.output_type);
let Type::Path(path) = &value else { return None };
let ident = path.path.get_ident()?.clone();
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
parsed
.fn_generics
.iter()
.find(|param| matches!(param, GenericParam::Type(type_param) if type_param.ident == ident && type_param.bounds.is_empty() && Some(&type_param.ident) != ctx_ident.as_ref()))?;
if let Some(where_clause) = &parsed.where_clause
&& tokens_contain_ident(where_clause.to_token_stream(), &ident)
{
return None;
}
let mut sources = 0;
for (index, field) in parsed.fields.iter().enumerate() {
match &field.ty {
ParsedFieldType::Node(NodeParsedField {
output_type,
input_type,
implementations,
}) => {
if bare_ident(output_type) == Some(&ident) {
// A source forwards its whole record opaquely; declared
// reads contradict that and are rejected by validation.
if !implementations.is_empty() || type_contains_ident(input_type, &ident) || !field.attribute_reads.is_empty() {
return None;
}
sources += 1;
} else if type_contains_ident(output_type, &ident) || type_contains_ident(input_type, &ident) {
return None;
}
}
ParsedFieldType::Regular(RegularParsedField { ty, implementations, lend, .. }) => {
if bare_ident(ty) == Some(&ident) {
if index != 0 || field.is_data_field || !implementations.is_empty() || lend.is_some() {
return None;
}
sources += 1;
} else if type_contains_ident(ty, &ident) {
return None;
}
}
}
}
(sources > 0).then(|| RoutingIo { generic: ident })
}
pub(crate) fn bare_ident(ty: &Type) -> Option<&Ident> {
let Type::Path(path) = ty else { return None };
path.path.get_ident()
}
pub(crate) fn tokens_contain_ident(tokens: TokenStream2, ident: &Ident) -> bool {
tokens.into_iter().any(|token| match token {
proc_macro2::TokenTree::Ident(candidate) => &candidate == ident,
proc_macro2::TokenTree::Group(group) => tokens_contain_ident(group.stream(), ident),
_ => false,
})
}
pub(crate) fn slot_value_type(output: &Type) -> Type {
match kernel_kind(output) {
KernelKind::Plain => output.clone(),
KernelKind::Poll(inner) | KernelKind::Interrupt(inner) => inner,
KernelKind::Future(payload) | KernelKind::FutureInterrupt(payload) => match kernel_kind(&payload) {
KernelKind::Poll(inner) | KernelKind::Interrupt(inner) => inner,
_ => payload,
},
}
}
pub(crate) fn is_source_kernel(output: &Type) -> bool {
matches!(kernel_kind(output), KernelKind::Future(_) | KernelKind::FutureInterrupt(_))
}
pub(crate) enum KernelKind {
Plain,
Interrupt(Type),
Poll(Type),
Future(Type),
FutureInterrupt(Type),
}
pub(crate) fn source_future_payload(segment: &syn::PathSegment) -> Type {
let PathArguments::AngleBracketed(args) = &segment.arguments else {
return syn::parse_quote!(());
};
args.args
.iter()
.find_map(|argument| match argument {
GenericArgument::Type(ty) => Some(ty.clone()),
_ => None,
})
.unwrap_or_else(|| syn::parse_quote!(()))
}
pub(crate) fn kernel_kind(output: &Type) -> KernelKind {
let plain = || KernelKind::Plain;
let Type::Path(path) = output else { return plain() };
let Some(segment) = path.path.segments.last() else { return plain() };
match segment.ident.to_string().as_str() {
"GPoll" => {
let PathArguments::AngleBracketed(args) = &segment.arguments else { return plain() };
let inner = args.args.iter().find_map(|argument| match argument {
GenericArgument::Type(ty) => Some(ty.clone()),
_ => None,
});
inner.map(KernelKind::Poll).unwrap_or_else(plain)
}
"SourceFuture" => KernelKind::Future(source_future_payload(segment)),
"Result" => {
let PathArguments::AngleBracketed(args) = &segment.arguments else { return plain() };
let mut types = args.args.iter().filter_map(|argument| match argument {
GenericArgument::Type(ty) => Some(ty),
_ => None,
});
let (Some(inner), Some(Type::Path(error_path))) = (types.next(), types.next()) else {
return plain();
};
if error_path.path.segments.last().is_none_or(|segment| segment.ident != "Interrupt") {
return plain();
}
if let Type::Path(inner_path) = inner
&& let Some(inner_segment) = inner_path.path.segments.last()
&& inner_segment.ident == "SourceFuture"
{
return KernelKind::FutureInterrupt(source_future_payload(inner_segment));
}
KernelKind::Interrupt(inner.clone())
}
_ => plain(),
}
}
pub(crate) fn context_param(parsed: &ParsedNodeFn) -> Option<&TypeParam> {
let Type::Path(path) = &parsed.input.ty else {
return None;
};
let ident = path.path.get_ident()?;
parsed.fn_generics.iter().find_map(|param| match param {
GenericParam::Type(type_param) if &type_param.ident == ident => Some(type_param),
_ => None,
})
}
pub(crate) fn type_disqualifies(ty: &Type) -> bool {
struct Disqualifier {
found: bool,
}
impl<'ast> Visit<'ast> for Disqualifier {
fn visit_type_reference(&mut self, _: &'ast syn::TypeReference) {
self.found = true;
}
fn visit_type_impl_trait(&mut self, _: &'ast syn::TypeImplTrait) {
self.found = true;
}
fn visit_lifetime(&mut self, _: &'ast Lifetime) {
self.found = true;
}
}
let mut visitor = Disqualifier { found: false };
visitor.visit_type(ty);
visitor.found
}
pub(crate) fn desugar_extract_lifetime(bound: &TypeParamBound, core_types: &TokenStream2) -> TokenStream2 {
let TypeParamBound::Trait(trait_bound) = bound else {
return quote!(#bound);
};
let Some(segment) = trait_bound.path.segments.last() else {
return quote!(#bound);
};
if segment.ident != "ExtractArena" {
return quote!(#bound);
}
let PathArguments::AngleBracketed(args) = &segment.arguments else {
return quote!(#bound);
};
if args.args.len() != 1 {
return quote!(#bound);
}
let Some(GenericArgument::Lifetime(lifetime)) = args.args.first() else {
return quote!(#bound);
};
quote!(#core_types::context::ExtractArena<ArenaRef = &#lifetime #core_types::arena::Arena>)
}
@@ -0,0 +1,519 @@
use super::*;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{GenericParam, Ident, Type};
pub(crate) fn entries_tokens(parsed: &ParsedNodeFn, class: &Class, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
if !data_field_generic_idents.is_empty() {
return quote!();
}
match class {
Class::RecordIo(_) => record_entries_tokens(parsed, struct_name, regular_fields),
Class::Routing(_) => routing_entries_tokens(parsed, struct_name, regular_fields),
Class::Flip { .. } => flip_entries_tokens(parsed, struct_name, regular_fields),
Class::Opaque => record_opaque_entries_tokens(parsed, struct_name, regular_fields),
}
}
/// The registry rows of a flipped plain node: every wire is a record wire,
/// inputs resolve their layouts off the claimed handles, and the output is an
/// element-only record of the kernel's return type.
fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
let Some(rows) = implementation_rows(parsed, regular_fields) else {
return quote!();
};
let rows: Vec<&Vec<Type>> = rows.iter().filter(|row| row.iter().all(|ty| !type_disqualifies(ty))).collect();
if rows.is_empty() {
return quote!();
}
let output = slot_value_type(&parsed.output_type);
let field_type = |field: &ParsedField| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type.clone(),
};
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
let generic_positions: Option<Vec<(Ident, usize)>> = parsed
.fn_generics
.iter()
.filter_map(|param| match param {
GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() => Some(&type_param.ident),
_ => None,
})
.map(|generic| {
regular_fields
.iter()
.position(|field| generic_extractable(&field_type(field), generic))
.map(|index| (generic.clone(), index))
})
.collect();
let Some(generic_positions) = generic_positions else {
return quote!();
};
let fn_name = &parsed.fn_name;
let entries_name = format_ident!("{}_entries", fn_name);
let arity = regular_fields.len();
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
let node_underscores: Vec<TokenStream2> = regular_fields.iter().map(|_| quote!(_)).collect();
// Shorthand associated types in the output only resolve against the
// generics' bounds, so rows name the output through a bounded alias. Only
// output-reaching generics (directly or through a kept bound) may appear:
// an unused alias parameter is an error.
let candidate_params: Vec<&GenericParam> = parsed
.fn_generics
.iter()
.filter(|param| matches!(param, GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref()))
.collect();
let param_ident = |param: &&GenericParam| match param {
GenericParam::Type(type_param) => type_param.ident.clone(),
_ => unreachable!("candidates are type parameters"),
};
let mut kept: Vec<bool> = candidate_params.iter().map(|param| type_contains_ident(&output, &param_ident(param))).collect();
loop {
let mut grew = false;
for index in 0..candidate_params.len() {
if kept[index] {
continue;
}
let ident = param_ident(&candidate_params[index]);
let mentioned = candidate_params.iter().zip(&kept).any(|(param, kept)| {
*kept
&& match param {
GenericParam::Type(type_param) => type_param.bounds.iter().any(|bound| {
let bound: Type = syn::parse_quote!(dyn #bound);
type_contains_ident(&bound, &ident)
}),
_ => false,
}
});
if mentioned {
kept[index] = true;
grew = true;
}
}
if !grew {
break;
}
}
let alias_params: Vec<&GenericParam> = candidate_params.iter().zip(&kept).filter(|(_, kept)| **kept).map(|(param, _)| *param).collect();
let alias_param_idents: Vec<Ident> = alias_params.iter().map(|param| param_ident(param)).collect();
let alias_param_tokens: Vec<TokenStream2> = alias_params.iter().map(|param| quote!(#param)).collect();
let output_alias = format_ident!("__{}_output", fn_name);
let alias_def = match alias_param_tokens.is_empty() {
true => quote!(#[allow(non_camel_case_types)] type #output_alias = #output;),
false => quote!(#[allow(non_camel_case_types, type_alias_bounds)] type #output_alias<#(#alias_param_tokens,)*> = #output;),
};
let entries = rows.iter().filter_map(|row| {
let assignments: Vec<(Ident, Type)> = generic_positions
.iter()
.map(|(generic, index)| generic_assignment(&field_type(regular_fields[*index]), &row[*index], generic).map(|assigned| (generic.clone(), assigned)))
.collect::<Option<_>>()?;
if type_disqualifies(&substitute_ident_types(&output, &assignments)) {
return None;
}
let assignment_types: Vec<TokenStream2> = assignments.iter().map(|(_, ty)| quote!(#ty)).collect();
let alias_arguments: Vec<TokenStream2> = assignments
.iter()
.filter(|(generic, _)| alias_param_idents.contains(generic))
.map(|(_, ty)| quote!(#ty))
.collect();
let row_output = match alias_arguments.is_empty() {
true => quote!(#output_alias),
false => quote!(#output_alias<#(#alias_arguments),*>),
};
let assignment_types = assignment_types.iter();
let turbofish = quote!(::<#(#node_underscores,)* #(#assignment_types,)*>);
let input_types = row.iter().map(|ty| quote!(gcore::registry::record_edge_type::<#ty>()));
let downcasts = names.iter().zip(row.iter()).enumerate().map(|(index, (name, ty))| {
let handle = format_ident!("__handle_{index}");
let layout = format_ident!("__layout_{index}");
quote! {
let #handle = inputs.next().unwrap();
let Some(#layout) = #handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = #handle.downcast_record::<#ty>()?;
}
});
let layout_args = (0..arity).map(|index| {
let layout = format_ident!("__layout_{index}");
quote!(&#layout,)
});
Some(quote! {
gcore::registry::RegistryEntry {
io: gcore::registry::NodeIOTypes::new(
gcore::concrete!(gcore::context::ContextImpl<'static>),
gcore::registry::record_type::<#row_output>(),
vec![#(#input_types),*],
),
constructor: |inputs| {
if inputs.len() != #arity {
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
#(#downcasts)*
let __node = #struct_name #turbofish::new(#(#names,)* #(#layout_args)*);
Ok(gcore::registry::EdgeHandle::new_record::<#row_output>(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>))
},
}
})
});
let entries: Vec<TokenStream2> = entries.collect();
if entries.is_empty() {
return quote!();
}
quote! {
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
#alias_def
vec![#(#entries),*]
}
}
}
/// The registry row of a routing node: one instance covers every element,
/// sources claim generic record edges, and the constructor wraps each source
/// in its union translation and stores the union as the node's layout.
fn routing_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
let Some(routing) = routing_io(parsed) else {
return quote!();
};
let is_source = |field: &ParsedField| {
let ty = match &field.ty {
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
};
matches!(ty, Type::Path(path) if path.path.get_ident() == Some(&routing.generic))
};
let values_concrete = regular_fields.iter().filter(|field| !is_source(field)).all(|field| {
let (ty, lend) = match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => (ty, lend.is_some()),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => (output_type, false),
};
!contains_open_generic(parsed, ty) && (lend || !type_disqualifies(ty))
});
if !values_concrete {
return quote!();
}
let fn_name = &parsed.fn_name;
let entries_name = format_ident!("{}_entries", fn_name);
let arity = regular_fields.len();
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
let token_name = routing.generic.to_string();
let input_types = regular_fields.iter().map(|field| {
if is_source(field) {
return quote!(gcore::registry::generic_record_edge_type(#token_name));
}
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(gcore::registry::record_edge_type::<#ty>()),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(gcore::registry::edge_type::<#output_type>()),
}
});
let source_layouts: Vec<Ident> = regular_fields
.iter()
.enumerate()
.filter(|(_, field)| is_source(field))
.map(|(index, _)| format_ident!("__layout_{index}"))
.collect();
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
let name = &field.pat_ident.ident;
if is_source(field) {
let layout = format_ident!("__layout_{index}");
let handle = format_ident!("__handle_{index}");
let ty = format_ident!("__ty_{index}");
return quote! {
let #handle = inputs.next().unwrap();
let #ty = #handle.ty().clone();
let Some(#layout) = #handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = #handle.downcast_erased::<gcore::registry::ErasedRecordNode>(#ty.clone())?;
};
}
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => {
let handle = format_ident!("__handle_{index}");
let layout = format_ident!("__in_layout_{index}");
quote! {
let #handle = inputs.next().unwrap();
let Some(#layout) = #handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = #handle.downcast_record::<#ty>()?;
}
}
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#output_type>()?;),
}
});
let value_layout_args = regular_fields
.iter()
.enumerate()
.filter(|(_, field)| !is_source(field) && matches!(field.ty, ParsedFieldType::Regular(_)))
.map(|(index, _)| {
let layout = format_ident!("__in_layout_{index}");
quote!(&#layout,)
});
let source_wraps = regular_fields.iter().enumerate().filter(|(_, field)| is_source(field)).map(|(index, field)| {
let name = &field.pat_ident.ident;
let layout = format_ident!("__layout_{index}");
quote!(let #name = gcore::record::RecordSource::new(#name, &#layout, &__union);)
});
let first_source_ty = regular_fields
.iter()
.enumerate()
.find(|(_, field)| is_source(field))
.map(|(index, _)| format_ident!("__ty_{index}"))
.expect("routing nodes have a source");
quote! {
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
vec![gcore::registry::RegistryEntry {
io: gcore::registry::NodeIOTypes::new(
gcore::concrete!(gcore::context::ContextImpl<'static>),
gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#token_name)))),
vec![#(#input_types),*],
),
constructor: |inputs| {
if inputs.len() != #arity {
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
#(#downcasts)*
let __union = gcore::record::Layout::union(&[#(&#source_layouts),*]);
#(#source_wraps)*
let __node = #struct_name::new(#(#names,)* &__union, #(#value_layout_args)*);
Ok(gcore::registry::EdgeHandle::new_erased(
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
#first_source_ty,
))
},
}]
}
}
}
fn record_opaque_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
let is_record = |field: &ParsedField| matches!(&field.ty, ParsedFieldType::Node(NodeParsedField { output_type, .. }) if is_record_value(output_type));
let values_concrete = regular_fields.iter().filter(|field| !is_record(field)).all(|field| {
let (ty, lend) = match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => (ty, lend.is_some()),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => (output_type, false),
};
!contains_open_generic(parsed, ty) && (lend || !type_disqualifies(ty))
});
if !values_concrete {
return quote!();
}
let fn_name = &parsed.fn_name;
let entries_name = format_ident!("{}_entries", fn_name);
let arity = regular_fields.len();
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
let input_types = regular_fields.iter().map(|field| {
if is_record(field) {
return quote!(gcore::registry::generic_record_edge_type("T"));
}
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => quote!(gcore::registry::edge_type::<#ty>()),
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(gcore::registry::edge_type::<#ty>()),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(gcore::registry::edge_type::<#output_type>()),
}
});
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
let name = &field.pat_ident.ident;
if is_record(field) {
let layout = format_ident!("__layout_{index}");
let handle = format_ident!("__handle_{index}");
let ty = format_ident!("__ty_{index}");
return quote! {
let #handle = inputs.next().unwrap();
let #ty = #handle.ty().clone();
let Some(#layout) = #handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = #handle.downcast_erased::<gcore::registry::ErasedRecordNode>(#ty.clone())?;
};
}
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;),
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#output_type>()?;),
}
});
let first_record = regular_fields.iter().position(|field| is_record(field)).expect("record-opaque nodes have a record input");
let record_layout = format_ident!("__layout_{first_record}");
let record_ty = format_ident!("__ty_{first_record}");
quote! {
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
vec![gcore::registry::RegistryEntry {
io: gcore::registry::NodeIOTypes::new(
gcore::concrete!(gcore::context::ContextImpl<'static>),
gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed("T")))),
vec![#(#input_types),*],
),
constructor: |inputs| {
if inputs.len() != #arity {
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
#(#downcasts)*
let __node = #struct_name::new(#(#names,)* &#record_layout);
Ok(gcore::registry::EdgeHandle::new_erased(
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
#record_ty,
))
},
}]
}
}
}
fn record_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
let Some(shape) = record_shape(parsed) else {
return quote!();
};
let carrier_in_fields = !shape.skips_carrier();
let values_concrete = regular_fields.iter().skip(carrier_in_fields as usize).all(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => !contains_open_generic(parsed, ty) && (lend.is_some() || !type_disqualifies(ty)),
_ => false,
});
if !values_concrete {
return quote!();
}
let fn_name = &parsed.fn_name;
let entries_name = format_ident!("{}_entries", fn_name);
let arity = regular_fields.len();
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
let reading_secondaries = reading_secondary_indices(regular_fields, &shape);
let input_types = regular_fields.iter().enumerate().map(|(index, field)| {
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
unreachable!("record nodes take no lazy inputs")
};
if carrier_in_fields && index == 0 {
return match &shape.carrier {
RecordCarrier::Token(token) => {
let name = token.to_string();
quote!(gcore::registry::generic_record_edge_type(#name))
}
RecordCarrier::Read(carrier_ty) => quote!(gcore::registry::record_edge_type::<#carrier_ty>()),
RecordCarrier::None => unreachable!(),
};
}
match field.attribute_reads.is_empty() {
true => quote!(gcore::registry::edge_type::<#ty>()),
false => quote!(gcore::registry::record_edge_type::<#ty>()),
}
});
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
let name = &field.pat_ident.ident;
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
unreachable!("record nodes take no lazy inputs")
};
if carrier_in_fields && index == 0 {
return quote! {
let __carrier_handle = inputs.next().unwrap();
let __carrier_ty = __carrier_handle.ty().clone();
let Some(__carrier_layout) = __carrier_handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = __carrier_handle.downcast_erased::<gcore::registry::ErasedRecordNode>(__carrier_ty.clone())?;
};
}
if !field.attribute_reads.is_empty() {
let layout_local = format_ident!("__in_layout_{index}");
return quote! {
let __in_handle = inputs.next().unwrap();
let __in_ty = __in_handle.ty().clone();
let Some(#layout_local) = __in_handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = __in_handle.downcast_erased::<gcore::registry::ErasedRecordNode>(__in_ty)?;
};
}
quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;)
});
let wire_layout_arg = carrier_in_fields.then(|| quote!(&__carrier_layout,)).into_iter();
let input_layout_args = reading_secondaries.iter().map(|index| {
let layout_local = format_ident!("__in_layout_{index}");
quote!(&#layout_local,)
});
let (io_output, construct_output) = match (&shape.carrier, &shape.element_write) {
(RecordCarrier::Token(token), _) => {
let name = token.to_string();
(
quote!(gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#name))))),
quote!(Ok(gcore::registry::EdgeHandle::new_erased(
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
__carrier_ty,
))),
)
}
(_, Some(element)) => (
quote!(gcore::registry::record_type::<#element>()),
quote!(Ok(gcore::registry::EdgeHandle::new_record::<#element>(::std::sync::Arc::new(__node)))),
),
(_, None) => unreachable!("non-token record nodes write an element"),
};
quote! {
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
vec![gcore::registry::RegistryEntry {
io: gcore::registry::NodeIOTypes::new(
gcore::concrete!(gcore::context::ContextImpl<'static>),
#io_output,
vec![#(#input_types),*],
),
constructor: |inputs| {
if inputs.len() != #arity {
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
#(#downcasts)*
let __node = #struct_name::new(#(#names,)* #(#wire_layout_arg)* #(#input_layout_args)*);
#construct_output
},
}]
}
}
}
fn implementation_rows(parsed: &ParsedNodeFn, regular_fields: &[&ParsedField]) -> Option<Vec<Vec<Type>>> {
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
let open_generics: Vec<&Ident> = parsed
.fn_generics
.iter()
.filter_map(|param| match param {
GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() => Some(&type_param.ident),
_ => None,
})
.collect();
let candidates: Vec<Vec<Type>> = regular_fields
.iter()
.map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => match implementations.is_empty() {
false => Some(implementations.iter().cloned().collect()),
true => open_generics.iter().all(|generic| !crate::codegen::type_contains_ident(ty, generic)).then(|| vec![ty.clone()]),
},
ParsedFieldType::Node(NodeParsedField { output_type, implementations, .. }) => match implementations.is_empty() {
false => Some(implementations.iter().map(|implementation| implementation.output.clone()).collect()),
true => open_generics
.iter()
.all(|generic| !crate::codegen::type_contains_ident(output_type, generic))
.then(|| vec![output_type.clone()]),
},
})
.collect::<Option<_>>()?;
let row_count = candidates.iter().map(|types| types.len()).max().unwrap_or(1).max(1);
Some((0..row_count).map(|row| candidates.iter().map(|types| types[row.min(types.len() - 1)].clone()).collect()).collect())
}
@@ -0,0 +1,173 @@
use super::*;
/// Generates strongly typed utilites to access inputs
pub(crate) fn generate_node_input_references(
parsed: &ParsedNodeFn,
fn_generics: &[crate::GenericParam],
field_idents: &[&PatIdent],
core_types: &TokenStream2,
identifier: &Ident,
cfg: &TokenStream2,
) -> TokenStream2 {
let inputs_module_name = format_ident!("{}", parsed.struct_name.to_string().to_case(Case::Snake));
let mut generated_input_accessor = Vec::new();
if !parsed.attributes.skip_impl {
let (mut modified, mut generic_collector) = FilterUsedGenerics::new(fn_generics);
for (input_index, (parsed_input, input_ident)) in parsed.fields.iter().zip(field_idents).enumerate() {
let mut ty = match &parsed_input.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
}
.clone();
// We only want the necessary generics.
let used = generic_collector.filter_unnecessary_generics(&mut modified, &mut ty);
// TODO: figure out a better name that doesn't conflict with so many types
let struct_name = format_ident!("{}Input", input_ident.ident.to_string().to_case(Case::Pascal));
let (fn_generic_params, phantom_data_declerations) = generate_phantom_data(used.iter());
// Only create structs with phantom data where necessary.
generated_input_accessor.push(if phantom_data_declerations.is_empty() {
quote! {
pub struct #struct_name;
}
} else {
quote! {
pub struct #struct_name <#(#used),*>{
#(#phantom_data_declerations,)*
}
}
});
generated_input_accessor.push(quote! {
impl <#(#used),*> #core_types::NodeInputDecleration for #struct_name <#(#fn_generic_params),*> {
const INDEX: usize = #input_index;
fn identifier() -> #core_types::ProtoNodeIdentifier {
#inputs_module_name::IDENTIFIER.clone()
}
type Result = #ty;
}
})
}
}
quote! {
#cfg
pub mod #inputs_module_name {
use super::*;
/// The `ProtoNodeIdentifier` of this node without any generics attached to it
pub const IDENTIFIER: #core_types::ProtoNodeIdentifier = #identifier();
#(#generated_input_accessor)*
}
}
}
/// It is necessary to generate PhantomData for each fn generic to avoid compiler errors.
pub(crate) fn generate_phantom_data<'a>(fn_generics: impl Iterator<Item = &'a crate::GenericParam>) -> (Vec<TokenStream2>, Vec<TokenStream2>) {
let mut phantom_data_declerations = Vec::new();
let mut fn_generic_params = Vec::new();
for fn_generic_param in fn_generics {
let field_name = format_ident!("phantom_{}", phantom_data_declerations.len());
match fn_generic_param {
crate::GenericParam::Lifetime(lifetime_param) => {
let lifetime = &lifetime_param.lifetime;
fn_generic_params.push(quote! {#lifetime});
phantom_data_declerations.push(quote! {#field_name: core::marker::PhantomData<&#lifetime ()>})
}
crate::GenericParam::Type(type_param) => {
let generic_name = &type_param.ident;
fn_generic_params.push(quote! {#generic_name});
phantom_data_declerations.push(quote! {#field_name: core::marker::PhantomData<#generic_name>});
}
_ => {}
}
}
(fn_generic_params, phantom_data_declerations)
}
/// Get only the necessary generics.
struct FilterUsedGenerics {
all: Vec<crate::GenericParam>,
used: Vec<bool>,
}
impl VisitMut for FilterUsedGenerics {
fn visit_lifetime_mut(&mut self, used_lifetime: &mut Lifetime) {
for (generic, used) in self.all.iter().zip(self.used.iter_mut()) {
let crate::GenericParam::Lifetime(lifetime_param) = generic else { continue };
if used_lifetime == &lifetime_param.lifetime {
*used = true;
}
}
}
fn visit_path_mut(&mut self, path: &mut syn::Path) {
for (index, (generic, used)) in self.all.iter().zip(self.used.iter_mut()).enumerate() {
let crate::GenericParam::Type(type_param) = generic else { continue };
if path.leading_colon.is_none() && !path.segments.is_empty() && path.segments[0].arguments.is_none() && path.segments[0].ident == type_param.ident {
*used = true;
// Sometimes the generics conflict with the type name so we rename the generics.
path.segments[0].ident = format_ident!("G{index}");
}
}
for mut el in Punctuated::pairs_mut(&mut path.segments) {
self.visit_path_segment_mut(el.value_mut());
}
}
}
impl FilterUsedGenerics {
fn new(fn_generics: &[crate::GenericParam]) -> (Vec<crate::GenericParam>, Self) {
let mut all_possible_generics = fn_generics.to_vec();
// The 'n lifetime may also be needed; we must add it in
all_possible_generics.insert(0, syn::GenericParam::Lifetime(syn::LifetimeParam::new(Lifetime::new("'n", proc_macro2::Span::call_site()))));
let modified = all_possible_generics
.iter()
.cloned()
.enumerate()
.map(|(index, mut generic)| {
let crate::GenericParam::Type(type_param) = &mut generic else { return generic };
// Sometimes the generics conflict with the type name so we rename the generics.
type_param.ident = format_ident!("G{index}");
generic
})
.collect::<Vec<_>>();
let generic_collector = Self {
used: vec![false; all_possible_generics.len()],
all: all_possible_generics,
};
(modified, generic_collector)
}
fn used<'a>(&'a self, modified: &'a [crate::GenericParam]) -> impl Iterator<Item = &'a crate::GenericParam> {
modified.iter().zip(&self.used).filter(|(_, used)| **used).map(move |(value, _)| value)
}
fn filter_unnecessary_generics(&mut self, modified: &mut Vec<syn::GenericParam>, ty: &mut Type) -> Vec<syn::GenericParam> {
self.used.fill(false);
// Find out which generics are necessary to support the node input
self.visit_type_mut(ty);
// Sometimes generics may reference other generics. This is a non-optimal way of dealing with that.
for _ in 0..=self.all.len() {
for (index, item) in modified.iter_mut().enumerate() {
if self.used[index] {
self.visit_generic_param_mut(item);
}
}
}
self.used(&*modified).cloned().collect()
}
}
+355 -5
View File
@@ -7,8 +7,8 @@ use syn::punctuated::Punctuated;
use syn::spanned::Spanned; use syn::spanned::Spanned;
use syn::token::{Comma, RArrow}; use syn::token::{Comma, RArrow};
use syn::{ use syn::{
AttrStyle, Attribute, Error, Expr, FnArg, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, ReturnType, TraitBound, Type, TypeImplTrait, TypeParam, AttrStyle, Attribute, Error, Expr, FnArg, GenericArgument, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, PathArguments, ReturnType,
TypeParamBound, Visibility, WhereClause, parse_quote, TraitBound, Type, TypeImplTrait, TypeParam, TypeParamBound, Visibility, WhereClause, parse_quote,
}; };
use crate::codegen::generate_node_code; use crate::codegen::generate_node_code;
@@ -39,6 +39,74 @@ pub(crate) struct ParsedNodeFn {
pub(crate) description: String, pub(crate) description: String,
} }
/// An `Attr<Marker>` slot in a parameter's read tuple: a declared attribute
/// read on that input's wire, not a wired input of its own.
#[derive(Clone, Debug)]
pub(crate) struct AttributeRead {
pub(crate) pat_ident: PatIdent,
pub(crate) marker: Type,
}
/// The write half of a record kernel's return: the element type in the first
/// tuple slot, then the attribute markers written and the ones removed. `None`
/// unless the value is a well-formed write tuple (a non-marker element first,
/// then only `Attr` and `RemoveAttr` slots, at least one).
pub(crate) struct RecordWrites {
pub(crate) element: Type,
pub(crate) markers: Vec<Type>,
pub(crate) removes: Vec<Type>,
}
pub(crate) fn record_writes(value: &Type) -> Option<RecordWrites> {
let Type::Tuple(tuple) = value else { return None };
let mut slots = tuple.elems.iter();
let element = slots.next()?;
if attr_marker(element).is_some() || remove_attr_marker(element).is_some() {
return None;
}
let mut markers = Vec::new();
let mut removes = Vec::new();
for slot in slots {
if let Some(marker) = attr_marker(slot) {
markers.push(marker);
} else if let Some(marker) = remove_attr_marker(slot) {
removes.push(marker);
} else {
return None;
}
}
(!markers.is_empty() || !removes.is_empty()).then(|| RecordWrites {
element: element.clone(),
markers,
removes,
})
}
/// Returns the marker type of an `Attr<Marker>` type, if `ty` is one.
pub(crate) fn attr_marker(ty: &Type) -> Option<Type> {
marker_of(ty, "Attr")
}
/// Returns the marker type of a `RemoveAttr<Marker>` type, if `ty` is one.
pub(crate) fn remove_attr_marker(ty: &Type) -> Option<Type> {
marker_of(ty, "RemoveAttr")
}
fn marker_of(ty: &Type, wrapper: &str) -> Option<Type> {
let Type::Path(path) = ty else { return None };
let segment = path.path.segments.last()?;
if segment.ident != wrapper {
return None;
}
let PathArguments::AngleBracketed(args) = &segment.arguments else { return None };
let mut types = args.args.iter().filter_map(|argument| match argument {
GenericArgument::Type(ty) => Some(ty),
_ => None,
});
let marker = types.next()?;
types.next().is_none().then(|| marker.clone())
}
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub(crate) struct NodeFnAttributes { pub(crate) struct NodeFnAttributes {
pub(crate) category: Option<LitStr>, pub(crate) category: Option<LitStr>,
@@ -56,6 +124,16 @@ pub(crate) struct NodeFnAttributes {
pub(crate) memoize: bool, pub(crate) memoize: bool,
/// Whether this node provides a scope /// Whether this node provides a scope
pub(crate) inject_scope: bool, pub(crate) inject_scope: bool,
/// Function producing a stand-in value while an async source node's real value is in flight
pub(crate) placeholder: Option<Path>,
/// Function overriding the generated `extent` method
pub(crate) extent: Option<Path>,
/// Function overriding the generated `eval_batch` method
pub(crate) batch: Option<Path>,
/// Whether partial upstream values are mapped to `Pending` instead of flowing into this node
pub(crate) no_partial: bool,
/// Whether this node keeps the plain-wire lowering during the record transition
pub(crate) plain: bool,
} }
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
@@ -63,7 +141,8 @@ pub enum ParsedValueSource {
#[default] #[default]
None, None,
Default(TokenStream2), Default(TokenStream2),
Scope(Expr), Scope(Box<Expr>),
SourceId,
} }
// #[widget(ParsedWidgetOverride::Hidden)] // #[widget(ParsedWidgetOverride::Hidden)]
@@ -118,6 +197,9 @@ pub struct ParsedField {
pub number_step: Option<LitFloat>, pub number_step: Option<LitFloat>,
pub unit: Option<LitStr>, pub unit: Option<LitStr>,
pub is_data_field: bool, pub is_data_field: bool,
/// The attribute reads destructured from this input's tuple, resolved
/// against this input's wire.
pub(crate) attribute_reads: Vec<AttributeRead>,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@@ -231,6 +313,8 @@ impl Parse for NumberRange {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct RegularParsedField { pub struct RegularParsedField {
pub ty: Type, pub ty: Type,
/// The original reference tokens when the parameter was written `&T`; `ty` holds the peeled inner type.
pub lend: Option<syn::TypeReference>,
pub exposed: bool, pub exposed: bool,
pub value_source: ParsedValueSource, pub value_source: ParsedValueSource,
pub number_soft_min: Option<NumberBound>, pub number_soft_min: Option<NumberBound>,
@@ -311,6 +395,11 @@ impl Parse for NodeFnAttributes {
let mut serialize = None; let mut serialize = None;
let mut memoize = false; let mut memoize = false;
let mut inject_scope = false; let mut inject_scope = false;
let mut placeholder = None;
let mut extent = None;
let mut batch = None;
let mut no_partial = false;
let mut plain = false;
let content = input; let content = input;
// let content; // let content;
@@ -453,13 +542,70 @@ impl Parse for NodeFnAttributes {
} }
inject_scope = true; inject_scope = true;
} }
// Function producing a stand-in value for an async source node while the spawned future is in flight.
// The node reports `Partial` with the stand-in until the real value lands; without a placeholder it reports `Pending`.
//
// Example usage:
// #[node_macro::node(..., placeholder(empty_image), ...)]
"placeholder" => {
let meta = meta.require_list()?;
if placeholder.is_some() {
return Err(Error::new_spanned(meta, "Multiple 'placeholder' attributes are not allowed"));
}
let parsed_path: Path = meta
.parse_args()
.map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'placeholder', e.g., placeholder(empty_image)"))?;
placeholder = Some(parsed_path);
}
// Function overriding the generated `extent` method, replacing the default meet over the node's inputs.
//
// Example usage:
// #[node_macro::node(..., extent(my_extent), ...)]
"extent" => {
let meta = meta.require_list()?;
if extent.is_some() {
return Err(Error::new_spanned(meta, "Multiple 'extent' attributes are not allowed"));
}
let parsed_path: Path = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'extent', e.g., extent(my_extent)"))?;
extent = Some(parsed_path);
}
// Function overriding the generated `eval_batch` method, replacing the trait's per-lane spec loop.
//
// Example usage:
// #[node_macro::node(..., batch(my_batch), ...)]
"batch" => {
let meta = meta.require_list()?;
if batch.is_some() {
return Err(Error::new_spanned(meta, "Multiple 'batch' attributes are not allowed"));
}
let parsed_path: Path = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'batch', e.g., batch(my_batch)"))?;
batch = Some(parsed_path);
}
// Instructs the generated eval to report `Pending` instead of passing partial upstream values into this node.
//
// Example usage:
// #[node_macro::node(..., no_partial, ...)]
"plain" => {
let path = meta.require_path_only()?;
if plain {
return Err(Error::new_spanned(path, "Multiple 'plain' attributes are not allowed"));
}
plain = true;
}
"no_partial" => {
let path = meta.require_path_only()?;
if no_partial {
return Err(Error::new_spanned(path, "Multiple 'no_partial' attributes are not allowed"));
}
no_partial = true;
}
_ => { _ => {
return Err(Error::new_spanned( return Err(Error::new_spanned(
meta, meta,
indoc!( indoc!(
r#" r#"
Unsupported attribute in `node`. Unsupported attribute in `node`.
Supported attributes are 'category', 'name', 'path', 'skip_impl', 'properties', 'cfg', 'shader_node', 'serialize', 'memoize', and 'inject_scope'. Supported attributes are 'category', 'name', 'path', 'skip_impl', 'properties', 'cfg', 'shader_node', 'serialize', 'memoize', 'inject_scope', 'placeholder', 'extent', 'batch', and 'no_partial'.
Example usage: Example usage:
#[node_macro::node(..., name("Test Node"), ...)] #[node_macro::node(..., name("Test Node"), ...)]
"# "#
@@ -493,6 +639,11 @@ impl Parse for NodeFnAttributes {
serialize, serialize,
memoize, memoize,
inject_scope, inject_scope,
placeholder,
extent,
batch,
no_partial,
plain,
}) })
} }
} }
@@ -584,8 +735,24 @@ fn parse_inputs(inputs: &Punctuated<FnArg, Comma>) -> syn::Result<(Input, Vec<Pa
context_features, context_features,
}); });
} else if let Pat::Ident(pat_ident) = &**pat { } else if let Pat::Ident(pat_ident) = &**pat {
if attr_marker(ty).is_some() {
return Err(Error::new_spanned(pat_ident, "an attribute read binds to an input: destructure it as `(value, Attr<..>)`"));
}
let field = parse_field(pat_ident.clone(), (**ty).clone(), attrs).map_err(|e| Error::new_spanned(pat_ident, format!("Failed to parse argument '{}': {}", pat_ident.ident, e)))?; let field = parse_field(pat_ident.clone(), (**ty).clone(), attrs).map_err(|e| Error::new_spanned(pat_ident, format!("Failed to parse argument '{}': {}", pat_ident.ident, e)))?;
fields.push(field); fields.push(field);
} else if let Pat::Tuple(pat_tuple) = &**pat {
let field = parse_read_tuple(pat_tuple, ty, attrs, index)?;
fields.push(field);
} else if let Pat::Wild(wild) = &**pat {
let pat_ident = PatIdent {
attrs: wild.attrs.clone(),
by_ref: None,
mutability: None,
ident: format_ident!("_unit{}", index, span = wild.underscore_token.span),
subpat: None,
};
let field = parse_field(pat_ident, (**ty).clone(), attrs).map_err(|e| Error::new_spanned(pat, format!("Failed to parse argument: {e}")))?;
fields.push(field);
} else { } else {
return Err(Error::new_spanned(pat, "Expected a simple identifier for the field name")); return Err(Error::new_spanned(pat, "Expected a simple identifier for the field name"));
} }
@@ -598,6 +765,85 @@ fn parse_inputs(inputs: &Punctuated<FnArg, Comma>) -> syn::Result<(Input, Vec<Pa
Ok((input, fields)) Ok((input, fields))
} }
/// Splits a lazy input's `Output = (T, Attr<..>..)` tuple into the element
/// type (the wire type) and the declared reads on that edge. A tuple without
/// `Attr` slots is an ordinary tuple output and passes through untouched.
fn split_lazy_reads(output_type: Type) -> syn::Result<(Type, Vec<AttributeRead>)> {
let Type::Tuple(tuple) = &output_type else {
return Ok((output_type, Vec::new()));
};
if !tuple.elems.iter().any(|slot| attr_marker(slot).is_some()) {
return Ok((output_type, Vec::new()));
}
let spelling = "a lazy input with attribute reads declares `Output = (T, Attr<..>)`";
let mut slots = tuple.elems.iter();
let element = slots.next().ok_or_else(|| Error::new_spanned(tuple, spelling))?;
if attr_marker(element).is_some() {
return Err(Error::new_spanned(element, spelling));
}
let attribute_reads: Vec<AttributeRead> = slots
.enumerate()
.map(|(index, slot)| {
let marker = attr_marker(slot).ok_or_else(|| Error::new_spanned(slot, spelling))?;
Ok(AttributeRead {
pat_ident: PatIdent {
attrs: Vec::new(),
by_ref: None,
mutability: None,
ident: format_ident!("__lazy_read_{}", index, span = slot.span()),
subpat: None,
},
marker,
})
})
.collect::<syn::Result<_>>()?;
Ok((element.clone(), attribute_reads))
}
/// Parses a `(value, reads..): (T, Attr<..>..)` parameter: the value component
/// is an ordinary field of the value type, each `Attr` component a read bound
/// to this input's wire.
fn parse_read_tuple(pat_tuple: &syn::PatTuple, ty: &Type, attrs: &[Attribute], index: usize) -> syn::Result<ParsedField> {
let spelling = "an input with attribute reads destructures as `(value, Attr<..>)` over `(T, Attr<..>)`";
let Type::Tuple(ty_tuple) = ty else {
return Err(Error::new_spanned(ty, spelling));
};
if pat_tuple.elems.len() != ty_tuple.elems.len() || ty_tuple.elems.len() < 2 {
return Err(Error::new_spanned(pat_tuple, spelling));
}
let mut slots = pat_tuple.elems.iter().zip(ty_tuple.elems.iter());
let (value_pat, value_ty) = slots.next().expect("length checked above");
if attr_marker(value_ty).is_some() {
return Err(Error::new_spanned(value_ty, spelling));
}
let value_ident = match value_pat {
Pat::Ident(pat_ident) => pat_ident.clone(),
Pat::Wild(wild) => PatIdent {
attrs: wild.attrs.clone(),
by_ref: None,
mutability: None,
ident: format_ident!("_value{}", index, span = wild.underscore_token.span),
subpat: None,
},
_ => return Err(Error::new_spanned(value_pat, "Expected a simple identifier for the value component")),
};
let attribute_reads: Vec<AttributeRead> = slots
.map(|(pat, ty)| {
let marker = attr_marker(ty).ok_or_else(|| Error::new_spanned(ty, spelling))?;
let Pat::Ident(pat_ident) = pat else {
return Err(Error::new_spanned(pat, "Expected a simple identifier for the attribute read"));
};
Ok(AttributeRead {
pat_ident: pat_ident.clone(),
marker,
})
})
.collect::<syn::Result<_>>()?;
let mut field = parse_field(value_ident.clone(), value_ty.clone(), attrs).map_err(|e| Error::new_spanned(&value_ident, format!("Failed to parse argument '{}': {}", value_ident.ident, e)))?;
field.attribute_reads = attribute_reads;
Ok(field)
}
/// Parse context feature identifiers from the trait bounds of a context parameter. /// Parse context feature identifiers from the trait bounds of a context parameter.
fn parse_context_feature_idents(ty: &Type) -> Vec<Ident> { fn parse_context_feature_idents(ty: &Type) -> Vec<Ident> {
let mut features = Vec::new(); let mut features = Vec::new();
@@ -723,7 +969,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
let value_source = match (default_value, scope) { let value_source = match (default_value, scope) {
(Some(_), Some(_)) => return Err(Error::new_spanned(&pat_ident, "Cannot have both `default` and `scope` attributes")), (Some(_), Some(_)) => return Err(Error::new_spanned(&pat_ident, "Cannot have both `default` and `scope` attributes")),
(Some(default_value), _) => ParsedValueSource::Default(default_value), (Some(default_value), _) => ParsedValueSource::Default(default_value),
(_, Some(scope)) => ParsedValueSource::Scope(scope), (_, Some(scope)) => ParsedValueSource::Scope(Box::new(scope)),
_ => ParsedValueSource::None, _ => ParsedValueSource::None,
}; };
@@ -816,6 +1062,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();
let (output_type, attribute_reads) = split_lazy_reads(output_type)?;
Ok(ParsedField { Ok(ParsedField {
pat_ident, pat_ident,
ty: ParsedFieldType::Node(NodeParsedField { ty: ParsedFieldType::Node(NodeParsedField {
@@ -830,6 +1077,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
number_step, number_step,
unit, unit,
is_data_field, is_data_field,
attribute_reads,
}) })
} else { } else {
let implementations = extract_attribute(attrs, "implementations") let implementations = extract_attribute(attrs, "implementations")
@@ -837,6 +1085,11 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();
let (ty, lend) = match ty {
Type::Reference(reference) => ((*reference.elem).clone(), Some(reference)),
ty => (ty, None),
};
// Error if a float literal is given for a bound on an integer-typed field // Error if a float literal is given for a bound on an integer-typed field
if is_integer_type(&ty) { if is_integer_type(&ty) {
let bound_attrs = [ let bound_attrs = [
@@ -869,6 +1122,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
number_hard_max, number_hard_max,
number_mode_range, number_mode_range,
ty, ty,
lend,
value_source, value_source,
implementations, implementations,
gpu_image, gpu_image,
@@ -880,6 +1134,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
number_step, number_step,
unit, unit,
is_data_field, is_data_field,
attribute_reads: Vec::new(),
}) })
} }
} }
@@ -931,6 +1186,10 @@ pub fn new_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<TokenS
let crate_ident = CrateIdent::default(); let crate_ident = CrateIdent::default();
let mut parsed_node = parse_node_fn(attr, item.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse node function:\n{e}")))?; let mut parsed_node = parse_node_fn(attr, item.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse node function:\n{e}")))?;
parsed_node.replace_impl_trait_in_input(); parsed_node.replace_impl_trait_in_input();
if parsed_node.injects_async_source_fields() {
let core_types = crate_ident.gcore()?.clone();
parsed_node.inject_async_source_fields(&core_types);
}
crate::validation::validate_node_fn(&parsed_node).map_err(|e| Error::new(e.span(), format!("Validation error:\n{e}")))?; crate::validation::validate_node_fn(&parsed_node).map_err(|e| Error::new(e.span(), format!("Validation error:\n{e}")))?;
generate_node_code(&crate_ident, &parsed_node).map_err(|e| Error::new(e.span(), format!("Failed to generate node code:\n{e}"))) generate_node_code(&crate_ident, &parsed_node).map_err(|e| Error::new(e.span(), format!("Failed to generate node code:\n{e}")))
} }
@@ -958,6 +1217,49 @@ impl ParsedNodeFn {
self.input.pat_ident.ident = Ident::new("__ctx", self.input.pat_ident.ident.span()); self.input.pat_ident.ident = Ident::new("__ctx", self.input.pat_ident.ident.span());
} }
} }
pub fn injects_async_source_fields(&self) -> bool {
self.is_async || crate::codegen::is_source_kernel(&self.output_type)
}
pub fn inject_async_source_fields(&mut self, core_types: &TokenStream2) {
let hidden_field = |name: &str, ty: Type, value_source: ParsedValueSource| ParsedField {
pat_ident: PatIdent {
attrs: Vec::new(),
by_ref: None,
mutability: None,
ident: Ident::new(name, proc_macro2::Span::call_site()),
subpat: None,
},
name: None,
description: String::new(),
widget_override: ParsedWidgetOverride::Hidden,
ty: ParsedFieldType::Regular(RegularParsedField {
ty,
lend: None,
exposed: false,
value_source,
number_soft_min: None,
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: false,
implementations: Default::default(),
gpu_image: false,
}),
number_display_decimal_places: None,
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
};
self.fields.push(hidden_field(
"_runtime",
parse_quote!(#core_types::runtime::RuntimeHandle),
ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::runtime::RuntimeNode"))),
));
self.fields.push(hidden_field("_source", parse_quote!(#core_types::SourceId), ParsedValueSource::SourceId));
}
} }
#[cfg(test)] #[cfg(test)]
@@ -1082,6 +1384,11 @@ mod tests {
serialize: None, serialize: None,
memoize: false, memoize: false,
inject_scope: false, inject_scope: false,
placeholder: None,
extent: None,
batch: None,
no_partial: false,
plain: false,
}, },
fn_name: Ident::new("add", Span::call_site()), fn_name: Ident::new("add", Span::call_site()),
struct_name: Ident::new("Add", Span::call_site()), struct_name: Ident::new("Add", Span::call_site()),
@@ -1102,6 +1409,7 @@ mod tests {
description: String::new(), description: String::new(),
widget_override: ParsedWidgetOverride::None, widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField { ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64), ty: parse_quote!(f64),
exposed: false, exposed: false,
value_source: ParsedValueSource::None, value_source: ParsedValueSource::None,
@@ -1117,6 +1425,7 @@ mod tests {
number_step: None, number_step: None,
unit: None, unit: None,
is_data_field: false, is_data_field: false,
attribute_reads: Vec::new(),
}], }],
body: TokenStream2::new(), body: TokenStream2::new(),
description: String::from("Multi\nLine\n"), description: String::from("Multi\nLine\n"),
@@ -1152,6 +1461,11 @@ mod tests {
serialize: None, serialize: None,
memoize: false, memoize: false,
inject_scope: false, inject_scope: false,
placeholder: None,
extent: None,
batch: None,
no_partial: false,
plain: false,
}, },
fn_name: Ident::new("transform", Span::call_site()), fn_name: Ident::new("transform", Span::call_site()),
struct_name: Ident::new("Transform", Span::call_site()), struct_name: Ident::new("Transform", Span::call_site()),
@@ -1181,6 +1495,7 @@ mod tests {
number_step: None, number_step: None,
unit: None, unit: None,
is_data_field: false, is_data_field: false,
attribute_reads: Vec::new(),
}, },
ParsedField { ParsedField {
pat_ident: pat_ident("translate"), pat_ident: pat_ident("translate"),
@@ -1188,6 +1503,7 @@ mod tests {
description: String::new(), description: String::new(),
widget_override: ParsedWidgetOverride::None, widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField { ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(DVec2), ty: parse_quote!(DVec2),
exposed: false, exposed: false,
value_source: ParsedValueSource::None, value_source: ParsedValueSource::None,
@@ -1203,6 +1519,7 @@ mod tests {
number_step: None, number_step: None,
unit: None, unit: None,
is_data_field: false, is_data_field: false,
attribute_reads: Vec::new(),
}, },
], ],
body: TokenStream2::new(), body: TokenStream2::new(),
@@ -1236,6 +1553,11 @@ mod tests {
serialize: None, serialize: None,
memoize: false, memoize: false,
inject_scope: false, inject_scope: false,
placeholder: None,
extent: None,
batch: None,
no_partial: false,
plain: false,
}, },
fn_name: Ident::new("circle", Span::call_site()), fn_name: Ident::new("circle", Span::call_site()),
struct_name: Ident::new("Circle", Span::call_site()), struct_name: Ident::new("Circle", Span::call_site()),
@@ -1256,6 +1578,7 @@ mod tests {
description: String::new(), description: String::new(),
widget_override: ParsedWidgetOverride::None, widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField { ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64), ty: parse_quote!(f64),
exposed: false, exposed: false,
value_source: ParsedValueSource::Default(quote!(50.)), value_source: ParsedValueSource::Default(quote!(50.)),
@@ -1271,6 +1594,7 @@ mod tests {
number_step: None, number_step: None,
unit: None, unit: None,
is_data_field: false, is_data_field: false,
attribute_reads: Vec::new(),
}], }],
body: TokenStream2::new(), body: TokenStream2::new(),
description: "Test\n".into(), description: "Test\n".into(),
@@ -1302,6 +1626,11 @@ mod tests {
serialize: None, serialize: None,
memoize: false, memoize: false,
inject_scope: false, inject_scope: false,
placeholder: None,
extent: None,
batch: None,
no_partial: false,
plain: false,
}, },
fn_name: Ident::new("levels", Span::call_site()), fn_name: Ident::new("levels", Span::call_site()),
struct_name: Ident::new("Levels", Span::call_site()), struct_name: Ident::new("Levels", Span::call_site()),
@@ -1322,6 +1651,7 @@ mod tests {
description: String::new(), description: String::new(),
widget_override: ParsedWidgetOverride::None, widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField { ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64), ty: parse_quote!(f64),
exposed: false, exposed: false,
value_source: ParsedValueSource::None, value_source: ParsedValueSource::None,
@@ -1342,6 +1672,7 @@ mod tests {
number_step: None, number_step: None,
unit: None, unit: None,
is_data_field: false, is_data_field: false,
attribute_reads: Vec::new(),
}], }],
body: TokenStream2::new(), body: TokenStream2::new(),
description: String::new(), description: String::new(),
@@ -1380,6 +1711,11 @@ mod tests {
serialize: None, serialize: None,
memoize: false, memoize: false,
inject_scope: false, inject_scope: false,
placeholder: None,
extent: None,
batch: None,
no_partial: false,
plain: false,
}, },
fn_name: Ident::new("add", Span::call_site()), fn_name: Ident::new("add", Span::call_site()),
struct_name: Ident::new("Add", Span::call_site()), struct_name: Ident::new("Add", Span::call_site()),
@@ -1400,6 +1736,7 @@ mod tests {
description: String::from("b"), description: String::from("b"),
widget_override: ParsedWidgetOverride::None, widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField { ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64), ty: parse_quote!(f64),
exposed: false, exposed: false,
value_source: ParsedValueSource::None, value_source: ParsedValueSource::None,
@@ -1415,6 +1752,7 @@ mod tests {
number_step: None, number_step: None,
unit: None, unit: None,
is_data_field: false, is_data_field: false,
attribute_reads: Vec::new(),
}], }],
body: TokenStream2::new(), body: TokenStream2::new(),
description: String::new(), description: String::new(),
@@ -1461,6 +1799,11 @@ mod tests {
serialize: None, serialize: None,
memoize: false, memoize: false,
inject_scope: false, inject_scope: false,
placeholder: None,
extent: None,
batch: None,
no_partial: false,
plain: false,
}, },
fn_name: Ident::new("load_image", Span::call_site()), fn_name: Ident::new("load_image", Span::call_site()),
struct_name: Ident::new("LoadImage", Span::call_site()), struct_name: Ident::new("LoadImage", Span::call_site()),
@@ -1481,6 +1824,7 @@ mod tests {
description: String::new(), description: String::new(),
widget_override: ParsedWidgetOverride::None, widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField { ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(String), ty: parse_quote!(String),
exposed: true, exposed: true,
value_source: ParsedValueSource::None, value_source: ParsedValueSource::None,
@@ -1496,6 +1840,7 @@ mod tests {
number_step: None, number_step: None,
unit: None, unit: None,
is_data_field: false, is_data_field: false,
attribute_reads: Vec::new(),
}], }],
body: TokenStream2::new(), body: TokenStream2::new(),
description: String::new(), description: String::new(),
@@ -1527,6 +1872,11 @@ mod tests {
serialize: None, serialize: None,
memoize: false, memoize: false,
inject_scope: false, inject_scope: false,
placeholder: None,
extent: None,
batch: None,
no_partial: false,
plain: false,
}, },
fn_name: Ident::new("custom_node", Span::call_site()), fn_name: Ident::new("custom_node", Span::call_site()),
struct_name: Ident::new("CustomNode", Span::call_site()), struct_name: Ident::new("CustomNode", Span::call_site()),
@@ -146,7 +146,7 @@ impl PerPixelAdjustCodegen<'_> {
ParamType::Uniform => quote!(uniform.#ident), ParamType::Uniform => quote!(uniform.#ident),
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let context = quote!(()); let context = quote!(&());
let entry_point_mod = &self.entry_point_mod; let entry_point_mod = &self.entry_point_mod;
let entry_point_name = &self.entry_point_name_ident; let entry_point_name = &self.entry_point_name_ident;
@@ -231,9 +231,10 @@ impl PerPixelAdjustCodegen<'_> {
description: "".to_string(), description: "".to_string(),
widget_override: Default::default(), widget_override: Default::default(),
ty: ParsedFieldType::Regular(RegularParsedField { ty: ParsedFieldType::Regular(RegularParsedField {
ty: parse_quote!(&'a WgpuExecutor), ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
lend: None,
exposed: true, exposed: true,
value_source: ParsedValueSource::Scope(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode")), value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode"))),
number_soft_min: None, number_soft_min: None,
number_soft_max: None, number_soft_max: None,
number_hard_min: None, number_hard_min: None,
@@ -246,6 +247,7 @@ impl PerPixelAdjustCodegen<'_> {
number_step: None, number_step: None,
unit: None, unit: None,
is_data_field: false, is_data_field: false,
attribute_reads: Vec::new(),
}); });
// find exactly one gpu_image field, runtime doesn't support more than 1 atm // find exactly one gpu_image field, runtime doesn't support more than 1 atm
@@ -287,7 +289,7 @@ impl PerPixelAdjustCodegen<'_> {
wgsl_shader: crate::WGSL_SHADER, wgsl_shader: crate::WGSL_SHADER,
fragment_shader_name: super::#entry_point_name, fragment_shader_name: super::#entry_point_name,
has_uniform: #has_uniform, has_uniform: #has_uniform,
}, #gpu_image, #uniform_buffer).await }, #gpu_image, #uniform_buffer)
} }
}; };
@@ -305,7 +307,7 @@ impl PerPixelAdjustCodegen<'_> {
fn_name: self.shader_node_mod.clone(), fn_name: self.shader_node_mod.clone(),
struct_name: format_ident!("{}", self.shader_node_mod.to_string().to_case(Case::Pascal)), struct_name: format_ident!("{}", self.shader_node_mod.to_string().to_case(Case::Pascal)),
mod_name: self.shader_node_mod.clone(), mod_name: self.shader_node_mod.clone(),
fn_generics: vec![parse_quote!('a: 'n)], fn_generics: Vec::new(),
where_clause: None, where_clause: None,
input: Input { input: Input {
pat_ident: self.parsed.input.pat_ident.clone(), pat_ident: self.parsed.input.pat_ident.clone(),
@@ -314,7 +316,7 @@ impl PerPixelAdjustCodegen<'_> {
context_features: self.parsed.input.context_features.clone(), context_features: self.parsed.input.context_features.clone(),
}, },
output_type: raster_gpu, output_type: raster_gpu,
is_async: true, is_async: false,
fields, fields,
body, body,
description: self.parsed.description.clone(), description: self.parsed.description.clone(),
+274 -2
View File
@@ -1,6 +1,6 @@
use crate::parsing::{Implementation, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField}; use crate::parsing::{Implementation, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, attr_marker, record_writes, remove_attr_marker};
use proc_macro_error2::emit_error; use proc_macro_error2::emit_error;
use quote::quote; use quote::{ToTokens, quote};
use syn::spanned::Spanned; use syn::spanned::Spanned;
use syn::{GenericParam, Type}; use syn::{GenericParam, Type};
@@ -11,6 +11,10 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
validate_primary_input_expose, validate_primary_input_expose,
validate_min_max, validate_min_max,
validate_range_slider_bounds, validate_range_slider_bounds,
validate_async_source,
validate_lend_fields,
validate_record_io,
validate_lazy_reads,
]; ];
for validator in validators { for validator in validators {
@@ -20,6 +24,256 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
Ok(()) Ok(())
} }
fn validate_record_io(parsed: &ParsedNodeFn) {
let value = crate::codegen::slot_value_type(&parsed.output_type);
if let Type::Tuple(tuple) = &value {
let has_marker_slot = tuple.elems.iter().any(|slot| attr_marker(slot).is_some() || remove_attr_marker(slot).is_some());
if has_marker_slot && record_writes(&value).is_none() {
emit_error!(
parsed.output_type.span(),
"a record return tuple is the element first, then only `Attr<..>` writes and `RemoveAttr<..>` deletions"
);
}
} else if attr_marker(&value).is_some() || remove_attr_marker(&value).is_some() {
emit_error!(parsed.output_type.span(), "an attribute write needs an element in the first tuple slot, e.g. `(T, Attr<..>)`");
}
let writes = record_writes(&value);
let has_reads = parsed
.fields
.iter()
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
if !has_reads && writes.is_none() {
return;
}
if parsed.is_async || crate::codegen::is_source_kernel(&parsed.output_type) {
emit_error!(parsed.output_type.span(), "attribute io is not supported on async source kernels");
}
if crate::codegen::is_poll_kernel(&parsed.output_type) {
emit_error!(parsed.output_type.span(), "attribute io needs a plain or `Result<_, Interrupt>` kernel, not a `GPoll` one");
}
for field in parsed.fields.iter().skip(1) {
if matches!(field.ty, ParsedFieldType::Node(_)) {
emit_error!(field.pat_ident.span(), "record nodes take no lazy inputs yet");
}
}
for (index, field) in parsed.fields.iter().enumerate() {
if field.attribute_reads.is_empty() {
continue;
}
if field.is_data_field {
emit_error!(field.pat_ident.span(), "a `#[data]` field has no wire to read attributes from");
continue;
}
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. }) => {
emit_error!(field.pat_ident.span(), "attribute reads need an owned value; take `T` instead of `&T`");
}
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => {
if matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty()) {
emit_error!(field.pat_ident.span(), "attribute-only inputs are not supported yet; the value component cannot be `()`");
}
let is_token_carrier = index == 0 && implementations.is_empty() && crate::codegen::unbounded_generic(parsed, ty).is_some();
if !is_token_carrier && crate::codegen::contains_open_generic(parsed, ty) {
emit_error!(
field.pat_ident.span(),
"a reading input's value is monomorphic for now; use a concrete type or an unbounded passthrough generic in the primary input"
);
}
}
// Lazy-input reads are validated by `validate_lazy_reads`; a
// record-io node already rejects lazy inputs above.
ParsedFieldType::Node(_) => {}
}
}
let Some(carrier) = parsed.fields.first() else {
emit_error!(
parsed.fn_name.span(),
"attribute io needs a primary input as the first parameter after the context (`_: ()` for none)"
);
return;
};
let carrier_ty = match &carrier.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend: None, .. }) if !carrier.is_data_field => Some(ty),
_ => None,
};
let Some(carrier_ty) = carrier_ty else {
emit_error!(
carrier.pat_ident.span(),
"a record node's primary input is an owned element, an unbounded passthrough generic, or `_: ()`; not `#[data]`, `&T`, or `impl Node`"
);
return;
};
let no_carrier = matches!(carrier_ty, Type::Tuple(tuple) if tuple.elems.is_empty());
let token = match (no_carrier, &carrier.ty) {
(false, ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. })) if implementations.is_empty() => crate::codegen::unbounded_generic(parsed, ty),
_ => None,
};
let element = writes.as_ref().map(|writes| &writes.element).unwrap_or(&value);
match &token {
Some(token) => {
if !matches!(crate::codegen::bare_ident(element), Some(ident) if ident == token) {
emit_error!(
parsed.output_type.span(),
"a generic element passes through unchanged: return `{}` in the first tuple position",
token
);
}
}
None => {
if let Some(ident) = crate::codegen::unbounded_generic(parsed, element) {
emit_error!(parsed.output_type.span(), "the returned generic element `{}` has no matching input", ident);
} else if !no_carrier && crate::codegen::contains_open_generic(parsed, carrier_ty) {
emit_error!(
carrier.pat_ident.span(),
"record element reads are monomorphic for now; use a concrete element type or an unbounded passthrough generic"
);
} else if crate::codegen::contains_open_generic(parsed, element) {
emit_error!(parsed.output_type.span(), "a written element must be a concrete type");
}
}
}
for field in &parsed.fields {
let mut seen_reads: Vec<String> = Vec::new();
for read in &field.attribute_reads {
let marker = read.marker.to_token_stream().to_string();
if seen_reads.contains(&marker) {
emit_error!(read.pat_ident.span(), "attribute `{}` is read twice from `{}`", marker, field.pat_ident.ident);
}
seen_reads.push(marker);
}
}
if let Some(writes) = &writes {
let mut seen_writes: Vec<String> = Vec::new();
for marker in &writes.markers {
let written = marker.to_token_stream().to_string();
if seen_writes.contains(&written) {
emit_error!(parsed.output_type.span(), "attribute `{}` is written twice", written);
}
seen_writes.push(written);
}
let mut seen_removes: Vec<String> = Vec::new();
for marker in &writes.removes {
let removed = marker.to_token_stream().to_string();
if seen_removes.contains(&removed) {
emit_error!(parsed.output_type.span(), "attribute `{}` is removed twice", removed);
}
if seen_writes.contains(&removed) {
emit_error!(parsed.output_type.span(), "attribute `{}` is both written and removed", removed);
}
seen_removes.push(removed);
}
if no_carrier && !writes.removes.is_empty() {
emit_error!(parsed.output_type.span(), "a node without a primary input writes a fresh record; there is nothing to remove");
}
}
}
fn validate_lazy_reads(parsed: &ParsedNodeFn) {
if !crate::codegen::has_lazy_reads(parsed) {
return;
}
if !crate::codegen::record_flip(parsed) {
emit_error!(
parsed.fn_name.span(),
"attribute reads on a lazy input need the record lowering; routing, `plain`, shader, batch, and non-row-assignable generic nodes keep the plain one"
);
}
for field in &parsed.fields {
let ParsedFieldType::Node(NodeParsedField { output_type, .. }) = &field.ty else {
continue;
};
if field.attribute_reads.is_empty() {
continue;
}
if crate::codegen::unbounded_generic(parsed, output_type).is_some() {
emit_error!(
field.pat_ident.span(),
"an unbounded generic source forwards its whole record; attribute reads need a concrete output type"
);
}
let mut seen: Vec<String> = Vec::new();
for read in &field.attribute_reads {
let marker = read.marker.to_token_stream().to_string();
if seen.contains(&marker) {
emit_error!(read.marker.span(), "attribute `{}` is read twice from `{}`", marker, field.pat_ident.ident);
}
seen.push(marker);
}
}
}
fn validate_async_source(parsed: &ParsedNodeFn) {
let snapshot_ctx = matches!(&parsed.input.ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "CtxSnapshot"));
let future_kernel = crate::codegen::is_source_kernel(&parsed.output_type);
if let Some(placeholder) = &parsed.attributes.placeholder
&& !parsed.is_async
&& !future_kernel
{
emit_error!(
placeholder.span(),
"`placeholder` applies only to async and source kernels; a synchronous node never reports `Partial`, so the stand-in is unused"
);
}
if parsed.is_async && future_kernel {
emit_error!(
parsed.output_type.span(),
"an `async fn` kernel already is the async part; returning `SourceFuture` is the sync-prologue form, so drop the `async` keyword or return the value directly"
);
return;
}
if !parsed.is_async {
if snapshot_ctx {
emit_error!(
parsed.input.pat_ident.span(),
"`CtxSnapshot` is the async source context; synchronous nodes take `impl Ctx` and read through extract bounds"
);
}
if !future_kernel {
return;
}
}
if parsed.is_async {
for field in &parsed.fields {
if matches!(field.ty, ParsedFieldType::Node(_)) {
emit_error!(
field.pat_ident.span(),
"`async fn` source nodes cannot take `impl Node` inputs: the spawned future outlives any borrow of the graph, so it cannot evaluate other nodes; use the sync-prologue form (return `SourceFuture`) to evaluate lazy inputs before spawning"
);
}
}
}
}
fn validate_lend_fields(parsed: &ParsedNodeFn) {
let future_kernel = crate::codegen::is_source_kernel(&parsed.output_type);
for field in &parsed.fields {
let ParsedFieldType::Regular(RegularParsedField { lend: Some(reference), .. }) = &field.ty else {
continue;
};
if let Some(mutability) = &reference.mutability {
emit_error!(mutability.span(), "reference parameters are read-only lends; `&mut` is not supported");
}
if let Some(lifetime) = &reference.lifetime {
emit_error!(lifetime.span(), "reference parameters use the eval lifetime implicitly; write a bare `&T`");
}
if field.is_data_field {
emit_error!(field.pat_ident.span(), "`#[data]` fields are node-resident state and cannot be references");
}
if parsed.is_async || future_kernel {
emit_error!(
field.pat_ident.span(),
"source kernels move their inputs into the spawned task, so they cannot take reference parameters"
);
}
}
}
fn validate_min_max(parsed: &ParsedNodeFn) { fn validate_min_max(parsed: &ParsedNodeFn) {
for field in &parsed.fields { for field in &parsed.fields {
if let ParsedField { if let ParsedField {
@@ -138,6 +392,18 @@ fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
fn validate_implementations_for_generics(parsed: &ParsedNodeFn) { fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
let has_skip_impl = parsed.attributes.skip_impl; let has_skip_impl = parsed.attributes.skip_impl;
let routing = crate::codegen::routing_io(parsed);
let record_token = crate::codegen::record_shape(parsed).and_then(|shape| match shape.carrier {
crate::codegen::RecordCarrier::Token(token) => Some(token),
_ => None,
});
let opaque_record_generic = |ty: &Type| {
let ident = match ty {
Type::Path(path) => path.path.get_ident(),
_ => None,
};
ident.is_some() && (ident == routing.as_ref().map(|routing| &routing.generic) || ident == record_token.as_ref())
};
if !has_skip_impl && !parsed.fn_generics.is_empty() { if !has_skip_impl && !parsed.fn_generics.is_empty() {
for field in &parsed.fields { for field in &parsed.fields {
@@ -149,6 +415,9 @@ fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
let pat_ident = &field.pat_ident; let pat_ident = &field.pat_ident;
match &field.ty { match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => { ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => {
if opaque_record_generic(ty) {
continue;
}
if contains_generic_param(ty, &parsed.fn_generics) && implementations.is_empty() { if contains_generic_param(ty, &parsed.fn_generics) && implementations.is_empty() {
emit_error!( emit_error!(
ty.span(), ty.span(),
@@ -166,6 +435,9 @@ fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
implementations, implementations,
.. ..
}) => { }) => {
if opaque_record_generic(output_type) {
continue;
}
if (contains_generic_param(input_type, &parsed.fn_generics) || contains_generic_param(output_type, &parsed.fn_generics)) && implementations.is_empty() { if (contains_generic_param(input_type, &parsed.fn_generics) || contains_generic_param(output_type, &parsed.fn_generics)) && implementations.is_empty() {
emit_error!( emit_error!(
pat_ident.span(), pat_ident.span(),
+27 -40
View File
@@ -1,17 +1,14 @@
use crate::brush_cache::BrushCache; use crate::brush_cache::BrushCache;
use crate::brush_stroke::{BrushStroke, BrushStyle}; use crate::brush_stroke::{BrushStroke, BrushStyle};
use core_types::Ctx;
use core_types::blending::BlendMode; use core_types::blending::BlendMode;
use core_types::bounds::{BoundingBox, RenderBoundingBox}; use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::color::{Alpha, Color, Pixel, Sample}; use core_types::color::{Alpha, Color, Pixel, Sample};
use core_types::generic::FnNode;
use core_types::list::{Item, List}; use core_types::list::{Item, List};
use core_types::math::bbox::{AxisAlignedBbox, Bbox}; use core_types::math::bbox::{AxisAlignedBbox, Bbox};
use core_types::registry::FutureWrapperNode;
use core_types::transform::Transform; use core_types::transform::Transform;
use core_types::uuid::NodeId; use core_types::uuid::NodeId;
use core_types::value::ClonedNode;
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM}; use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM};
use core_types::{Ctx, Node};
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use raster_nodes::blending_nodes::blend_colors; use raster_nodes::blending_nodes::blend_colors;
use raster_nodes::std_nodes::{empty_image, extend_image_to_bounds}; use raster_nodes::std_nodes::{empty_image, extend_image_to_bounds};
@@ -63,7 +60,7 @@ impl<P: Pixel + Alpha> Sample for BrushStampGenerator<P> {
/// The feather exponent is calculated from hardness to determine edge softness. /// The feather exponent is calculated from hardness to determine edge softness.
/// Used internally to create the brush texture before stamping it repeatedly along a stroke path. /// Used internally to create the brush texture before stamping it repeatedly along a stroke path.
#[node_macro::node(category(""), skip_impl)] #[node_macro::node(category(""), skip_impl)]
fn brush_stamp_generator(#[unit(" px")] diameter: f64, color: Color, hardness: f64, flow: f64) -> BrushStampGenerator<Color> { fn brush_stamp_generator(_: impl Ctx, #[unit(" px")] diameter: f64, color: Color, hardness: f64, flow: f64) -> BrushStampGenerator<Color> {
// Diameter // Diameter
let radius = diameter / 2.; let radius = diameter / 2.;
@@ -83,9 +80,9 @@ fn brush_stamp_generator(#[unit(" px")] diameter: f64, color: Color, hardness: f
/// Used to efficiently paint brush strokes. Applies the same texture repeatedly at different positions with proper blending and boundary handling. /// Used to efficiently paint brush strokes. Applies the same texture repeatedly at different positions with proper blending and boundary handling.
#[node_macro::node(category(""), skip_impl)] #[node_macro::node(category(""), skip_impl)]
fn blit<BlendFn>(mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>> fn blit<BlendFn>(_: impl Ctx, mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>>
where where
BlendFn: for<'any_input> Node<'any_input, (Color, Color), Output = Color>, BlendFn: Fn(Color, Color) -> Color,
{ {
if positions.is_empty() { if positions.is_empty() {
return target; return target;
@@ -125,7 +122,7 @@ where
for x in blit_area_offset.x..blit_area_offset.x + blit_area_dimensions.x { for x in blit_area_offset.x..blit_area_offset.x + blit_area_dimensions.x {
let src_pixel = texture.data[texture_index(x, y)]; let src_pixel = texture.data[texture_index(x, y)];
let dst_pixel = &mut element.data_mut().data[target_index(x + clamp_start.x, y + clamp_start.y)]; let dst_pixel = &mut element.data_mut().data[target_index(x + clamp_start.x, y + clamp_start.y)];
*dst_pixel = blend_mode.eval((src_pixel, *dst_pixel)); *dst_pixel = blend_mode(src_pixel, *dst_pixel);
} }
} }
} }
@@ -134,10 +131,10 @@ where
target target
} }
pub async fn create_brush_texture(brush_style: &BrushStyle) -> Raster<CPU> { pub fn create_brush_texture(brush_style: &BrushStyle) -> Raster<CPU> {
let stamp = brush_stamp_generator(brush_style.diameter, brush_style.color, brush_style.hardness, brush_style.flow); let stamp = brush_stamp_generator(&(), brush_style.diameter, brush_style.color, brush_style.hardness, brush_style.flow);
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(brush_style.diameter), 0., -DVec2::splat(brush_style.diameter / 2.)); let transform = DAffine2::from_scale_angle_translation(DVec2::splat(brush_style.diameter), 0., -DVec2::splat(brush_style.diameter / 2.));
let blank_texture = empty_image((), transform, List::new_from_element(Color::TRANSPARENT)).into_iter().next().unwrap_or_default(); let blank_texture = empty_image(&(), transform, List::new_from_element(Color::TRANSPARENT)).into_iter().next().unwrap_or_default();
let image = blend_stamp_closure(stamp, blank_texture, |a, b| blend_colors(a, b, BlendMode::Normal, 1.)); let image = blend_stamp_closure(stamp, blank_texture, |a, b| blend_colors(a, b, BlendMode::Normal, 1.));
image.into_element() image.into_element()
@@ -188,7 +185,7 @@ pub fn blend_with_mode(background: Item<Raster<CPU>>, foreground: Item<Raster<CP
/// Generates the brush strokes painted with the Brush tool as a raster image. /// Generates the brush strokes painted with the Brush tool as a raster image.
/// If an input image is supplied, strokes are drawn on top of it, expanding bounds as needed. /// If an input image is supplied, strokes are drawn on top of it, expanding bounds as needed.
#[node_macro::node(category("Raster"))] #[node_macro::node(category("Raster"))]
async fn brush( fn brush(
_: impl Ctx, _: impl Ctx,
/// Optional raster content that may be drawn onto. /// Optional raster content that may be drawn onto.
mut background: List<Raster<CPU>>, mut background: List<Raster<CPU>>,
@@ -224,7 +221,7 @@ async fn brush(
let mut brush_plan = cache.compute_brush_plan(list_item, &draw_strokes); let mut brush_plan = cache.compute_brush_plan(list_item, &draw_strokes);
// TODO: Find a way to handle more than one item // TODO: Find a way to handle more than one item
let Some(mut actual_image) = extend_image_to_bounds((), List::new_from_item(brush_plan.background), background_bounds).into_iter().next() else { let Some(mut actual_image) = extend_image_to_bounds(&(), List::new_from_item(brush_plan.background), background_bounds).into_iter().next() else {
return List::new(); return List::new();
}; };
@@ -234,7 +231,7 @@ async fn brush(
// TODO: apply rotation from layer to stamp for non-rotationally-symmetric brushes. // TODO: apply rotation from layer to stamp for non-rotationally-symmetric brushes.
let mut brush_texture = cache.get_cached_brush(&stroke.style); let mut brush_texture = cache.get_cached_brush(&stroke.style);
if brush_texture.is_none() { if brush_texture.is_none() {
let tex = create_brush_texture(&stroke.style).await; let tex = create_brush_texture(&stroke.style);
cache.store_brush(stroke.style.clone(), tex.clone()); cache.store_brush(stroke.style.clone(), tex.clone());
brush_texture = Some(tex); brush_texture = Some(tex);
} }
@@ -255,21 +252,14 @@ async fn brush(
let stroke_origin_in_layer = bbox.start - snap_offset - DVec2::splat(stroke.style.diameter / 2.); let stroke_origin_in_layer = bbox.start - snap_offset - DVec2::splat(stroke.style.diameter / 2.);
let stroke_to_layer = DAffine2::from_translation(stroke_origin_in_layer) * DAffine2::from_scale(stroke_size); let stroke_to_layer = DAffine2::from_translation(stroke_origin_in_layer) * DAffine2::from_scale(stroke_size);
let normal_blend = FnNode::new(|(a, b)| blend_colors(a, b, BlendMode::Normal, 1.));
let blit_node = BlitNode::new(
FutureWrapperNode::new(ClonedNode::new(brush_texture)),
FutureWrapperNode::new(ClonedNode::new(positions)),
FutureWrapperNode::new(ClonedNode::new(normal_blend)),
);
let blit_target = if idx == 0 { let blit_target = if idx == 0 {
let target = core::mem::take(&mut brush_plan.first_stroke_texture); let target = core::mem::take(&mut brush_plan.first_stroke_texture);
extend_image_to_bounds((), List::new_from_item(target), stroke_to_layer) extend_image_to_bounds(&(), List::new_from_item(target), stroke_to_layer)
} else { } else {
empty_image((), stroke_to_layer, List::new_from_element(Color::TRANSPARENT)) empty_image(&(), stroke_to_layer, List::new_from_element(Color::TRANSPARENT))
// EmptyImageNode::new(CopiedNode::new(stroke_to_layer), CopiedNode::new(Color::TRANSPARENT)).eval(())
}; };
let list = blit_node.eval(blit_target).await; let list = blit(&(), blit_target, brush_texture, positions, |a, b| blend_colors(a, b, BlendMode::Normal, 1.));
assert_eq!(list.len(), 1); assert_eq!(list.len(), 1);
list.into_iter().next().unwrap_or_default() list.into_iter().next().unwrap_or_default()
}; };
@@ -291,7 +281,7 @@ async fn brush(
for stroke in trace.into_iter().map(|row| row.into_element()) { for stroke in trace.into_iter().map(|row| row.into_element()) {
let mut brush_texture = cache.get_cached_brush(&stroke.style); let mut brush_texture = cache.get_cached_brush(&stroke.style);
if brush_texture.is_none() { if brush_texture.is_none() {
let tex = create_brush_texture(&stroke.style).await; let tex = create_brush_texture(&stroke.style);
cache.store_brush(stroke.style.clone(), tex.clone()); cache.store_brush(stroke.style.clone(), tex.clone());
brush_texture = Some(tex); brush_texture = Some(tex);
} }
@@ -305,17 +295,15 @@ async fn brush(
_ => BlendMode::Restore, _ => BlendMode::Restore,
}; };
let blend_params = FnNode::new(move |(a, b)| blend_colors(a, b, mask_blend_mode, 1.)); erase_restore_mask = blit(&(), List::new_from_item(erase_restore_mask), brush_texture, positions, move |a, b| {
let blit_node = BlitNode::new( blend_colors(a, b, mask_blend_mode, 1.)
FutureWrapperNode::new(ClonedNode::new(brush_texture)), })
FutureWrapperNode::new(ClonedNode::new(positions)), .into_iter()
FutureWrapperNode::new(ClonedNode::new(blend_params)), .next()
); .unwrap_or_default();
erase_restore_mask = blit_node.eval(List::new_from_item(erase_restore_mask)).await.into_iter().next().unwrap_or_default();
} }
let blend_params = FnNode::new(|(a, b)| blend_colors(a, b, BlendMode::MultiplyAlpha, 1.)); actual_image = blend_image_closure(erase_restore_mask, actual_image, |a, b| blend_colors(a, b, BlendMode::MultiplyAlpha, 1.));
actual_image = blend_image_closure(erase_restore_mask, actual_image, |a, b| blend_params.eval((a, b)));
} }
let transform: DAffine2 = actual_image.attribute_cloned_or_default(ATTR_TRANSFORM); let transform: DAffine2 = actual_image.attribute_cloned_or_default(ATTR_TRANSFORM);
@@ -410,16 +398,16 @@ mod test {
#[test] #[test]
fn test_brush_texture() { fn test_brush_texture() {
let size = 20.; let size = 20.;
let image = brush_stamp_generator(size, Color::BLACK, 100., 100.); let image = brush_stamp_generator(&(), size, Color::BLACK, 100., 100.);
assert_eq!(image.transform(), DAffine2::from_scale_angle_translation(DVec2::splat(size.ceil()), 0., -DVec2::splat(size / 2.))); assert_eq!(image.transform(), DAffine2::from_scale_angle_translation(DVec2::splat(size.ceil()), 0., -DVec2::splat(size / 2.)));
// center pixel should be BLACK // center pixel should be BLACK
assert_eq!(image.sample(DVec2::splat(0.), DVec2::ONE), Some(Color::BLACK)); assert_eq!(image.sample(DVec2::splat(0.), DVec2::ONE), Some(Color::BLACK));
} }
#[tokio::test] #[test]
async fn test_brush_output_size() { fn test_brush_output_size() {
let image = brush( let image = brush(
(), &(),
&BrushCache::default(), &BrushCache::default(),
List::new_from_element(Raster::new_cpu(Image::<Color>::default())), List::new_from_element(Raster::new_cpu(Image::<Color>::default())),
List::new_from_element(BrushStroke { List::new_from_element(BrushStroke {
@@ -433,8 +421,7 @@ mod test {
blend_mode: BlendMode::Normal, blend_mode: BlendMode::Normal,
}, },
}), }),
) );
.await;
assert_eq!(image.element(0).unwrap().width, 20); assert_eq!(image.element(0).unwrap().width, 20);
} }
} }
+14 -13
View File
@@ -1,6 +1,7 @@
use core_types::gpoll::GPoll;
use core_types::list::List; use core_types::list::List;
use core_types::transform::Footprint; use core_types::transform::Footprint;
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl}; use core_types::{CacheHash, Color, Context, Ctx, DeriveCtx, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use graphic_types::vector_types::GradientStops; use graphic_types::vector_types::GradientStops;
use graphic_types::{Artboard, Graphic, Vector}; use graphic_types::{Artboard, Graphic, Vector};
@@ -61,8 +62,8 @@ fn animation_time(
} }
#[node_macro::node(category("Debug"))] #[node_macro::node(category("Debug"))]
async fn quantize_real_time<T>( fn quantize_real_time<T>(
ctx: impl Ctx + ExtractAll + CloneVarArgs, ctx: impl Ctx + ExtractRealTime + DeriveCtx,
#[implementations( #[implementations(
Context -> bool, Context -> bool,
Context -> u32, Context -> u32,
@@ -84,11 +85,11 @@ async fn quantize_real_time<T>(
Context -> List<f64>, Context -> List<f64>,
Context -> (), Context -> (),
)] )]
value: impl Node<'n, Context<'static>, Output = T>, value: impl Node<Context<'_>, Output = T>,
#[default(1)] #[default(1)]
#[unit("sec")] #[unit("sec")]
quantum: f64, quantum: f64,
) -> T { ) -> GPoll<T> {
let time = ctx.try_real_time().unwrap_or_default(); let time = ctx.try_real_time().unwrap_or_default();
let time = time / 1000.; let time = time / 1000.;
let mut quantized_time = (time * quantum.recip()).round() / quantum.recip(); let mut quantized_time = (time * quantum.recip()).round() / quantum.recip();
@@ -96,13 +97,13 @@ async fn quantize_real_time<T>(
quantized_time = time; quantized_time = time;
} }
let quantized_time = quantized_time * 1000.; let quantized_time = quantized_time * 1000.;
let new_context = OwnedContextImpl::from(ctx).with_real_time(quantized_time); let scope = ctx.scope().with_real_time(Some(quantized_time));
value.eval(Some(new_context.into())).await value.eval(&ctx.with_scope(&scope))
} }
#[node_macro::node(category("Debug"))] #[node_macro::node(category("Debug"))]
async fn quantize_animation_time<T>( fn quantize_animation_time<T>(
ctx: impl Ctx + ExtractAll + CloneVarArgs, ctx: impl Ctx + ExtractAnimationTime + DeriveCtx,
#[implementations( #[implementations(
Context -> bool, Context -> bool,
Context -> u32, Context -> u32,
@@ -124,18 +125,18 @@ async fn quantize_animation_time<T>(
Context -> List<f64>, Context -> List<f64>,
Context -> (), Context -> (),
)] )]
value: impl Node<'n, Context<'static>, Output = T>, value: impl Node<Context<'_>, Output = T>,
#[default(1)] #[default(1)]
#[unit("sec")] #[unit("sec")]
quantum: f64, quantum: f64,
) -> T { ) -> GPoll<T> {
let time = ctx.try_animation_time().unwrap_or_default(); let time = ctx.try_animation_time().unwrap_or_default();
let mut quantized_time = (time * quantum.recip()).round() / quantum.recip(); let mut quantized_time = (time * quantum.recip()).round() / quantum.recip();
if !quantized_time.is_finite() { if !quantized_time.is_finite() {
quantized_time = time; quantized_time = time;
} }
let new_context = OwnedContextImpl::from(ctx).with_animation_time(quantized_time); let scope = ctx.scope().with_animation_time(Some(quantized_time));
value.eval(Some(new_context.into())).await value.eval(&ctx.with_scope(&scope))
} }
/// Produces the current position of the user's pointer within the document canvas. /// Produces the current position of the user's pointer within the document canvas.
+2 -2
View File
@@ -47,7 +47,7 @@ fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> List<GradientStops> {
} }
#[node_macro::node(category("Context"), path(core_types::vector))] #[node_macro::node(category("Context"), path(core_types::vector))]
async fn read_position( fn read_position(
ctx: impl Ctx + ExtractPosition, ctx: impl Ctx + ExtractPosition,
_primary: (), _primary: (),
/// The number of nested loops to traverse outwards (from the innermost loop) to get the position from. The most upstream loop is level 0, and downstream loops add levels. /// The number of nested loops to traverse outwards (from the innermost loop) to get the position from. The most upstream loop is level 0, and downstream loops add levels.
@@ -64,7 +64,7 @@ async fn read_position(
/// ///
/// Nested loops can enable 2D or higher-dimensional iteration by using the *Loop Level* parameter to read the index from outer levels of loops. /// Nested loops can enable 2D or higher-dimensional iteration by using the *Loop Level* parameter to read the index from outer levels of loops.
#[node_macro::node(category("Context"), path(core_types::vector))] #[node_macro::node(category("Context"), path(core_types::vector))]
async fn read_index( fn read_index(
ctx: impl Ctx + ExtractIndex, ctx: impl Ctx + ExtractIndex,
_primary: (), _primary: (),
/// The number of nested loops to traverse outwards (from the innermost loop) to get the index from. The most upstream loop is level 0, and downstream loops add levels. /// The number of nested loops to traverse outwards (from the innermost loop) to get the index from. The most upstream loop is level 0, and downstream loops add levels.
@@ -1,120 +1,16 @@
use core::f64; use core_types::context::{Context, ContextModification, Ctx, DeriveCtx};
use core_types::context::{CloneVarArgs, Context, ContextFeatures, Ctx, ExtractAll}; use core_types::gpoll::Interrupt;
use core_types::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
use core_types::transform::Footprint;
use core_types::uuid::NodeId;
use core_types::{Color, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::vector_types::GradientStops;
use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
/// Filters out what should be unused components of the context based on the specified requirements. /// Filters out what should be unused components of the context based on the specified requirements.
/// This node is inserted by the compiler to "zero out" unused context components. /// This node is inserted by the compiler to "zero out" unused context components.
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
async fn context_modification<T>( fn context_modification<T>(
ctx: impl Ctx + CloneVarArgs + ExtractAll, ctx: impl Ctx + DeriveCtx,
/// The data to pass through, evaluated with the stripped down context. /// The data to pass through, evaluated with the stripped down context.
#[implementations( value: impl Node<Context<'_>, Output = T>,
Context -> (),
Context -> bool,
Context -> u32,
Context -> u64,
Context -> f32,
Context -> f64,
Context -> String,
Context -> DAffine2,
Context -> Footprint,
Context -> DVec2,
Context -> List<String>,
Context -> List<NodeId>,
Context -> List<f64>,
Context -> List<u8>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Artboard>,
Context -> List<GradientStops>,
Context -> AttributeDyn,
Context -> AttributeValueDyn,
Context -> ListDyn,
)]
value: impl Node<Context<'static>, Output = T>,
/// The parts of the context to keep when evaluating the input value. All other parts are nullified. /// The parts of the context to keep when evaluating the input value. All other parts are nullified.
features_to_keep: ContextFeatures, modification: ContextModification,
) -> T { ) -> Result<T, Interrupt> {
let new_context = OwnedContextImpl::from_flags(ctx, features_to_keep); let scope = ctx.scope().nullified(modification.features, Some(modification.sources()));
value.eval(&ctx.nullified(modification.features, &scope))
value.eval(Some(new_context.into())).await
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::graphene_hash::CacheHash;
use core_types::transform::Footprint;
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
/// Verifies that nullified context fields don't affect the cache hash — only the kept features matter.
#[test]
fn test_nullified_context_hash_stability() {
use core_types::Context;
use std::sync::Arc;
let original_ctx: Context = Some(Arc::new(
OwnedContextImpl::empty()
.with_footprint(Footprint::default())
.with_index(1)
.with_real_time(10.5)
.with_vararg(Box::new("test"))
.with_animation_time(20.25),
));
// A second context with different values for the nullified fields
let changed_ctx: Context = Some(Arc::new(
OwnedContextImpl::empty()
.with_footprint(Footprint::default())
.with_index(2)
.with_real_time(999.9)
.with_vararg(Box::new("test"))
.with_animation_time(888.8),
));
// Nullify everything — both should hash the same regardless of their field values
let features_to_keep = ContextFeatures::empty();
let nullified1 = OwnedContextImpl::from_flags(original_ctx.clone().unwrap(), features_to_keep);
let nullified2 = OwnedContextImpl::from_flags(changed_ctx.clone().unwrap(), features_to_keep);
let mut hasher1 = DefaultHasher::new();
nullified1.cache_hash(&mut hasher1);
let mut hasher2 = DefaultHasher::new();
nullified2.cache_hash(&mut hasher2);
assert_eq!(
hasher1.finish(),
hasher2.finish(),
"Hash of nullified context should remain stable regardless of input changes when features are nullified"
);
// Keep only footprint and varargs — both have the same footprint and vararg, so hash should still match
let partial_features = ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS;
let partial1 = OwnedContextImpl::from_flags(original_ctx.clone().unwrap(), partial_features);
let partial2 = OwnedContextImpl::from_flags(changed_ctx.clone().unwrap(), partial_features);
let mut hasher3 = DefaultHasher::new();
partial1.cache_hash(&mut hasher3);
let mut hasher4 = DefaultHasher::new();
partial2.cache_hash(&mut hasher4);
assert_eq!(
hasher3.finish(),
hasher4.finish(),
"Hash should be stable when keeping only footprint and varargs and their values are the same"
);
}
} }
+2 -2
View File
@@ -29,8 +29,8 @@ fn unwrap_option<T: Default>(_: impl Ctx, #[implementations(Option<f64>, Option<
input.unwrap_or_default() input.unwrap_or_default()
} }
/// Meant for debugging purposes, not general use. Clones the input value. /// Clones the element out of its record wire.
#[node_macro::node(category("Debug"))] #[node_macro::node(category("Debug"))]
fn clone<'i, T: Clone + 'i>(_: impl Ctx, #[implementations(&List<Raster<CPU>>)] value: &'i T) -> T { fn clone<T: Clone>(_: impl Ctx, #[implementations(List<Raster<CPU>>)] value: &T) -> T {
value.clone() value.clone()
} }
+2
View File
@@ -5,6 +5,8 @@ pub mod debug;
pub mod extract_xy; pub mod extract_xy;
pub mod memo; pub mod memo;
pub mod ops; pub mod ops;
#[cfg(test)]
mod record;
// Re-export all nodes // Re-export all nodes
pub use animation::*; pub use animation::*;
+273 -39
View File
@@ -1,54 +1,288 @@
use core_types::WasmNotSend; use core_types::arena::ArenaCell;
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll, ExtractArena};
use core_types::frame_table::{FrameTable, Lookup};
use core_types::gpoll::{Extent, Finality, GPoll};
use core_types::graphene_hash::CacheHash; use core_types::graphene_hash::CacheHash;
use core_types::memo::*; use core_types::memo::IORecord;
use std::hash::DefaultHasher; use core_types::node::Node;
use std::hash::Hasher; use core_types::record::{OwnedRecord, RecordCapture, RecordValue, copy_record_bytes, record_from_bytes};
use core_types::registry::cache_key;
use std::sync::Arc; use std::sync::Arc;
use std::sync::Mutex; use std::sync::Mutex;
/// Helps speed up repeated renders in a computationally-heavy part of the node graph. /// Helps speed up repeated renders in a computationally-heavy part of the node graph.
/// ///
/// Stores the last evaluated data that flowed through this node and immediately returns that data on subsequent renders if the context has not changed. /// Stores a deep copy of the last record that flowed through this node and replays it on subsequent renders if the context has not changed.
#[node_macro::node(category("General"), path(graphene_core::memo), skip_impl)] #[node_macro::node(category("General"), path(graphene_core::memo), extent(memoize_extent))]
async fn memoize<I: CacheHash + Send + 'n, T: Clone + WasmNotSend>(input: I, #[data] cache: Arc<Mutex<Option<(u64, T)>>>, content: impl Node<I, Output = T>) -> T { fn memoize<'e>(
// Caches the output of a given node called with a specific input. ctx: impl Ctx + CacheHash + ExtractArena<'e>,
// #[data] cache: Arc<Mutex<Option<(u64, OwnedRecord, Finality)>>>,
// A cache miss occurs when the Option is None. In this case, the node evaluates the inner node and memoizes (stores) the result. content: impl Node<Context<'_>, Output = RecordValue<'e>>,
// ) -> GPoll<RecordValue<'e>> {
// A cache hit occurs when the Option is Some and has a stored hash matching the hash of the call argument. In this case, the node returns the cached value without re-evaluating the inner node. let key = cache_key(&ctx);
// if let Some((hash, copy, finality)) = cache.lock().unwrap().as_ref()
// Currently, only one input-output pair is cached. Subsequent calls with different inputs will overwrite the previous cache. && *hash == key
{
let mut hasher = DefaultHasher::new(); return match copy.replay(content.layout(), ctx.arena()) {
input.cache_hash(&mut hasher); Some(value) => match finality {
let hash = hasher.finish(); Finality::AllFinal => GPoll::Final(value),
Finality::Partial => GPoll::Partial(value),
if let Some(data) = cache.lock().as_ref().unwrap().as_ref().and_then(|data| (data.0 == hash).then_some(data.1.clone())) { },
return data; None => GPoll::arena_exhausted(),
};
} }
let result = content.eval(&ctx);
let value = content.eval(input).await; let publishable = match &result {
*cache.lock().unwrap() = Some((hash, value.clone())); GPoll::Final(value) => Some((value, Finality::AllFinal)),
value GPoll::Partial(value) => Some((value, Finality::Partial)),
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => None,
};
if let Some((value, finality)) = publishable {
// SAFETY: the value came from this edge, so it carries the edge's layout.
let copy = unsafe { OwnedRecord::copy_out(content.layout(), content.layout().rec(value)) };
*cache.lock().unwrap() = Some((key, copy, finality));
}
result
} }
type MonitorValue<I, T> = Arc<Mutex<Option<Arc<IORecord<I, T>>>>>; fn memoize_extent<C, NodeContent>(node: &MemoizeNode<NodeContent>, ctx: &C) -> GPoll<Extent>
where
NodeContent: Node<C>,
{
node.content.extent(ctx)
}
#[node_macro::node(category(""), path(graphene_core::memo), extent(frame_memo_extent))]
fn frame_memo<'e>(
ctx: impl Ctx + CacheHash + ExtractArena<'e>,
#[data] cell: ArenaCell<FrameTable<Box<[u8]>, 32>>,
content: impl Node<Context<'_>, Output = RecordValue<'e>>,
) -> GPoll<RecordValue<'e>> {
let arena = ctx.arena();
let table = match cell.load(arena) {
Some(table) => table,
None => match arena.alloc(FrameTable::new()) {
Some((table, weak)) => {
cell.store(weak);
table
}
None => return content.eval(&ctx),
},
};
// SAFETY: published bytes are same-frame copies of this edge's records,
// so they carry the edge's layout with live parked references.
let revive = |bytes: &'e Box<[u8]>| unsafe { record_from_bytes(content.layout(), bytes) };
match table.lookup(cache_key(ctx)) {
Lookup::Hit(Finality::AllFinal, bytes) => GPoll::Final(revive(bytes)),
Lookup::Hit(Finality::Partial, bytes) => GPoll::Partial(revive(bytes)),
Lookup::Vacant(slot) => match content.eval(&ctx) {
GPoll::Final(value) => {
// SAFETY: the value came from this edge, so it carries the edge's layout.
let bytes = unsafe { copy_record_bytes(content.layout(), content.layout().rec(&value)) };
GPoll::Final(revive(slot.publish(bytes, Finality::AllFinal)))
}
GPoll::Partial(value) => {
// SAFETY: as above.
let bytes = unsafe { copy_record_bytes(content.layout(), content.layout().rec(&value)) };
GPoll::Partial(revive(slot.publish(bytes, Finality::Partial)))
}
unpublishable => {
slot.release();
unpublishable
}
},
Lookup::Full => content.eval(&ctx),
}
}
fn frame_memo_extent<C, NodeContent>(node: &FrameMemoNode<NodeContent>, ctx: &C) -> GPoll<Extent>
where
NodeContent: Node<C>,
{
node.content.extent(ctx)
}
type MonitorValue = Arc<Mutex<Option<IORecord<CtxSnapshot, RecordCapture>>>>;
/// The Monitor node is used by the editor to access the data flowing through it. /// The Monitor node is used by the editor to access the data flowing through it.
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), properties("monitor_properties"), skip_impl)] #[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), properties("monitor_properties"))]
async fn monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>( fn monitor<'e>(ctx: impl Ctx + DeriveCtx + ExtractAll + ExtractArena<'e>, #[data] io: MonitorValue, content: impl Node<Context<'_>, Output = RecordValue<'e>>) -> GPoll<RecordValue<'e>> {
input: I, let result = content.eval(&ctx);
#[allow(clippy::type_complexity)] if let GPoll::Final(value) | GPoll::Partial(value) = &result {
#[data] // SAFETY: the value came from this edge, so it carries the edge's layout.
io: MonitorValue<I, T>, let captured = unsafe { RecordCapture::capture(content.layout(), content.layout().rec(value), ctx.arena()) };
content: impl Node<I, Output = T>, *io.lock().unwrap() = captured.map(|output| IORecord {
) -> T { input: CtxSnapshot::capture(ctx),
let output = content.eval(input.clone()).await; output,
*io.lock().unwrap() = Some(Arc::new(IORecord { input, output: output.clone() })); });
output }
result
} }
fn serialize_monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>(io: &MonitorValue<I, T>) -> Option<Arc<dyn std::any::Any + Send + Sync>> { fn serialize_monitor(io: &MonitorValue) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
let io = io.lock().unwrap(); let io = io.lock().unwrap();
io.as_ref().map(|output| output.clone() as Arc<dyn std::any::Any + Send + Sync>) io.as_ref().map(|io| Arc::new(io.clone()) as Arc<dyn std::any::Any + Send + Sync>)
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::SourceId;
use core_types::arena::Arena;
use core_types::context::{ContextImpl, EvalScope};
use core_types::registry::{EdgeHandle, ErasedNode, ErasedRecordNode};
use std::sync::atomic::{AtomicU32, Ordering};
struct CountingNode(AtomicU32);
impl<Input> Node<Input> for CountingNode {
type Output = u32;
fn eval(&self, _input: &Input) -> GPoll<u32> {
GPoll::Final(self.0.fetch_add(1, Ordering::Relaxed) + 1)
}
}
struct PartialCountingNode(AtomicU32);
impl<Input> Node<Input> for PartialCountingNode {
type Output = u32;
fn eval(&self, _input: &Input) -> GPoll<u32> {
GPoll::Partial(self.0.fetch_add(1, Ordering::Relaxed) + 1)
}
}
struct ValueNode<T>(T);
impl<T: Clone, Input> Node<Input> for ValueNode<T> {
type Output = T;
fn eval(&self, _input: &Input) -> GPoll<T> {
GPoll::Final(self.0.clone())
}
}
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
core_types::record::stack::reserve(1 << 16);
EvalScope::new(Some(0.5), None, None, generations, arena)
}
fn element_layout<T: Clone + Send + Sync + 'static>() -> core_types::record::Layout {
core_types::record::Layout::default().with_writes(0, core_types::record::element_write::<T>(), &[])
}
#[test]
fn monitor_serialize_exposes_the_capture_through_the_edge() {
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let layout = element_layout::<u32>();
let monitor = MonitorNode::new(core_types::record::RecordLift::<u32, _>::new(ValueNode(11u32)), &layout);
let handle = EdgeHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
assert!(handle.serialize().is_none(), "no capture before the first eval");
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
let GPoll::Final(_) = edge.eval(&ctx) else {
panic!("expected a final record");
};
let io = handle.serialize().expect("the eval landed a capture");
let io = io.downcast_ref::<IORecord<CtxSnapshot, RecordCapture>>().expect("the capture is the monitor io");
assert!(
core_types::context::ExtractFootprint::try_footprint(&io.input).is_none(),
"the root context has no footprint to capture"
);
let element = io.output.materialize_element(&arena).expect("the capture materializes inside the window");
assert_eq!(*element.downcast_ref::<u32>().unwrap(), 11);
}
#[test]
fn memoize_caches_across_evals() {
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let layout = element_layout::<u32>();
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0))), &layout);
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
}
#[test]
fn memo_invalidates_on_generation_bump() {
let arena = Arena::new(1024).unwrap();
let source: SourceId = 7;
let before = [(source, 1)];
let after = [(source, 2)];
let scope_before = scope_fixture(&before, &arena);
let scope_after = scope_fixture(&after, &arena);
let layout = element_layout::<u32>();
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0))), &layout);
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
assert_eq!(memoized.eval(&ContextImpl::root(&scope_after)), GPoll::Final(2));
}
#[test]
fn memo_replays_partiality_on_hit() {
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let layout = element_layout::<u32>();
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(PartialCountingNode(AtomicU32::new(0))), &layout);
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
assert_eq!(memoized.eval(&ctx), GPoll::Partial(1));
assert_eq!(memoized.eval(&ctx), GPoll::Partial(1));
}
#[test]
fn memoized_edges_stack_and_rewire() {
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let layout = element_layout::<u32>();
let edge = EdgeHandle::new_record::<u32>(Arc::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0)))) as Arc<ErasedRecordNode>);
let memoized = EdgeHandle::new_record::<u32>(Arc::new(MemoizeNode::new(edge.downcast_record::<u32>().unwrap(), &layout)) as Arc<ErasedRecordNode>);
let stacked = MemoizeNode::new(memoized.downcast_record::<u32>().unwrap(), &layout);
let stacked = core_types::record::RecordExtract::<u32, _>::new(stacked, &layout);
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
}
#[test]
fn frame_memo_shares_one_record_copy_per_frame() {
let arena = Arena::new(4096).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let layout = element_layout::<String>();
let memo = FrameMemoNode::new(core_types::record::RecordLift::<String, _>::new(ValueNode("lent out".to_string())), &layout);
let GPoll::Final(first) = memo.eval(&ctx) else {
panic!("the miss must fill the frame table");
};
let GPoll::Final(second) = memo.eval(&ctx) else {
panic!("the hit must revive the published record");
};
let first: &String = unsafe { core_types::record::borrow_element(layout.rec(&first)) };
let second: &String = unsafe { core_types::record::borrow_element(layout.rec(&second)) };
assert_eq!(first, "lent out");
assert!(std::ptr::eq(first, second), "the hit shares the parked payload");
}
} }
+13 -9
View File
@@ -1,23 +1,27 @@
use core_types::{Ctx, ExtractFootprint, ops::Convert, transform::Footprint}; use core_types::ExtractAll;
use core_types::runtime::SourceFuture;
use core_types::{Ctx, ops::Convert, ops::ConvertAsync, transform::Footprint};
use std::marker::PhantomData; use std::marker::PhantomData;
// Re-export TypeNode from core-types for convenience
pub use core_types::ops::TypeNode;
/// Passes-through the input value without changing it. This is useful for rerouting wires for organization purposes. /// Passes-through the input value without changing it. This is useful for rerouting wires for organization purposes.
#[node_macro::node(category("General"), skip_impl)] #[node_macro::node(category("General"), skip_impl)]
fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T { fn passthrough<T: Send>(_: impl Ctx, content: T) -> T {
content content
} }
#[node_macro::node(category(""), skip_impl)] #[node_macro::node(category(""), skip_impl)]
fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty: PhantomData<O>) -> O { fn into<T: Send + Into<O>, O: Send>(_: impl Ctx, value: T, #[data] _out_ty: PhantomData<O>) -> O {
value.into() value.into()
} }
#[node_macro::node(category(""), skip_impl)] #[node_macro::node(category(""), skip_impl)]
async fn convert<'i, T: 'i + Send + Convert<O, C>, O: 'i + Send, C: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: T, converter: C, _out_ty: PhantomData<O>) -> O { fn convert<T: Send + Convert<O, C>, O: Send, C: Send>(ctx: impl Ctx + ExtractAll, value: T, converter: C, #[data] _out_ty: PhantomData<O>) -> O {
value.convert(*ctx.try_footprint().unwrap_or(&Footprint::DEFAULT), converter).await value.convert(*ctx.try_footprint().unwrap_or(&Footprint::DEFAULT), converter)
}
#[node_macro::node(category(""), skip_impl)]
fn convert_async<T: Send + ConvertAsync<O, C>, O: Send + 'static, C: Send>(ctx: impl Ctx + ExtractAll, value: T, converter: C, #[data] _out_ty: PhantomData<O>) -> SourceFuture<O> {
value.convert(*ctx.try_footprint().unwrap_or(&Footprint::DEFAULT), converter)
} }
#[cfg(test)] #[cfg(test)]
@@ -26,6 +30,6 @@ mod test {
#[test] #[test]
pub fn passthrough_node() { pub fn passthrough_node() {
assert_eq!(passthrough((), &4), &4); assert_eq!(passthrough(&(), &4), &4);
} }
} }
File diff suppressed because it is too large. Load diff
+10 -14
View File
@@ -1,6 +1,7 @@
use core_types::gpoll::Interrupt;
use core_types::list::{Item, List}; use core_types::list::{Item, List};
use core_types::transform::TransformMut; use core_types::transform::TransformMut;
use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl}; use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, Color, Context, Ctx, DeriveCtx, ModifyFootprint};
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use graphic_types::graphic::{Graphic, IntoGraphicList}; use graphic_types::graphic::{Graphic, IntoGraphicList};
use graphic_types::{Artboard, Vector}; use graphic_types::{Artboard, Vector};
@@ -9,8 +10,8 @@ use vector_types::GradientStops;
/// Constructs a single-element `Artboard[]` with the given content and metadata stored as row attributes. /// Constructs a single-element `Artboard[]` with the given content and metadata stored as row attributes.
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
pub async fn create_artboard<T: IntoGraphicList>( pub fn create_artboard<T: IntoGraphicList>(
ctx: impl ExtractAll + CloneVarArgs + Ctx, ctx: impl Ctx + DeriveCtx + ModifyFootprint,
/// Graphics to include within the artboard. /// Graphics to include within the artboard.
#[implementations( #[implementations(
Context -> List<Graphic>, Context -> List<Graphic>,
@@ -22,7 +23,7 @@ pub async fn create_artboard<T: IntoGraphicList>(
Context -> List<GradientStops>, Context -> List<GradientStops>,
Context -> DAffine2, Context -> DAffine2,
)] )]
content: impl Node<Context<'static>, Output = T>, content: impl Node<Context<'_>, Output = T>,
/// Coordinate of the top-left corner of the artboard within the document. /// Coordinate of the top-left corner of the artboard within the document.
location: DVec2, location: DVec2,
/// Width and height of the artboard within the document. /// Width and height of the artboard within the document.
@@ -32,14 +33,9 @@ pub async fn create_artboard<T: IntoGraphicList>(
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible. /// Whether to cut off the contained content that extends outside the artboard, or keep it visible.
#[default(true)] #[default(true)]
clip: bool, clip: bool,
) -> List<Artboard> { ) -> Result<List<Artboard>, Interrupt> {
let footprint = ctx.try_footprint().copied(); let translated = ctx.modify_footprint(|footprint| footprint.translate(location));
let mut new_ctx = OwnedContextImpl::from(ctx); let content = content.eval(&translated.ctx())?.into_graphic_list();
if let Some(mut footprint) = footprint {
footprint.translate(location);
new_ctx = new_ctx.with_footprint(footprint);
}
let content = content.eval(new_ctx.into_context()).await.into_graphic_list();
// Normalize so `location` is the top-left corner and `dimensions` are positive (allowing negative input // Normalize so `location` is the top-left corner and `dimensions` are positive (allowing negative input
// dimensions to represent dragging from the opposite corner). Compute the corner using the raw signed // dimensions to represent dragging from the opposite corner). Compute the corner using the raw signed
@@ -50,11 +46,11 @@ pub async fn create_artboard<T: IntoGraphicList>(
let background = background.element(0).copied().unwrap_or(Color::WHITE); let background = background.element(0).copied().unwrap_or(Color::WHITE);
// Name is not stored here, it's resolved live from the parent layer's display name // Name is not stored here, it's resolved live from the parent layer's display name
List::new_from_item( Ok(List::new_from_item(
Item::new_from_element(Artboard::new(content)) Item::new_from_element(Artboard::new(content))
.with_attribute(ATTR_LOCATION, normalized_location) .with_attribute(ATTR_LOCATION, normalized_location)
.with_attribute(ATTR_DIMENSIONS, normalized_dimensions) .with_attribute(ATTR_DIMENSIONS, normalized_dimensions)
.with_attribute(ATTR_BACKGROUND, background) .with_attribute(ATTR_BACKGROUND, background)
.with_attribute(ATTR_CLIP, clip), .with_attribute(ATTR_CLIP, clip),
) ))
} }
+30 -26
View File
@@ -1,8 +1,9 @@
use core_types::bounds::{BoundingBox, RenderBoundingBox}; use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::gpoll::Interrupt;
use core_types::list::{AttributeDyn, AttributeValueDyn, Item, List, ListDyn}; use core_types::list::{AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
use core_types::registry::types::{Angle, SignedInteger}; use core_types::registry::types::{Angle, SignedInteger};
use core_types::uuid::NodeId; use core_types::uuid::NodeId;
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl}; use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, Color, Context, Ctx, DeriveCtx};
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use graphic_types::graphic::{Graphic, IntoGraphicList}; use graphic_types::graphic::{Graphic, IntoGraphicList};
use graphic_types::{Artboard, Vector}; use graphic_types::{Artboard, Vector};
@@ -108,8 +109,8 @@ pub fn extract_element<T: Clone + Default + Send + Sync + 'static>(
} }
#[node_macro::node(category("General"))] #[node_macro::node(category("General"))]
async fn map<Item: AnyHash + Send + Sync + CacheHash>( fn map<Item: AnyHash + Clone + Send + Sync + CacheHash>(
ctx: impl Ctx + CloneVarArgs + ExtractAll, ctx: impl Ctx + DeriveCtx,
#[implementations( #[implementations(
List<Graphic>, List<Graphic>,
List<Vector>, List<Vector>,
@@ -127,23 +128,24 @@ async fn map<Item: AnyHash + Send + Sync + CacheHash>(
Context -> List<GradientStops>, Context -> List<GradientStops>,
Context -> List<String>, Context -> List<String>,
)] )]
mapped: impl Node<Context<'static>, Output = List<Item>>, mapped: impl Node<Context<'_>, Output = List<Item>>,
) -> List<Item> { ) -> Result<List<Item>, Interrupt> {
let spilled = ctx.index_head();
let mut rows = List::new(); let mut rows = List::new();
for (i, row) in content.into_iter().enumerate() { for (i, row) in content.into_iter().enumerate() {
let owned_ctx = OwnedContextImpl::from(ctx.clone()); let item = List::new_from_item(row);
let owned_ctx = owned_ctx.with_vararg(Box::new(List::new_from_item(row))).with_index(i); let scoped = ctx.push_vararg(&item);
let list = mapped.eval(owned_ctx.into_context()).await; let list = mapped.eval(&scoped.ctx().promoted(&spilled, i as u64))?;
rows.extend(list); rows.extend(list);
} }
rows Ok(rows)
} }
#[node_macro::node(category("General"))] #[node_macro::node(category("General"))]
async fn mirror<T: 'n + Send + Clone>( fn mirror<T: Send + Clone>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
List<Graphic>, List<Graphic>,
@@ -229,8 +231,8 @@ pub fn path_of_subgraph(_: impl Ctx, node_path: List<NodeId>) -> List<NodeId> {
/// The value is type-erased into an `AttributeValueDyn` by an auto-inserted convert node, so this node only /// The value is type-erased into an `AttributeValueDyn` by an auto-inserted convert node, so this node only
/// monomorphizes over `T` instead of the cartesian product `(T, U)`. /// monomorphizes over `T` instead of the cartesian product `(T, U)`.
#[node_macro::node(category("Attributes: Write"))] #[node_macro::node(category("Attributes: Write"))]
async fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>( fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
ctx: impl ExtractAll + CloneVarArgs + Ctx, ctx: impl Ctx + DeriveCtx,
/// The `List` to set the named attribute on (one value per item). /// The `List` to set the named attribute on (one value per item).
#[implementations( #[implementations(
List<Artboard>, List<Artboard>,
@@ -252,15 +254,17 @@ async fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
name: String, name: String,
/// The node that produces the attribute value for each item. Called once per item with the item's index in context. /// The node that produces the attribute value for each item. Called once per item with the item's index in context.
#[implementations(Context -> AttributeValueDyn)] #[implementations(Context -> AttributeValueDyn)]
value: impl Node<'n, Context<'static>, Output = AttributeValueDyn>, value: impl Node<Context<'_>, Output = AttributeValueDyn>,
) -> List<T> { ) -> Result<List<T>, Interrupt> {
let spilled = ctx.index_head();
for index in 0..content.len() { for index in 0..content.len() {
let row = content.clone_item(index).expect("index is within bounds"); let row = content.clone_item(index).expect("index is within bounds");
let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_vararg(Box::new(List::new_from_item(row))).with_index(index); let item = List::new_from_item(row);
let v = value.eval(owned_ctx.into_context()).await; let scoped = ctx.push_vararg(&item);
let v = value.eval(&scoped.ctx().promoted(&spilled, index as u64))?;
content.set_attribute_value_dyn(&name, index, v); content.set_attribute_value_dyn(&name, index, v);
} }
content Ok(content)
} }
/// Sets a named attribute on the primary list, with each value taken from the corresponding item's element in the source list (paired by index, wrapping if the source has fewer items). /// Sets a named attribute on the primary list, with each value taken from the corresponding item's element in the source list (paired by index, wrapping if the source has fewer items).
@@ -497,7 +501,7 @@ fn read_attribute_raster(
/// Joins two `List`s of the same type, extending the base `List` with the items from the new `List`. /// Joins two `List`s of the same type, extending the base `List` with the items from the new `List`.
#[node_macro::node(category("General"))] #[node_macro::node(category("General"))]
pub async fn extend<T: 'n + Send + Clone>( pub fn extend<T: Send + Clone>(
_: impl Ctx, _: impl Ctx,
/// The `List` whose items will appear at the start of the extended `List`. /// The `List` whose items will appear at the start of the extended `List`.
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)] #[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
@@ -517,7 +521,7 @@ pub async fn extend<T: 'n + Send + Clone>(
/// Performs an obsolete function as part of a migration from an older document format. /// Performs an obsolete function as part of a migration from an older document format.
/// Users are advised to delete this node and replace it with a new one. /// Users are advised to delete this node and replace it with a new one.
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
pub async fn legacy_layer_extend<T: 'n + Send + Clone>( pub fn legacy_layer_extend<T: Send + Clone>(
_: impl Ctx, _: impl Ctx,
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)] base: List<T>, #[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)] base: List<T>,
#[expose] #[expose]
@@ -544,7 +548,7 @@ pub async fn legacy_layer_extend<T: 'n + Send + Clone>(
/// Nests the input graphical content in a wrapper graphic. This essentially "groups" the input. /// Nests the input graphical content in a wrapper graphic. This essentially "groups" the input.
/// The inverse of this node is 'Flatten Graphic'. /// The inverse of this node is 'Flatten Graphic'.
#[node_macro::node(category("General"))] #[node_macro::node(category("General"))]
pub async fn wrap_graphic<T: Into<Graphic> + 'n>( pub fn wrap_graphic<T: Into<Graphic>>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
List<Graphic>, List<Graphic>,
@@ -565,7 +569,7 @@ pub async fn wrap_graphic<T: Into<Graphic> + 'n>(
/// Converts a list of graphical content into a `Graphic[]` by placing it into an element of a new wrapper `Graphic[]`. /// Converts a list of graphical content into a `Graphic[]` by placing it into an element of a new wrapper `Graphic[]`.
/// If it is already a `Graphic[]`, it is not wrapped again. Use the 'Wrap Graphic' node if wrapping is always desired. /// If it is already a `Graphic[]`, it is not wrapped again. Use the 'Wrap Graphic' node if wrapping is always desired.
#[node_macro::node(category("General"))] #[node_macro::node(category("General"))]
pub async fn to_graphic<T: IntoGraphicList>( pub fn to_graphic<T: IntoGraphicList>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
List<Graphic>, List<Graphic>,
@@ -583,7 +587,7 @@ pub async fn to_graphic<T: IntoGraphicList>(
/// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled. /// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled.
#[node_macro::node(category("General"))] #[node_macro::node(category("General"))]
pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: bool) -> List<Graphic> { pub fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: bool) -> List<Graphic> {
// TODO: Avoid mutable reference, instead return a new List<Graphic>? // TODO: Avoid mutable reference, instead return a new List<Graphic>?
fn flatten_list(output_graphic_list: &mut List<Graphic>, current_graphic_list: List<Graphic>, fully_flatten: bool, recursion_depth: usize) { fn flatten_list(output_graphic_list: &mut List<Graphic>, current_graphic_list: List<Graphic>, fully_flatten: bool, recursion_depth: usize) {
for index in 0..current_graphic_list.len() { for index in 0..current_graphic_list.len() {
@@ -620,7 +624,7 @@ pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten:
/// Converts a `Graphic[]` into a `Vector[]` by deeply flattening any vector content it contains, and discarding any non-vector content. /// Converts a `Graphic[]` into a `Vector[]` by deeply flattening any vector content it contains, and discarding any non-vector content.
#[node_macro::node(category("Vector"))] #[node_macro::node(category("Vector"))]
pub async fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> { pub fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
let graphic_list = content.into_graphic_list(); let graphic_list = content.into_graphic_list();
let mut output: List<Vector> = graphic_list.clone().into_flattened_list(); let mut output: List<Vector> = graphic_list.clone().into_flattened_list();
@@ -653,19 +657,19 @@ pub async fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(L
/// Converts a `Graphic[]` into a `Raster[]` by deeply flattening any raster content it contains, and discarding any non-raster content. /// Converts a `Graphic[]` into a `Raster[]` by deeply flattening any raster content it contains, and discarding any non-raster content.
#[node_macro::node(category("Raster"))] #[node_macro::node(category("Raster"))]
pub async fn flatten_raster<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Raster<CPU>>)] content: T) -> List<Raster<CPU>> { pub fn flatten_raster<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Raster<CPU>>)] content: T) -> List<Raster<CPU>> {
content.into_flattened_list() content.into_flattened_list()
} }
/// Converts a `Graphic[]` into a `Color[]` by deeply flattening any color content it contains, and discarding any non-color content. /// Converts a `Graphic[]` into a `Color[]` by deeply flattening any color content it contains, and discarding any non-color content.
#[node_macro::node(category("General"))] #[node_macro::node(category("General"))]
pub async fn flatten_color<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] content: T) -> List<Color> { pub fn flatten_color<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] content: T) -> List<Color> {
content.into_flattened_list() content.into_flattened_list()
} }
/// Converts a `Graphic[]` into a `GradientStops[]` by deeply flattening any gradient content it contains, and discarding any non-gradient content. /// Converts a `Graphic[]` into a `GradientStops[]` by deeply flattening any gradient content it contains, and discarding any non-gradient content.
#[node_macro::node(category("General"))] #[node_macro::node(category("General"))]
pub async fn flatten_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<GradientStops>)] content: T) -> List<GradientStops> { pub fn flatten_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<GradientStops>)] content: T) -> List<GradientStops> {
content.into_flattened_list() content.into_flattened_list()
} }
-27
View File
@@ -1,27 +0,0 @@
use core_types::NodeIO;
use core_types::WasmNotSend;
pub use core_types::registry::{DowncastBothNode, DynAnyNode, FutureWrapperNode, PanicNode};
pub use core_types::{Node, generic, ops};
use dyn_any::StaticType;
pub use graph_craft::proto::{Any, NodeContainer, TypeErasedBox, TypeErasedNode};
use graph_craft::proto::{FutureAny, SharedNodeContainer};
pub trait IntoTypeErasedNode<'n> {
fn into_type_erased(self) -> TypeErasedBox<'n>;
}
impl<'n, N: 'n> IntoTypeErasedNode<'n> for N
where
N: for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + Sync + WasmNotSend,
{
fn into_type_erased(self) -> TypeErasedBox<'n> {
Box::new(self)
}
}
pub fn input_node<O: StaticType>(n: SharedNodeContainer) -> DowncastBothNode<(), O> {
downcast_node(n)
}
pub fn downcast_node<I: StaticType, O: StaticType>(n: SharedNodeContainer) -> DowncastBothNode<I, O> {
DowncastBothNode::new(n)
}
+1 -1
View File
@@ -1,9 +1,9 @@
pub mod any;
pub mod platform_application_io; pub mod platform_application_io;
pub mod render_background; pub mod render_background;
pub mod render_cache; pub mod render_cache;
pub mod render_node; pub mod render_node;
pub mod render_pixel_preview; pub mod render_pixel_preview;
pub mod runtime;
pub mod text; pub mod text;
pub use blending_nodes; pub use blending_nodes;
pub use brush_nodes as brush; pub use brush_nodes as brush;
@@ -3,9 +3,11 @@ use base64::Engine;
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
use canvas_utils::{Canvas, CanvasHandle}; use canvas_utils::{Canvas, CanvasHandle};
use core_types::color::SRGBA8; use core_types::color::SRGBA8;
use core_types::gpoll::GPoll;
use core_types::list::{Item, List}; use core_types::list::{Item, List};
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
use core_types::math::bbox::Bbox; use core_types::math::bbox::Bbox;
use core_types::runtime::SourceFuture;
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
use core_types::transform::Footprint; use core_types::transform::Footprint;
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
@@ -137,7 +139,7 @@ fn image_to_bytes(_: impl Ctx, image: List<Raster<CPU>>) -> List<u8> {
/// Loads binary from URLs and local asset paths. Returns a transparent placeholder if the resource fails to load, allowing rendering to continue. /// Loads binary from URLs and local asset paths. Returns a transparent placeholder if the resource fails to load, allowing rendering to continue.
#[node_macro::node(category("Web Request"))] #[node_macro::node(category("Web Request"))]
async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: String) -> Arc<[u8]> { async fn load_resource(_: impl Ctx, _primary: (), #[name("URL")] url: String) -> Arc<[u8]> {
let placeholder = || -> Arc<[u8]> { Arc::from(Vec::<u8>::new()) }; let placeholder = || -> Arc<[u8]> { Arc::from(Vec::<u8>::new()) };
let response = match reqwest::Client::new().get(&url).send().await { let response = match reqwest::Client::new().get(&url).send().await {
@@ -185,14 +187,14 @@ fn decode_image(_: impl Ctx, data: Arc<[u8]>) -> List<Raster<CPU>> {
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
async fn create_canvas(_: impl Ctx) -> CanvasHandle { fn create_canvas(_: impl Ctx) -> CanvasHandle {
CanvasHandle::new() CanvasHandle::new()
} }
/// Renders a view of the input graphic within an area defined by the *Footprint*. /// Renders a view of the input graphic within an area defined by the *Footprint*.
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
async fn rasterize<T: WasmNotSend + Clone + 'n>( async fn rasterize<T: WasmNotSend + Clone>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
List<Vector>, List<Vector>,
@@ -262,29 +264,37 @@ where
} }
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(category(""), inject_scope)]
pub async fn editor_api<'a: 'n>(_: impl Ctx, #[scope("editor-api")] editor_api: &'a PlatformEditorApi) -> &'a PlatformEditorApi { pub fn editor_api(_: impl Ctx, #[scope("editor-api")] editor_api: Arc<PlatformEditorApi>) -> Arc<PlatformEditorApi> {
editor_api editor_api
} }
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
pub async fn resource<'a: 'n>(_: impl Ctx, hash: ResourceHash, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Resource { pub fn resource(_: impl Ctx, hash: ResourceHash, #[scope(editor_api::IDENTIFIER)] editor_api: Arc<PlatformEditorApi>) -> SourceFuture<GPoll<Resource>> {
let application_io = editor_api.application_io.as_ref().expect("ApplicationIo must be available when using resources"); let application_io = editor_api.application_io.clone();
application_io.load_resource(hash).await.unwrap_or_else(|| { Box::pin(async move {
panic!("Resource {hash} not found"); let Some(application_io) = application_io else {
return GPoll::error("ApplicationIo not available");
};
match application_io.load_resource(hash).await {
Some(resource) => GPoll::Final(resource),
None => GPoll::error("resource not found"),
}
}) })
} }
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(category(""), inject_scope)]
pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> &'a ::wgpu_executor::WgpuExecutor { pub fn wgpu_executor(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Arc<PlatformEditorApi>) -> ::wgpu_executor::WgpuExecutorHandle {
editor_api ::wgpu_executor::WgpuExecutorHandle(
.application_io editor_api
.as_ref() .application_io
.expect("ApplicationIo not not available") .as_ref()
.gpu_executor() .expect("ApplicationIo not not available")
.expect("GPU executor not available") .gpu_executor_arc()
.expect("GPU executor not available"),
)
} }
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(category(""), inject_scope)]
pub async fn try_wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Option<&'a ::wgpu_executor::WgpuExecutor> { pub fn try_wgpu_executor(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Arc<PlatformEditorApi>) -> Option<::wgpu_executor::WgpuExecutorHandle> {
editor_api.application_io.as_ref()?.gpu_executor() editor_api.application_io.as_ref()?.gpu_executor_arc().map(::wgpu_executor::WgpuExecutorHandle)
} }
+13 -19
View File
@@ -9,14 +9,10 @@ use graphic_types::raster_types::Texture;
use rendering::{RenderParams, SvgRender, SvgRenderOutput}; use rendering::{RenderParams, SvgRender, SvgRenderOutput};
use std::fmt::Write; use std::fmt::Write;
use wgpu::util::DeviceExt; use wgpu::util::DeviceExt;
use wgpu_executor::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache}; use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
async fn render_background<'a: 'n>( fn render_background(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache, data: RenderOutput) -> RenderOutput {
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
data: RenderOutput,
) -> RenderOutput {
let footprint = ctx.footprint(); let footprint = ctx.footprint();
let render_params = ctx let render_params = ctx
.vararg(0) .vararg(0)
@@ -35,14 +31,12 @@ async fn render_background<'a: 'n>(
let data = match foreground_data { let data = match foreground_data {
RenderOutputType::Texture(foreground_texture) => { RenderOutputType::Texture(foreground_texture) => {
let doc_to_screen = render_params.footprint.transform.as_affine2(); let doc_to_screen = render_params.footprint.transform.as_affine2();
let blended = pipeline let blended = pipeline.run::<CompositeBackground>(&CompositeBackgroundArgs {
.run::<CompositeBackground>(&CompositeBackgroundArgs { foreground: foreground_texture.as_ref(),
foreground: foreground_texture.as_ref(), backgrounds: &metadata.backgrounds,
backgrounds: &metadata.backgrounds, document_to_screen: doc_to_screen,
document_to_screen: doc_to_screen, zoom: render_params.viewport_zoom.to_f32(),
zoom: render_params.viewport_zoom.to_f32(), });
})
.await;
RenderOutputType::Texture(blended) RenderOutputType::Texture(blended)
} }
@@ -121,9 +115,9 @@ async fn render_background<'a: 'n>(
} }
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(category(""), inject_scope)]
async fn composite_background_pipeline<'a: 'n>( fn composite_background_pipeline(
_ctx: impl Ctx, _ctx: impl Ctx,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>, #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
#[data] pipeline: WgpuPipelineCache, #[data] pipeline: WgpuPipelineCache,
) -> WgpuPipelineCache { ) -> WgpuPipelineCache {
if let Some(executor) = executor { if let Some(executor) = executor {
@@ -148,7 +142,7 @@ pub struct CompositeBackgroundArgs<'a> {
zoom: f32, zoom: f32,
} }
impl AsyncWgpuPipeline for CompositeBackground { impl WgpuPipeline for CompositeBackground {
type Args<'a> = CompositeBackgroundArgs<'a>; type Args<'a> = CompositeBackgroundArgs<'a>;
type Out = Texture; type Out = Texture;
@@ -331,7 +325,7 @@ impl AsyncWgpuPipeline for CompositeBackground {
} }
} }
async fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out { fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
let &CompositeBackgroundArgs { let &CompositeBackgroundArgs {
foreground, foreground,
backgrounds, backgrounds,
@@ -340,7 +334,7 @@ impl AsyncWgpuPipeline for CompositeBackground {
} = args; } = args;
let foreground_size = foreground.size(); let foreground_size = foreground.size();
let output = executor.request_texture(UVec2::new(foreground_size.width, foreground_size.height)).await; let output = executor.request_texture(UVec2::new(foreground_size.width, foreground_size.height));
if zoom <= 0. { if zoom <= 0. {
return output; return output;
+48 -70
View File
@@ -1,8 +1,9 @@
//! Tile-based render caching for efficient viewport panning. //! Tile-based render caching for efficient viewport panning.
use core_types::gpoll::Interrupt;
use core_types::math::bbox::AxisAlignedBbox; use core_types::math::bbox::AxisAlignedBbox;
use core_types::transform::{Footprint, RenderQuality, Transform}; use core_types::transform::{Footprint, RenderQuality, Transform};
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl}; use core_types::{Ctx, DeriveCtx, ExtractAll};
use glam::{DAffine2, DVec2, IVec2, UVec2}; use glam::{DAffine2, DVec2, IVec2, UVec2};
use graph_craft::application_io::PlatformEditorApi; use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::value::{RenderOutput, RenderOutputType}; use graph_craft::document::value::{RenderOutput, RenderOutputType};
@@ -11,7 +12,6 @@ use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
use std::collections::HashSet; use std::collections::HashSet;
use std::hash::Hash; use std::hash::Hash;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use wgpu_executor::WgpuExecutor;
pub const TILE_SIZE: u32 = 256; pub const TILE_SIZE: u32 = 256;
pub const MAX_CACHE_MEMORY_BYTES: usize = 512 * 1024 * 1024; pub const MAX_CACHE_MEMORY_BYTES: usize = 512 * 1024 * 1024;
@@ -321,25 +321,23 @@ fn flood_fill(start: &TileCoord, tile_set: &HashSet<TileCoord>, visited: &mut Ha
} }
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
pub async fn render_output_cache<'a: 'n>( pub fn render_output_cache(
ctx: impl Ctx + ExtractAll + CloneVarArgs + ExtractRealTime + ExtractAnimationTime + ExtractPointerPosition + Sync, ctx: impl Ctx + ExtractAll + DeriveCtx,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>, #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi, #[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: std::sync::Arc<PlatformEditorApi>,
data: impl Node<Context<'static>, Output = RenderOutput> + Send + Sync, data: impl Node<Context<'_>, Output = RenderOutput>,
#[data] tile_cache: TileCache, #[data] tile_cache: TileCache,
) -> RenderOutput { ) -> Result<RenderOutput, Interrupt> {
let footprint = ctx.footprint(); let footprint = *ctx.footprint();
let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()) else { let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()) else {
log::warn!("render_output_cache: missing or invalid render params, falling back to direct render"); log::warn!("render_output_cache: missing or invalid render params, falling back to direct render");
let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint); return data.eval(&ctx.derived());
return data.eval(context.into_context()).await;
}; };
// Fall back to direct render for non-Vello or zero-size viewports // Fall back to direct render for non-Vello or zero-size viewports
let physical_resolution = footprint.resolution; let physical_resolution = footprint.resolution;
if !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || physical_resolution.x == 0 || physical_resolution.y == 0 { if !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || physical_resolution.x == 0 || physical_resolution.y == 0 {
let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint).with_vararg(Box::new(render_params.clone())); return data.eval(&ctx.derived());
return data.eval(context.into_context()).await;
} }
let zoom = footprint.scale_magnitudes().x; let zoom = footprint.scale_magnitudes().x;
@@ -375,8 +373,38 @@ pub async fn render_output_cache<'a: 'n>(
if missing_region.tiles.is_empty() { if missing_region.tiles.is_empty() {
continue; continue;
} }
let region = render_missing_region(missing_region, |ctx| data.eval(ctx), ctx.clone(), render_params, &footprint.transform, &device_origin_offset).await; let min_tile = missing_region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
new_regions.push(region); let max_tile = missing_region.tiles.iter().fold(IVec2::new(i32::MIN, i32::MIN), |acc, t| acc.max(IVec2::new(t.x, t.y)));
let tile_count = (max_tile - min_tile) + IVec2::ONE;
let region_pixel_size = (tile_count * TILE_SIZE as i32).as_uvec2();
let tile_global_offset = min_tile.as_dvec2() * TILE_SIZE as f64 + device_origin_offset;
let region_transform = DAffine2::from_translation(-tile_global_offset) * footprint.transform;
let region_footprint = Footprint {
transform: region_transform,
resolution: region_pixel_size,
quality: RenderQuality::Full,
};
let mut result = data.eval(&ctx.with_footprint(&region_footprint))?;
let RenderOutputType::Texture(texture) = result.data else {
unreachable!("render_output_cache: expected texture output from Vello render");
};
result.metadata.apply_transform(region_transform.inverse());
let memory_size = (region_pixel_size.x * region_pixel_size.y) as usize * BYTES_PER_PIXEL;
new_regions.push(CachedRegion {
texture,
texture_size: region_pixel_size,
tiles: missing_region.tiles.clone(),
metadata: result.metadata,
last_access: 0,
memory_size,
});
} }
tile_cache.store_regions(new_regions.clone()); tile_cache.store_regions(new_regions.clone());
@@ -385,68 +413,18 @@ pub async fn render_output_cache<'a: 'n>(
// If no regions, fall back to direct render // If no regions, fall back to direct render
if all_regions.is_empty() { if all_regions.is_empty() {
let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint).with_vararg(Box::new(render_params.clone())); return data.eval(&ctx.derived());
return data.eval(context.into_context()).await;
} }
let executor = executor.expect("GPU executor not available"); let executor = executor.expect("GPU executor not available");
let output_texture = executor.request_texture(physical_resolution).await; let output_texture = executor.request_texture(physical_resolution);
let combined_metadata = composite_cached_regions(&all_regions, &output_texture, &device_origin_offset, &footprint.transform, executor); let combined_metadata = composite_cached_regions(&all_regions, &output_texture, &device_origin_offset, &footprint.transform, &executor);
RenderOutput { Ok(RenderOutput {
data: RenderOutputType::Texture(output_texture), data: RenderOutputType::Texture(output_texture),
metadata: combined_metadata, metadata: combined_metadata,
} })
}
async fn render_missing_region<F, Fut>(
region: &RenderRegion,
render_fn: F,
ctx: impl Ctx + ExtractAll + CloneVarArgs,
render_params: &RenderParams,
viewport_transform: &DAffine2,
viewport_origin_offset: &DVec2,
) -> CachedRegion
where
F: Fn(Context<'static>) -> Fut,
Fut: std::future::Future<Output = RenderOutput>,
{
let min_tile = region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
let max_tile = region.tiles.iter().fold(IVec2::new(i32::MIN, i32::MIN), |acc, t| acc.max(IVec2::new(t.x, t.y)));
let tile_count = (max_tile - min_tile) + IVec2::ONE;
let region_pixel_size = (tile_count * TILE_SIZE as i32).as_uvec2();
let tile_global_offset = min_tile.as_dvec2() * TILE_SIZE as f64 + *viewport_origin_offset;
let region_transform = DAffine2::from_translation(-tile_global_offset) * *viewport_transform;
let region_footprint = Footprint {
transform: region_transform,
resolution: region_pixel_size,
quality: RenderQuality::Full,
};
let region_params = render_params.clone();
let region_ctx = OwnedContextImpl::from(ctx).with_footprint(region_footprint).with_vararg(Box::new(region_params)).into_context();
let mut result = render_fn(region_ctx).await;
let RenderOutputType::Texture(texture) = result.data else {
unreachable!("render_missing_region: expected texture output from Vello render");
};
let pixel_to_document = region_transform.inverse();
result.metadata.apply_transform(pixel_to_document);
let memory_size = (region_pixel_size.x * region_pixel_size.y) as usize * BYTES_PER_PIXEL;
CachedRegion {
texture,
texture_size: region_pixel_size,
tiles: region.tiles.clone(),
metadata: result.metadata,
last_access: 0,
memory_size,
}
} }
fn composite_cached_regions( fn composite_cached_regions(
+102 -30
View File
@@ -1,7 +1,7 @@
use core_types::gpoll::Interrupt;
use core_types::list::List; use core_types::list::List;
use core_types::transform::{Footprint, Transform}; use core_types::transform::{Footprint, Transform};
use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs}; use core_types::{Color, Context, Ctx, DeriveCtx, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots, WasmNotSend};
use core_types::{Color, Context, Ctx, ExtractFootprint, OwnedContextImpl, WasmNotSend};
use graph_craft::document::value::{RenderOutput, RenderOutputType}; use graph_craft::document::value::{RenderOutput, RenderOutputType};
use graphene_application_io::{ExportFormat, RenderConfig}; use graphene_application_io::{ExportFormat, RenderConfig};
use graphic_types::raster_types::{CPU, Raster}; use graphic_types::raster_types::{CPU, Raster};
@@ -9,7 +9,7 @@ use graphic_types::{Artboard, Graphic, Vector};
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput}; use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
use std::sync::Arc; use std::sync::Arc;
use vector_types::GradientStops; use vector_types::GradientStops;
use wgpu_executor::{RenderContext, WgpuExecutor}; use wgpu_executor::RenderContext;
#[derive(Clone, dyn_any::DynAny)] #[derive(Clone, dyn_any::DynAny)]
pub enum RenderIntermediateType { pub enum RenderIntermediateType {
@@ -23,8 +23,8 @@ pub struct RenderIntermediate {
} }
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send + Sync>( fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
ctx: impl Ctx + ExtractVarArgs + ExtractAll + CloneVarArgs, ctx: impl Ctx + ExtractVarArgs + DeriveCtx,
#[implementations( #[implementations(
Context -> List<Artboard>, Context -> List<Artboard>,
Context -> List<Graphic>, Context -> List<Graphic>,
@@ -34,21 +34,19 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
Context -> List<GradientStops>, Context -> List<GradientStops>,
Context -> List<String>, Context -> List<String>,
)] )]
data: impl Node<Context<'static>, Output = T>, data: impl Node<Context<'_>, Output = T>,
) -> RenderIntermediate { ) -> Result<RenderIntermediate, Interrupt> {
let data = data.eval(&ctx.derived())?;
let render_params = ctx let render_params = ctx
.vararg(0) .vararg(0)
.expect("Did not find var args") .expect("Did not find var args")
.downcast_ref::<RenderParams>() .downcast_ref::<RenderParams>()
.expect("Downcasting render params yielded invalid type"); .expect("Downcasting render params yielded invalid type");
let ctx = OwnedContextImpl::from(ctx.clone()).into_context();
let data = data.eval(ctx).await;
let footprint = Footprint::default(); let footprint = Footprint::default();
let mut metadata = RenderMetadata::default(); let mut metadata = RenderMetadata::default();
data.collect_metadata(&mut metadata, footprint, None); data.collect_metadata(&mut metadata, footprint, None);
match &render_params.render_output_type { Ok(match &render_params.render_output_type {
RenderOutputTypeRequest::Vello => { RenderOutputTypeRequest::Vello => {
let mut scene = vello::Scene::new(); let mut scene = vello::Scene::new();
@@ -70,13 +68,13 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
metadata, metadata,
} }
} }
} })
} }
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
async fn render<'a: 'n>( fn render(
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>, #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
data: RenderIntermediate, data: RenderIntermediate,
) -> RenderOutput { ) -> RenderOutput {
let footprint = ctx.footprint(); let footprint = ctx.footprint();
@@ -133,7 +131,6 @@ async fn render<'a: 'n>(
let texture = executor let texture = executor
.expect("GPU executor not available") .expect("GPU executor not available")
.render_vello_scene(&transformed_scene, footprint.resolution, context, None) .render_vello_scene(&transformed_scene, footprint.resolution, context, None)
.await
.expect("Failed to render Vello scene"); .expect("Failed to render Vello scene");
RenderOutputType::Texture(texture) RenderOutputType::Texture(texture)
} }
@@ -144,11 +141,13 @@ async fn render<'a: 'n>(
} }
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
async fn create_context<'a: 'n>( fn create_context(ctx: impl Ctx + ExtractVarArgs + DeriveCtx, data: impl Node<Context<'_>, Output = RenderOutput>) -> Result<RenderOutput, Interrupt> {
// Context injections are defined in the wrap_network_in_scope function let render_config = *ctx
render_config: RenderConfig, .vararg(0)
data: impl Node<Context<'static>, Output = RenderOutput>, .expect("Did not find var args")
) -> RenderOutput { .downcast_ref::<RenderConfig>()
.expect("Downcasting render config yielded invalid type");
let render_output_type = match render_config.export_format { let render_output_type = match render_config.export_format {
ExportFormat::Svg => RenderOutputTypeRequest::Svg, ExportFormat::Svg => RenderOutputTypeRequest::Svg,
ExportFormat::Raster => RenderOutputTypeRequest::Vello, ExportFormat::Raster => RenderOutputTypeRequest::Vello,
@@ -169,16 +168,89 @@ async fn create_context<'a: 'n>(
..Default::default() ..Default::default()
}; };
let ctx = OwnedContextImpl::default() let scope = ctx
.with_footprint(footprint) .scope()
.with_real_time(render_config.time.time) .with_real_time(Some(render_config.time.time))
.with_animation_time(render_config.time.animation_time.as_secs_f64()) .with_animation_time(Some(render_config.time.animation_time.as_secs_f64()))
.with_pointer_position(render_config.pointer) .with_pointer_position(Some(render_config.pointer));
.with_vararg(Box::new(render_params)) let varargs = VarArgLink {
.into_context(); args: VarArgSlots::Single(&render_params),
outer: None,
let mut result = data.eval(ctx).await; };
let scoped = ctx.with_scope(&scope);
let with_params = scoped.with_varargs(&varargs);
let mut result = data.eval(&with_params.with_footprint(&footprint))?;
result.metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale))); result.metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale)));
result Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::arena::Arena;
use core_types::context::{ContextImpl, EvalScope, VarArgsResult};
use core_types::gpoll::GPoll;
use core_types::node::Node;
use core_types::{ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
use graphene_application_io::TimingInformation;
struct ProbeNode;
impl<'a> Node<ContextImpl<'a>> for ProbeNode {
type Output = RenderOutput;
fn eval(&self, ctx: &ContextImpl<'a>) -> GPoll<RenderOutput> {
let render_params = ctx.vararg(0).unwrap().downcast_ref::<RenderParams>().expect("the vararg chain must start with RenderParams");
assert_eq!(render_params.scale, 2.0);
assert!(matches!(ctx.vararg(1), Err(VarArgsResult::IndexOutOfBounds)), "the RenderConfig must not leak downstream");
assert_eq!(ctx.footprint().transform, glam::DAffine2::from_scale(glam::DVec2::splat(2.0)) * Footprint::DEFAULT.transform);
assert_eq!(ctx.try_real_time(), Some(1.5));
assert_eq!(ctx.try_animation_time(), Some(2.0));
assert_eq!(ctx.try_pointer_position(), Some(glam::DVec2::new(3.0, 4.0)));
GPoll::Final(RenderOutput {
data: RenderOutputType::Buffer {
data: Vec::new(),
width: 0,
height: 0,
},
metadata: RenderMetadata::default(),
})
}
}
#[test]
fn create_context_builds_the_render_context_from_the_root_vararg() {
let arena = Arena::new(256).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let root = ContextImpl::root(&scope);
let render_config = RenderConfig {
scale: 2.0,
time: TimingInformation {
time: 1.5,
animation_time: std::time::Duration::from_secs(2),
},
pointer: glam::DVec2::new(3.0, 4.0),
..Default::default()
};
let varargs = VarArgLink {
args: VarArgSlots::Single(&render_config),
outer: None,
};
let ctx = root.with_varargs(&varargs);
let graph = CreateContextNode::new(ProbeNode);
let GPoll::Final(result) = <CreateContextNode<ProbeNode> as Node<ContextImpl>>::eval(&graph, &ctx) else {
panic!("create_context must complete synchronously");
};
assert_eq!(
result.data,
RenderOutputType::Buffer {
data: Vec::new(),
width: 0,
height: 0
}
);
}
} }
@@ -1,22 +1,22 @@
use core_types::gpoll::Interrupt;
use core_types::transform::{Footprint, Transform}; use core_types::transform::{Footprint, Transform};
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, OwnedContextImpl}; use core_types::{Ctx, DeriveCtx, ExtractAll};
use glam::{DAffine2, DVec2, UVec2, Vec2}; use glam::{DAffine2, DVec2, UVec2, Vec2};
use graph_craft::document::value::{RenderOutput, RenderOutputType}; use graph_craft::document::value::{RenderOutput, RenderOutputType};
use graphic_types::raster_types::Texture; use graphic_types::raster_types::Texture;
use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams}; use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
use vector_types::vector::style::RenderMode; use vector_types::vector::style::RenderMode;
use wgpu_executor::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache}; use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
pub async fn render_pixel_preview<'a: 'n>( pub fn render_pixel_preview(
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync, ctx: impl Ctx + ExtractAll + DeriveCtx,
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache, #[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
data: impl Node<Context<'static>, Output = RenderOutput> + Send + Sync, data: impl Node<Context<'_>, Output = RenderOutput>,
) -> RenderOutput { ) -> Result<RenderOutput, Interrupt> {
let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()).cloned() else { let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::<RenderParams>()).cloned() else {
log::error!("invalid render params for pixel preview"); log::error!("invalid render params for pixel preview");
let context = OwnedContextImpl::from(ctx).into_context(); return data.eval(&ctx.derived());
return data.eval(context).await;
}; };
let physical_scale = render_params.scale; let physical_scale = render_params.scale;
@@ -24,8 +24,7 @@ pub async fn render_pixel_preview<'a: 'n>(
let viewport_zoom = footprint.scale_magnitudes().x; let viewport_zoom = footprint.scale_magnitudes().x;
if render_params.render_mode != RenderMode::PixelPreview || !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || viewport_zoom <= 1. { if render_params.render_mode != RenderMode::PixelPreview || !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || viewport_zoom <= 1. {
let context = OwnedContextImpl::from(ctx).into_context(); return data.eval(&ctx.derived());
return data.eval(context).await;
} }
let physical_resolution = footprint.resolution; let physical_resolution = footprint.resolution;
@@ -51,33 +50,31 @@ pub async fn render_pixel_preview<'a: 'n>(
quality: footprint.quality, quality: footprint.quality,
}; };
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(upstream_footprint).with_vararg(Box::new(render_params)).into_context(); let scoped = ctx.push_vararg(&render_params);
let mut result = data.eval(new_ctx).await; let mut result = data.eval(&scoped.ctx().with_footprint(&upstream_footprint))?;
let RenderOutputType::Texture(ref source_texture) = result.data else { return result }; let RenderOutputType::Texture(ref source_texture) = result.data else { return Ok(result) };
let logical_transform = DAffine2::from_scale(DVec2::splat(1. / physical_scale)) * footprint.transform; let logical_transform = DAffine2::from_scale(DVec2::splat(1. / physical_scale)) * footprint.transform;
let transform = DAffine2::from_translation(-upstream_min) * logical_transform.inverse() * DAffine2::from_scale(logical_resolution); let transform = DAffine2::from_translation(-upstream_min) * logical_transform.inverse() * DAffine2::from_scale(logical_resolution);
let resampled = pipeline let resampled = pipeline.run::<PixelPreview>(&PixelPreviewArgs {
.run::<PixelPreview>(&PixelPreviewArgs { source: source_texture.as_ref(),
source: source_texture.as_ref(), transform: &transform,
transform: &transform, size: physical_resolution,
size: physical_resolution, });
})
.await;
result.data = RenderOutputType::Texture(resampled); result.data = RenderOutputType::Texture(resampled);
result.metadata.apply_transform(footprint.transform * DAffine2::from_translation(upstream_min)); result.metadata.apply_transform(footprint.transform * DAffine2::from_translation(upstream_min));
result Ok(result)
} }
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(category(""), inject_scope)]
async fn pixel_preview_pipeline<'a: 'n>( fn pixel_preview_pipeline(
_ctx: impl Ctx, _ctx: impl Ctx,
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>, #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
#[data] pipeline: WgpuPipelineCache, #[data] pipeline: WgpuPipelineCache,
) -> WgpuPipelineCache { ) -> WgpuPipelineCache {
if let Some(executor) = executor { if let Some(executor) = executor {
@@ -97,7 +94,7 @@ pub struct PixelPreviewArgs<'a> {
size: UVec2, size: UVec2,
} }
impl AsyncWgpuPipeline for PixelPreview { impl WgpuPipeline for PixelPreview {
type Args<'a> = PixelPreviewArgs<'a>; type Args<'a> = PixelPreviewArgs<'a>;
type Out = Texture; type Out = Texture;
@@ -169,11 +166,11 @@ impl AsyncWgpuPipeline for PixelPreview {
PixelPreview { pipeline, bind_group_layout } PixelPreview { pipeline, bind_group_layout }
} }
async fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out { fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
let context = &executor.context(); let context = &executor.context();
let &PixelPreviewArgs { source, transform, size } = args; let &PixelPreviewArgs { source, transform, size } = args;
let output = executor.request_texture(size).await; let output = executor.request_texture(size);
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default()); let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
let output_view = output.create_view(&wgpu::TextureViewDescriptor::default()); let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
+11
View File
@@ -0,0 +1,11 @@
pub use core_types::runtime::*;
use crate::platform_application_io::editor_api;
use core_types::Ctx;
use graph_craft::application_io::PlatformEditorApi;
use std::sync::Arc;
#[node_macro::node(category(""), inject_scope)]
pub fn runtime(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Arc<PlatformEditorApi>) -> RuntimeHandle {
editor_api.runtime.clone()
}
+307 -22
View File
@@ -1,4 +1,5 @@
use core_types::Context; use core_types::Context;
use core_types::gpoll::GPoll;
use core_types::list::List; use core_types::list::List;
use core_types::registry::types::{Fraction, Percentage, PixelSize}; use core_types::registry::types::{Fraction, Percentage, PixelSize};
use core_types::transform::Footprint; use core_types::transform::Footprint;
@@ -740,7 +741,7 @@ fn logical_not(
/// Evaluates either the "If True" or "If False" input branch based on whether the input condition is true or false. /// Evaluates either the "If True" or "If False" input branch based on whether the input condition is true or false.
#[node_macro::node(category("Math: Logic"))] #[node_macro::node(category("Math: Logic"))]
async fn switch<T, C: Send + 'n + Clone>( fn switch<T, C>(
#[implementations(Context)] ctx: C, #[implementations(Context)] ctx: C,
condition: bool, condition: bool,
#[expose] #[expose]
@@ -781,8 +782,8 @@ async fn switch<T, C: Send + 'n + Clone>(
Context -> List<GradientStops>, Context -> List<GradientStops>,
)] )]
if_false: impl Node<C, Output = T>, if_false: impl Node<C, Output = T>,
) -> T { ) -> GPoll<T> {
if condition { if_true.eval(ctx).await } else { if_false.eval(ctx).await } if condition { if_true.eval(ctx) } else { if_false.eval(ctx) }
} }
/// Constructs a bool value which may be set to true or false. /// Constructs a bool value which may be set to true or false.
@@ -988,74 +989,358 @@ fn normalize(_: impl Ctx, vector: DVec2) -> DVec2 {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;
use core_types::Node;
use core_types::generic::FnNode;
#[test] #[test]
pub fn dot_product_function() { pub fn dot_product_function() {
let vector_a = DVec2::new(1., 2.); let vector_a = DVec2::new(1., 2.);
let vector_b = DVec2::new(3., 4.); let vector_b = DVec2::new(3., 4.);
assert_eq!(dot_product((), vector_a, vector_b, false), 11.); assert_eq!(dot_product(&(), vector_a, vector_b, false), 11.);
} }
#[test] #[test]
pub fn length_function() { pub fn length_function() {
let vector = DVec2::new(3., 4.); let vector = DVec2::new(3., 4.);
assert_eq!(length((), vector), 5.); assert_eq!(length(&(), vector), 5.);
} }
#[test] #[test]
fn test_basic_expression() { fn test_basic_expression() {
let result = math((), 0., "2 + 2".to_string(), 0.); let result = math(&(), 0., "2 + 2".to_string(), 0.);
assert_eq!(result, 4.); assert_eq!(result, 4.);
} }
#[test] #[test]
fn test_complex_expression() { fn test_complex_expression() {
let result = math((), 0., "(5 * 3) + (10 / 2)".to_string(), 0.); let result = math(&(), 0., "(5 * 3) + (10 / 2)".to_string(), 0.);
assert_eq!(result, 20.); assert_eq!(result, 20.);
} }
#[test] #[test]
fn test_default_expression() { fn test_default_expression() {
let result = math((), 0., "0".to_string(), 0.); let result = math(&(), 0., "0".to_string(), 0.);
assert_eq!(result, 0.); assert_eq!(result, 0.);
} }
#[test] #[test]
fn test_invalid_expression() { fn test_invalid_expression() {
let result = math((), 0., "invalid".to_string(), 0.); let result = math(&(), 0., "invalid".to_string(), 0.);
assert_eq!(result, 0.); assert_eq!(result, 0.);
} }
#[test]
pub fn foo() {
let fnn = FnNode::new(|(a, b)| (b, a));
assert_eq!(fnn.eval((1u32, 2u32)), (2, 1));
}
#[test] #[test]
pub fn add_vectors() { pub fn add_vectors() {
assert_eq!(super::add((), DVec2::ONE, DVec2::ONE), DVec2::ONE * 2.); assert_eq!(super::add(&(), DVec2::ONE, DVec2::ONE), DVec2::ONE * 2.);
} }
#[test] #[test]
pub fn subtract_f64() { pub fn subtract_f64() {
assert_eq!(super::subtract((), 5_f64, 3_f64), 2.); assert_eq!(super::subtract(&(), 5_f64, 3_f64), 2.);
} }
#[test] #[test]
pub fn divide_vectors() { pub fn divide_vectors() {
assert_eq!(super::divide((), DVec2::ONE, 2_f64), DVec2::ONE / 2.); assert_eq!(super::divide(&(), DVec2::ONE, 2_f64), DVec2::ONE / 2.);
} }
#[test] #[test]
pub fn modulo_positive() { pub fn modulo_positive() {
assert_eq!(super::modulo((), -5_f64, 2_f64, true), 1_f64); assert_eq!(super::modulo(&(), -5_f64, 2_f64, true), 1_f64);
} }
#[test] #[test]
pub fn modulo_negative() { pub fn modulo_negative() {
assert_eq!(super::modulo((), -5_f64, 2_f64, false), -1_f64); assert_eq!(super::modulo(&(), -5_f64, 2_f64, false), -1_f64);
}
}
#[cfg(test)]
mod graphene_test {
use super::*;
use core_types::arena::Arena;
use core_types::context::{ContextImpl, EvalScope, ExtractIndex};
use core_types::gpoll::{Finality, GPoll};
use core_types::node::{BatchStatus, Node};
use core_types::record::{Layout, RecordLift, RecordValue, stack};
use core_types::registry::{ErasedRecordNode, construct};
use core_types::value::record_value_edge;
use std::mem::MaybeUninit;
struct SourceNode<T>(T);
impl<T: Clone, Input> Node<Input> for SourceNode<T> {
type Output = T;
fn eval(&self, _input: &Input) -> GPoll<T> {
GPoll::Final(self.0.clone())
}
}
struct IndexNode;
impl<Input: ExtractIndex> Node<Input> for IndexNode {
type Output = f64;
fn eval(&self, input: &Input) -> GPoll<f64> {
GPoll::Final(input.innermost_index() as f64)
}
}
fn scope_fixture(arena: &Arena) -> EvalScope<'_> {
EvalScope::new(None, None, None, &[], arena)
}
fn reserve_for(layouts: &[&Layout]) {
stack::reserve(layouts.iter().map(|layout| layout.frame_bytes()).sum::<usize>().max(1 << 12));
}
/// Lifts a plain-element test source onto a record wire, returned beside its
/// element-only layout for the generated node's constructor.
fn lifted<T, N>(node: N) -> (RecordLift<T, N>, Layout)
where
T: Clone + Send + Sync + 'static,
N: for<'c> Node<ContextImpl<'c>, Output = T>,
{
let lift = RecordLift::<T, _>::new(node);
let layout = Node::<ContextImpl>::layout(&lift).clone();
(lift, layout)
}
fn element<T: Copy>(layout: &Layout, value: &RecordValue<'_>) -> T {
unsafe { layout.rec(value).element::<T>() }
}
#[test]
fn generated_add_evaluates_through_the_node_path() {
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let (a, la) = lifted(SourceNode(1.0f64));
let (b, lb) = lifted(SourceNode(2.0f64));
let graph = AddNode::<_, _, f64, f64>::new(a, b, &la, &lb);
let out = Node::<ContextImpl>::layout(&graph).clone();
reserve_for(&[&la, &lb, &out]);
let GPoll::Final(value) = Node::eval(&graph, &ctx) else {
panic!("expected a final record");
};
assert_eq!(element::<f64>(&out, &value), 3.0);
}
#[test]
fn generated_add_batches_through_the_erased_edge() {
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let (index, li) = lifted(IndexNode);
let (src, ls) = lifted(SourceNode(10.0f64));
let node = AddNode::<_, _, f64, f64>::new(index, src, &li, &ls);
let out = Node::<ContextImpl>::layout(&node).clone();
reserve_for(&[&li, &ls, &out]);
let erased: Box<ErasedRecordNode> = Box::new(node);
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = erased.eval_batch(&ctx, 2..6, Some(&mut scratch));
let BatchStatus::Filled(batch, finality) = status else {
panic!("expected filled, got {status:?}");
};
let mut got = Vec::new();
batch.for_each(|_, lane| got.push(unsafe { lane.element::<f64>() }));
assert_eq!(got, vec![12.0, 13.0, 14.0, 15.0]);
assert_eq!(finality, Finality::AllFinal);
}
#[test]
fn generated_wire_constructor_resolves_and_wires() {
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let entries = super::_logical_or_mod::logical_or_entries();
let wired = construct(&entries[0], vec![record_value_edge(true), record_value_edge(false)]).unwrap();
let layout = wired.layout().unwrap().clone();
let edge = wired.downcast_record::<bool>().unwrap();
reserve_for(&[&layout]);
let GPoll::Final(value) = edge.eval(&ctx) else {
panic!("expected a final record");
};
assert!(element::<bool>(&layout, &value));
}
#[test]
fn ctor_registration_populates_the_node_registry() {
let registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
let rows = registry
.iter()
.find_map(|(id, rows)| id.as_str().ends_with("::AddNode").then_some(rows))
.expect("AddNode rows registered at startup");
assert_eq!(rows.len(), 6);
}
#[test]
fn generic_add_registers_one_entry_per_implementation() {
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let entries = super::_add_mod::add_entries();
assert_eq!(entries.len(), 6);
assert_eq!(entries[0].io.inputs, vec![core_types::registry::record_edge_type::<f64>(), core_types::registry::record_edge_type::<f64>()]);
assert_eq!(entries[0].io.return_value, core_types::registry::record_type::<f64>());
assert_eq!(entries[3].io.inputs, vec![core_types::registry::record_edge_type::<DVec2>(), core_types::registry::record_edge_type::<DVec2>()]);
assert_eq!(entries[3].io.return_value, core_types::registry::record_type::<DVec2>());
let wired = construct(&entries[0], vec![record_value_edge(1.5f64), record_value_edge(2.5f64)]).unwrap();
let layout = wired.layout().unwrap().clone();
let edge = wired.downcast_record::<f64>().unwrap();
reserve_for(&[&layout]);
let GPoll::Final(value) = edge.eval(&ctx) else {
panic!("expected a final record");
};
assert_eq!(element::<f64>(&layout, &value), 4.0);
}
#[test]
fn converted_switch_evaluates_only_the_taken_branch() {
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
struct CountingSource(Arc<AtomicU32>, f64);
impl<Input> Node<Input> for CountingSource {
type Output = f64;
fn eval(&self, _input: &Input) -> GPoll<f64> {
self.0.fetch_add(1, Ordering::Relaxed);
GPoll::Final(self.1)
}
}
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let taken = Arc::new(AtomicU32::new(0));
let untaken = Arc::new(AtomicU32::new(0));
let (cond, lc) = lifted(SourceNode(true));
let (if_true, lt) = lifted(CountingSource(taken.clone(), 1.0));
let (if_false, lf) = lifted(CountingSource(untaken.clone(), 2.0));
let graph = SwitchNode::<_, _, _, f64>::new(cond, if_true, if_false, &lc, &lt, &lf);
let out = Node::<ContextImpl>::layout(&graph).clone();
reserve_for(&[&lc, &lt, &lf, &out]);
let GPoll::Final(value) = Node::eval(&graph, &ctx) else {
panic!("expected a final record");
};
assert_eq!(element::<f64>(&out, &value), 1.0);
assert_eq!(taken.load(Ordering::Relaxed), 1);
assert_eq!(untaken.load(Ordering::Relaxed), 0);
}
#[test]
fn converted_switch_passes_branch_status_through() {
struct PendingSource;
impl<Input> Node<Input> for PendingSource {
type Output = f64;
fn eval(&self, _input: &Input) -> GPoll<f64> {
GPoll::Pending
}
}
struct PartialSource;
impl<Input> Node<Input> for PartialSource {
type Output = f64;
fn eval(&self, _input: &Input) -> GPoll<f64> {
GPoll::Partial(7.0)
}
}
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let (c1, lc1) = lifted(SourceNode(true));
let (p1, lp1) = lifted(PendingSource);
let (pa1, lpa1) = lifted(PartialSource);
let pending = SwitchNode::<_, _, _, f64>::new(c1, p1, pa1, &lc1, &lp1, &lpa1);
let (c2, lc2) = lifted(SourceNode(false));
let (p2, lp2) = lifted(PendingSource);
let (pa2, lpa2) = lifted(PartialSource);
let partial = SwitchNode::<_, _, _, f64>::new(c2, p2, pa2, &lc2, &lp2, &lpa2);
let out = Node::<ContextImpl>::layout(&partial).clone();
reserve_for(&[&lc1, &lp1, &lpa1, &lc2, &lp2, &lpa2, &out]);
assert!(matches!(Node::eval(&pending, &ctx), GPoll::Pending));
let GPoll::Partial(value) = Node::eval(&partial, &ctx) else {
panic!("expected a partial record");
};
assert_eq!(element::<f64>(&out, &value), 7.0);
}
#[test]
fn converted_switch_merges_condition_status_into_the_branch_result() {
struct PartialCondition;
impl<Input> Node<Input> for PartialCondition {
type Output = bool;
fn eval(&self, _input: &Input) -> GPoll<bool> {
GPoll::Partial(true)
}
}
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let (cond, lc) = lifted(PartialCondition);
let (if_true, lt) = lifted(SourceNode(1.0f64));
let (if_false, lf) = lifted(SourceNode(2.0f64));
let graph = SwitchNode::<_, _, _, f64>::new(cond, if_true, if_false, &lc, &lt, &lf);
let out = Node::<ContextImpl>::layout(&graph).clone();
reserve_for(&[&lc, &lt, &lf, &out]);
let GPoll::Partial(value) = Node::eval(&graph, &ctx) else {
panic!("expected a partial record");
};
assert_eq!(element::<f64>(&out, &value), 1.0);
}
#[test]
fn generated_eval_computes_on_stand_in_and_traces_fallback() {
struct FallbackNode;
impl<Input> Node<Input> for FallbackNode {
type Output = f64;
fn eval(&self, _input: &Input) -> GPoll<f64> {
GPoll::fallback(0.0, "upstream failed")
}
}
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let (fallback, lfb) = lifted(FallbackNode);
let (src, ls) = lifted(SourceNode(5.0f64));
let graph = AddNode::<_, _, f64, f64>::new(fallback, src, &lfb, &ls);
let out = Node::<ContextImpl>::layout(&graph).clone();
reserve_for(&[&lfb, &ls, &out]);
let GPoll::Fallback(boxed) = Node::eval(&graph, &ctx) else {
panic!("fallback must propagate with the computed stand-in");
};
assert_eq!(element::<f64>(&out, &boxed.0), 5.0);
assert!(boxed.1.kind == "upstream failed");
assert_eq!(boxed.1.trace, vec![0]);
} }
} }
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more