Compare commits

...
Author SHA1 Message Date
Dennis Kobert c3fdc97f81 Convert create_context to a sync derivation kernel over the bare-root contract 2026-07-27 11:40:16 +00:00
Dennis Kobert 3d17fa0f0c Make the arena unwind safe and the slot locks poison tolerant 2026-07-27 11:40:16 +00:00
Dennis Kobert 9e83632647 Make the GPU render and dispatch pipelines synchronous 2026-07-27 10:47:44 +00:00
Dennis Kobert 6392c02dee Add the sync-prologue async source form 2026-07-27 10:47:44 +00:00
Dennis Kobert 470ffdab43 Add vararg slot cloning and snapshot vararg capture 2026-07-27 10:47:44 +00:00
Dennis Kobert 28d9e3cbe3 Convert the remaining nodes and mark genuine async sources 2026-07-26 22:58:40 +00:00
Dennis Kobert 28d37d30d0 Store the wgpu executor as an Arc and restore the upload texture node 2026-07-26 22:58:40 +00:00
Dennis Kobert cf66f8396b Emit the async source tier from the node macro 2026-07-26 22:58:40 +00:00
Dennis Kobert be5c78421a Add the async source runtime vocabulary and context snapshot 2026-07-26 22:58:40 +00:00
Dennis Kobert f0f7d6a5d7 Start adapting nodes to new version 2026-07-26 20:59:12 +00:00
Dennis Kobert 44277c9636 Update node macro to new syntax 2026-07-26 20:58:11 +00:00
Dennis Kobert 99f94503c3 Reshape ContextImpl into the borrowed graphene context 2026-07-25 19:33:41 +00:00
Dennis Kobert 925075337b Add the generation-scoped arena and the FrameTable frame memo store 2026-07-25 17:05:40 +00:00
Dennis Kobert df70222d61 Add the GNode trait with the spec-loop batch default; give InjectIndex its method 2026-07-25 17:05:01 +00:00
Dennis Kobert 1f9e0cc37b Add the GPoll evaluation vocabulary and an inert Type::Ref variant 2026-07-25 17:03:32 +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
83 changed files with 6106 additions and 1946 deletions

No files matched your search

Generated
+6 -4
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",
+1 -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};
+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
@@ -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 }
+5 -14
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;
@@ -65,21 +67,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 {
@@ -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);
} }
}, },
@@ -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()),
@@ -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::Ref(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);
+5 -9
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};
@@ -660,19 +660,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,
graphene_std::raster::Image {
width: image.width, width: image.width,
height: image.height, height: image.height,
data: image.data.iter().map(|&c| SRGBA8::from(c)).collect(), pixels: image.data.iter().flat_map(rgba8_bytes).collect::<Vec<u8>>().into(),
base64_string: image.base64_string,
},
)
}) })
.collect(); .collect();
responses.add(FrontendMessage::UpdateImageData { image_data }); responses.add(FrontendMessage::UpdateImageData { image_data });
+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;
}
+67 -808
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() {
}
.into(),
);
messages.push(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>
messages.push(BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into());
wrapper.dispatch(Message::Batched { messages: messages.into() }); wrapper.dispatch(Message::Batched { messages: messages.into() });
});
} }
}
#[cfg(target_family = "wasm")]
wrapper.animation_frame(js_sys::Date::now() as u64);
});
// 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::*;
+46 -16
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,6 +51,10 @@ 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();
// Node graph panics can only originate here when the node graph runs inside this wasm module
#[cfg(feature = "editor")]
{
let backtrace = Error::new("stack").stack().to_string(); let backtrace = Error::new("stack").stack().to_string();
if backtrace.contains("DynAnyNode") { if backtrace.contains("DynAnyNode") {
log::error!("Node graph evaluation panicked {info}"); log::error!("Node graph evaluation panicked {info}");
@@ -64,14 +76,15 @@ pub fn panic_hook(info: &panic::PanicHookInfo) {
/text>"# /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. // 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(); .to_string();
wrapper.send_frontend_message_to_js_rust_proxy(FrontendMessage::UpdateDocumentArtwork { svg: error }); wrapper.send_frontend_message_to_js(FrontendMessage::UpdateDocumentArtwork { svg: error });
}); });
} }
return; return;
} else {
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
} }
}
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
log::error!("{info}"); log::error!("{info}");
@@ -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;
} }
};
wrapper(callback); 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:?}"),
},
}
}
});
} }
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<'_> {
@@ -309,6 +309,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::Ref(_) => None,
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
@@ -569,6 +570,7 @@ impl TaggedValue {
match ty { match ty {
Type::Generic(_) => None, Type::Generic(_) => None,
Type::Ref(_) => 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;
@@ -262,7 +262,7 @@ impl BorrowTree {
/// This ensures that no borrowed data can escape the node graph. /// 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> pub async fn eval_tagged_value<I>(&self, id: NodeId, input: I) -> Result<TaggedValue, String>
where where
I: StaticType + 'static + Send + Sync, I: StaticType + 'static + Send + Sync + std::panic::UnwindSafe,
{ {
let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?; let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?;
let output = node.eval(Box::new(input)); let output = node.eval(Box::new(input));
+2 -2
View File
@@ -84,12 +84,12 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
..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 { 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
extract: ContextFeatures::INDEX, extract: ContextFeatures::INDEX | ContextFeatures::VARARGS,
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
}, },
..Default::default() ..Default::default()
@@ -0,0 +1,291 @@
use std::any::Any;
use std::mem::MaybeUninit;
use std::ops::Add;
use core_types::arena::{Arena, ArenaCell};
use core_types::context::{ContextImpl, Ctx, EvalScope, ExtractArena, InjectIndex};
use core_types::gnode::{BatchStatus, GNode, StatusCell};
use core_types::gpoll::{ErrorKind, Finality, GPoll, Interrupt};
fn add<A: Add<B>, B, C: Ctx>(_ctx: &C, augend: A, addend: B) -> <A as Add<B>>::Output {
augend + addend
}
struct AddNode<Node0, Node1> {
augend: Node0,
addend: Node1,
}
impl<Node0, Node1> AddNode<Node0, Node1> {
fn new(augend: Node0, addend: Node1) -> Self {
Self { augend, addend }
}
}
impl<A, B, Input, Node0, Node1> GNode<Input> for AddNode<Node0, Node1>
where
A: Add<B>,
Input: Ctx,
Node0: GNode<Input, Output = A>,
Node1: GNode<Input, Output = B>,
{
type Output = <A as Add<B>>::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
let cell = StatusCell::new();
let augend = match cell.eval_input(0, &self.augend, input) {
Ok(value) => value,
Err(interrupt) => return interrupt.into(),
};
let addend = match cell.eval_input(1, &self.addend, input) {
Ok(value) => value,
Err(interrupt) => return interrupt.into(),
};
cell.finish(add(input, augend, addend))
}
}
struct ValueNode<T>(T);
impl<T: Clone, Input> GNode<Input> for ValueNode<T> {
type Output = T;
fn eval(&self, _input: &Input) -> GPoll<T> {
GPoll::Final(self.0.clone())
}
}
struct ReadIndexNode;
impl<Input: InjectIndex + Copy + ExtractIndexValue> GNode<Input> for ReadIndexNode {
type Output = f64;
fn eval(&self, input: &Input) -> GPoll<f64> {
GPoll::Final(input.index_value() as f64)
}
}
trait ExtractIndexValue {
fn index_value(&self) -> u64;
}
impl ExtractIndexValue for ContextImpl<'_> {
fn index_value(&self) -> u64 {
self.index_head().index
}
}
fn string_length<C: Ctx>(_ctx: &C, value: &String) -> f64 {
value.len() as f64
}
struct LendStringNode {
value: String,
cell: ArenaCell<String>,
}
impl LendStringNode {
fn new(value: String) -> Self {
Self {
value,
cell: ArenaCell::new(),
}
}
}
impl<'e, Input> GNode<Input> for LendStringNode
where
Input: Ctx + ExtractArena<ArenaRef = &'e Arena>,
{
type Output = &'e String;
fn eval(&self, input: &Input) -> GPoll<&'e String> {
let arena = input.arena();
if let Some(value) = self.cell.load(arena) {
return GPoll::Final(value);
}
match arena.alloc(self.value.clone()) {
Some((value, weak)) => {
self.cell.store(weak);
GPoll::Final(value)
}
None => GPoll::arena_exhausted(),
}
}
}
struct StringLengthNode<Node0> {
value: Node0,
}
impl<Node0> StringLengthNode<Node0> {
fn new(value: Node0) -> Self {
Self { value }
}
}
impl<'e, Input, Node0> GNode<Input> for StringLengthNode<Node0>
where
Input: Ctx,
Node0: GNode<Input, Output = &'e String>,
{
type Output = f64;
fn eval(&self, input: &Input) -> GPoll<f64> {
let cell = StatusCell::new();
let value = match cell.eval_input(0, &self.value, input) {
Ok(value) => value,
Err(interrupt) => return interrupt.into(),
};
cell.finish(string_length(input, value))
}
}
type ErasedGNode<T> = dyn for<'c> GNode<ContextImpl<'c>, Output = T>;
type ErasedLendEdge = dyn for<'c> GNode<ContextImpl<'c>, Output = &'c String>;
fn string_length_constructor(args: Vec<Box<dyn Any>>) -> Result<Box<ErasedGNode<f64>>, &'static str> {
let mut args = args.into_iter();
let value = *args.next().ok_or("arity")?.downcast::<Box<ErasedLendEdge>>().map_err(|_| "type")?;
Ok(Box::new(StringLengthNode::new(value)))
}
fn add_constructor_f64(args: Vec<Box<dyn Any>>) -> Result<Box<ErasedGNode<f64>>, &'static str> {
let mut args = args.into_iter();
let augend = *args.next().ok_or("arity")?.downcast::<Box<ErasedGNode<f64>>>().map_err(|_| "type")?;
let addend = *args.next().ok_or("arity")?.downcast::<Box<ErasedGNode<f64>>>().map_err(|_| "type")?;
Ok(Box::new(AddNode::new(augend, addend)))
}
fn scope_fixture<'a>(generations: &'a [(u64, u64)], arena: &'a Arena) -> EvalScope<'a> {
EvalScope::new(Some(0.5), None, None, generations, arena)
}
#[test]
fn hand_expansion_evaluates_through_typed_erased_edges() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let augend: Box<dyn Any> = Box::new(Box::new(ValueNode(1.0f64)) as Box<ErasedGNode<f64>>);
let addend: Box<dyn Any> = Box::new(Box::new(ValueNode(2.0f64)) as Box<ErasedGNode<f64>>);
let wired = add_constructor_f64(vec![augend, addend]).unwrap();
assert_eq!(wired.eval(&ctx), GPoll::Final(3.0));
}
#[test]
fn wiring_rejects_type_and_arity_mismatches() {
let augend: Box<dyn Any> = Box::new(Box::new(ValueNode(1.0f64)) as Box<ErasedGNode<f64>>);
let addend: Box<dyn Any> = Box::new(Box::new(ValueNode(2u32)) as Box<ErasedGNode<u32>>);
assert_eq!(add_constructor_f64(vec![augend, addend]).map(|_| ()), Err("type"));
let augend: Box<dyn Any> = Box::new(Box::new(ValueNode(1.0f64)) as Box<ErasedGNode<f64>>);
assert_eq!(add_constructor_f64(vec![augend]).map(|_| ()), Err("arity"));
}
#[test]
fn spec_loop_batches_through_the_erased_edge() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let graph: Box<ErasedGNode<f64>> = Box::new(AddNode::new(ReadIndexNode, ValueNode(10.0f64)));
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = graph.eval_batch(&ctx, 2..6, Some(&mut scratch));
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes, &[12.0, 13.0, 14.0, 15.0]);
assert_eq!(finality, Finality::AllFinal);
}
#[test]
fn lending_kernel_clones_once_per_generation_and_lends_after() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let node = LendStringNode::new("lend me".to_string());
let GPoll::Final(first) = node.eval(&ctx) else {
panic!("first eval must clone into the arena and lend");
};
let GPoll::Final(second) = node.eval(&ctx) else {
panic!("second eval must hit the cell");
};
assert_eq!(first, "lend me");
assert!(std::ptr::eq(first, second));
}
#[test]
fn exhausted_arena_reports_the_operational_error() {
let arena = Arena::new(0);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let node = LendStringNode::new("too big".to_string());
let GPoll::Error(error) = node.eval(&ctx) else {
panic!("exhaustion must surface as an operational error");
};
assert_eq!(error.kind, ErrorKind::ArenaExhausted);
}
#[test]
fn lending_edges_erase_and_wire_like_owned_edges() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let value: Box<dyn Any> = Box::new(Box::new(LendStringNode::new("across the boundary".to_string())) as Box<ErasedLendEdge>);
let wired = string_length_constructor(vec![value]).unwrap();
assert_eq!(wired.eval(&ctx), GPoll::Final(19.0));
}
#[test]
fn spec_loop_batches_through_the_erased_lending_edge() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let graph: Box<ErasedLendEdge> = Box::new(LendStringNode::new("batched".to_string()));
let mut scratch = [const { MaybeUninit::uninit() }; 3];
let status = graph.eval_batch(&ctx, 0..3, Some(&mut scratch));
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes.len(), 3);
assert!(lanes.iter().all(|lane| std::ptr::eq(*lane, lanes[0])));
assert_eq!(*lanes[0], "batched");
assert_eq!(finality, Finality::AllFinal);
}
#[test]
fn fallback_input_records_partiality_invisibly() {
struct FallbackNode;
impl<Input> GNode<Input> for FallbackNode {
type Output = f64;
fn eval(&self, _input: &Input) -> GPoll<f64> {
GPoll::fallback(0.0, "upstream failed")
}
}
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let graph = AddNode::new(FallbackNode, ValueNode(5.0f64));
let GPoll::Fallback(boxed) = graph.eval(&ctx) else {
panic!("fallback must propagate with the computed stand-in");
};
assert_eq!(boxed.0, 5.0);
assert!(boxed.1.kind == "upstream failed");
assert_eq!(boxed.1.trace, vec![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 }
+10 -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,
@@ -0,0 +1,260 @@
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
pub struct Arena {
generation: AtomicU64,
offset: AtomicUsize,
buf: Box<[UnsafeCell<MaybeUninit<u8>>]>,
drops: Mutex<Vec<DropEntry>>,
}
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.
unsafe impl Sync for Arena {}
unsafe impl Send for Arena {}
impl std::panic::UnwindSafe for Arena {}
impl std::panic::RefUnwindSafe for Arena {}
impl Arena {
pub fn new(capacity: usize) -> Self {
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
Self {
// Starts at 1 so the null handle word (0) can never upgrade.
generation: AtomicU64::new(1),
offset: AtomicUsize::new(0),
buf,
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>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
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 }, ArenaWeak::new(self.generation(), offset)))
}
pub fn alloc_slice_copy<T: Copy>(&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>(&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) })
}
pub fn reset(&mut self) {
let base = self.base();
for entry in self.drops.get_mut().unwrap().drain(..) {
// 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;
self.generation.fetch_add(1, Ordering::Release);
}
}
impl Drop for Arena {
fn drop(&mut self) {
self.reset();
}
}
pub struct ArenaWeak<T> {
word: u64,
_marker: PhantomData<*const 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 };
fn new(generation: u64, offset: usize) -> Self {
debug_assert!(offset < u32::MAX as usize);
Self {
word: ((generation & 0xFFFF_FFFF) << 32) | offset as u64,
_marker: PhantomData,
}
}
pub fn upgrade(self, arena: &Arena) -> Option<&T> {
let generation = self.word >> 32;
if generation != arena.generation() & 0xFFFF_FFFF {
return None;
}
let offset = (self.word & 0xFFFF_FFFF) 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> 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::atomic::AtomicU32;
#[test]
fn alloc_upgrade_reset_miss() {
let mut arena = Arena::new(1024);
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 mut arena = Arena::new(64 + align_of::<u32>() - 1);
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() {
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);
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 drop_glue_runs_on_reset() {
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);
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);
}
}
+828 -58
View File
@@ -1,8 +1,8 @@
use crate::arena::Arena;
use crate::transform::Footprint; use crate::transform::Footprint;
use glam::DVec2; use glam::DVec2;
pub use no_std_types::context::{ArcCtx, Ctx}; pub use no_std_types::context::{ArcCtx, Ctx};
use std::any::Any; use std::any::Any;
use std::borrow::Borrow;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::panic::Location; use std::panic::Location;
use std::sync::Arc; use std::sync::Arc;
@@ -36,6 +36,9 @@ pub trait ExtractPosition {
} }
pub trait ExtractIndex { pub trait ExtractIndex {
fn try_index(&self) -> Option<impl Iterator<Item = usize>>; fn try_index(&self) -> Option<impl Iterator<Item = usize>>;
fn innermost_index(&self) -> u64 {
self.try_index().and_then(|mut indices| indices.next()).unwrap_or(0) as u64
}
} }
pub trait ExtractVarArgs { pub trait ExtractVarArgs {
// TODO: Consider returning a slice or something like that // TODO: Consider returning a slice or something like that
@@ -62,7 +65,9 @@ pub trait InjectRealTime {}
pub trait InjectAnimationTime {} pub trait InjectAnimationTime {}
pub trait InjectPointerPosition {} pub trait InjectPointerPosition {}
pub trait InjectPosition {} pub trait InjectPosition {}
pub trait InjectIndex {} pub trait InjectIndex {
fn set_index(&mut self, index: u64);
}
pub trait InjectVarArgs {} pub trait InjectVarArgs {}
// ================ // ================
@@ -101,7 +106,6 @@ impl<T: Ctx> InjectRealTime for T {}
impl<T: Ctx> InjectAnimationTime for T {} impl<T: Ctx> InjectAnimationTime for T {}
impl<T: Ctx> InjectPointerPosition for T {} impl<T: Ctx> InjectPointerPosition for T {}
impl<T: Ctx> InjectPosition for T {} impl<T: Ctx> InjectPosition for T {}
impl<T: Ctx> InjectIndex for T {}
impl<T: Ctx> InjectVarArgs for T {} impl<T: Ctx> InjectVarArgs for T {}
// ============= // =============
@@ -383,48 +387,6 @@ impl ExtractFootprint for () {
} }
} }
// =====================================
// EXTRACT TRAIT IMPLS FOR `ContextImpl`
// =====================================
impl Ctx for ContextImpl<'_> {}
impl ExtractFootprint for ContextImpl<'_> {
fn try_footprint(&self) -> Option<&Footprint> {
self.footprint
}
}
impl ExtractRealTime for ContextImpl<'_> {
fn try_real_time(&self) -> Option<f64> {
self.real_time
}
}
impl ExtractPosition for ContextImpl<'_> {
fn try_position(&self) -> Option<impl Iterator<Item = DVec2>> {
self.position.clone().map(|x| x.into_iter())
}
}
impl ExtractIndex for ContextImpl<'_> {
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
self.index.clone().map(|x| x.into_iter())
}
}
impl ExtractVarArgs for ContextImpl<'_> {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
let Some(inner) = self.varargs else { return Err(VarArgsResult::NoVarArgs) };
inner.get(index).ok_or(VarArgsResult::IndexOutOfBounds).copied()
}
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
let Some(inner) = self.varargs else { return Err(VarArgsResult::NoVarArgs) };
Ok(inner.len())
}
fn hash_varargs(&self, _hasher: &mut dyn Hasher) {
todo!()
}
}
// ========================================== // ==========================================
// EXTRACT TRAIT IMPLS FOR `OwnedContextImpl` // EXTRACT TRAIT IMPLS FOR `OwnedContextImpl`
// ========================================== // ==========================================
@@ -507,7 +469,8 @@ impl CloneVarArgs for Arc<OwnedContextImpl> {
// TYPES `Context` AND `OwnedContextImpl` // TYPES `Context` AND `OwnedContextImpl`
// ====================================== // ======================================
pub type Context<'a> = Option<Arc<OwnedContextImpl>>; pub type OwnedContext = Option<Arc<OwnedContextImpl>>;
pub type Context<'a> = ContextImpl<'a>;
type DynRef<'a> = &'a (dyn Any + Send + Sync); type DynRef<'a> = &'a (dyn Any + Send + Sync);
type DynBox = Box<dyn AnyHash + Send + Sync>; type DynBox = Box<dyn AnyHash + Send + Sync>;
@@ -629,6 +592,38 @@ impl Hash for Box<dyn AnyHash + Send + Sync> {
pub trait AnyHash: DynHash + Any {} pub trait AnyHash: DynHash + Any {}
impl<T: DynHash + Any> AnyHash for T {} impl<T: DynHash + Any> AnyHash for T {}
pub trait VarArg: AnyHash {
fn clone_slot(&self) -> OwnedSlot;
}
impl<T: AnyHash + Clone + Send + Sync> VarArg for T {
fn clone_slot(&self) -> OwnedSlot {
OwnedSlot(Box::new(self.clone()))
}
}
pub struct OwnedSlot(Box<dyn VarArg + Send + Sync>);
impl Clone for OwnedSlot {
fn clone(&self) -> Self {
self.0.clone_slot()
}
}
impl std::ops::Deref for OwnedSlot {
type Target = dyn VarArg + Send + Sync;
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
impl std::fmt::Debug for OwnedSlot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("OwnedSlot")
}
}
impl OwnedContextImpl { impl OwnedContextImpl {
pub fn set_footprint(&mut self, footprint: Footprint) { pub fn set_footprint(&mut self, footprint: Footprint) {
self.footprint = Some(footprint); self.footprint = Some(footprint);
@@ -680,32 +675,807 @@ impl OwnedContextImpl {
} }
} }
#[derive(Default, Clone, dyn_any::DynAny)] pub type SourceId = u64;
pub struct ContextImpl<'a> {
pub(crate) footprint: Option<&'a Footprint>, #[derive(Clone, Copy, Debug)]
pub struct IndexLink<'a> {
pub index: u64,
pub outer: Option<&'a IndexLink<'a>>,
}
#[derive(Clone, Copy, Debug)]
pub struct PositionLink<'a> {
pub position: DVec2,
pub outer: Option<&'a PositionLink<'a>>,
}
pub type DynSlot<'a> = &'a (dyn VarArg + Send + Sync);
#[derive(Clone, Copy)]
pub enum VarArgSlots<'a> {
Single(DynSlot<'a>),
Slice(&'a [DynSlot<'a>]),
}
impl<'a> VarArgSlots<'a> {
pub fn get(&self, index: usize) -> Option<DynSlot<'a>> {
match self {
VarArgSlots::Single(slot) => (index == 0).then_some(*slot),
VarArgSlots::Slice(slots) => slots.get(index).copied(),
}
}
pub fn len(&self) -> usize {
match self {
VarArgSlots::Single(_) => 1,
VarArgSlots::Slice(slots) => slots.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn iter(&self) -> impl Iterator<Item = DynSlot<'a>> + '_ {
(0..self.len()).filter_map(move |index| self.get(index))
}
}
#[derive(Clone, Copy)]
pub struct VarArgLink<'a> {
pub args: VarArgSlots<'a>,
pub outer: Option<&'a VarArgLink<'a>>,
}
#[derive(Clone, Copy)]
pub struct EvalScope<'a> {
real_time: Option<f64>, real_time: Option<f64>,
position: Option<Vec<DVec2>>, // This could be converted into a single enum to save extra bytes animation_time: Option<f64>,
index: Option<Vec<usize>>, // This could be converted into a single enum to save extra bytes pointer_position: Option<DVec2>,
varargs: Option<&'a [DynRef<'a>]>, generations: &'a [(SourceId, u64)],
arena: &'a Arena,
hash: u64,
}
impl<'a> EvalScope<'a> {
pub fn new(real_time: Option<f64>, animation_time: Option<f64>, pointer_position: Option<DVec2>, generations: &'a [(SourceId, u64)], arena: &'a Arena) -> Self {
let mut scope = Self {
real_time,
animation_time,
pointer_position,
generations,
arena,
hash: 0,
};
scope.hash = scope.compute_hash(None);
scope
}
pub fn retained(&self, retain: &[SourceId]) -> EvalScope<'a> {
EvalScope {
hash: self.compute_hash(Some(retain)),
..*self
}
}
pub fn with_real_time(&self, real_time: Option<f64>) -> EvalScope<'a> {
let mut scope = EvalScope { real_time, ..*self };
scope.hash = scope.compute_hash(None);
scope
}
pub fn with_animation_time(&self, animation_time: Option<f64>) -> EvalScope<'a> {
let mut scope = EvalScope { animation_time, ..*self };
scope.hash = scope.compute_hash(None);
scope
}
pub fn with_pointer_position(&self, pointer_position: Option<DVec2>) -> EvalScope<'a> {
let mut scope = EvalScope { pointer_position, ..*self };
scope.hash = scope.compute_hash(None);
scope
}
pub fn nullified(&self, keep: ContextFeatures) -> EvalScope<'a> {
let mut scope = EvalScope {
real_time: self.real_time.filter(|_| keep.contains(ContextFeatures::REAL_TIME)),
animation_time: self.animation_time.filter(|_| keep.contains(ContextFeatures::ANIMATION_TIME)),
pointer_position: self.pointer_position.filter(|_| keep.contains(ContextFeatures::POINTER_POSITION)),
..*self
};
scope.hash = scope.compute_hash(None);
scope
}
fn compute_hash(&self, retain: Option<&[SourceId]>) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
self.real_time.map(f64::to_bits).hash(&mut hasher);
self.animation_time.map(f64::to_bits).hash(&mut hasher);
self.pointer_position.map(|position| (position.x.to_bits(), position.y.to_bits())).hash(&mut hasher);
for (source, generation) in self.generations {
if retain.is_none_or(|retain| retain.contains(source)) {
(source, generation).hash(&mut hasher);
}
}
hasher.finish()
}
pub fn generation(&self, source: SourceId) -> Option<u64> {
self.generations.iter().find(|(candidate, _)| *candidate == source).map(|(_, generation)| *generation)
}
pub fn generations(&self) -> &'a [(SourceId, u64)] {
self.generations
}
pub fn arena(&self) -> &'a Arena {
self.arena
}
}
pub trait ExtractArena {
type ArenaRef;
fn arena(&self) -> Self::ArenaRef;
}
pub trait CtxFamily {
type Ctx<'s>: Ctx + DeriveCtx<Family = Self>;
}
pub type Derived<'s, C> = <<C as DeriveCtx>::Family as CtxFamily>::Ctx<'s>;
pub trait DeriveCtx {
type Family: CtxFamily;
fn derived(&self) -> Derived<'_, Self>;
fn index_head(&self) -> IndexLink<'_>;
fn scope(&self) -> &EvalScope<'_>;
fn position_head(&self) -> Option<&PositionLink<'_>>;
fn varargs_head(&self) -> Option<&VarArgLink<'_>>;
fn promoted<'s>(&'s self, spilled_head: &'s IndexLink<'s>, inner_index: u64) -> Derived<'s, Self>;
fn with_footprint<'s>(&'s self, footprint: &'s Footprint) -> Derived<'s, Self>;
fn with_varargs<'s>(&'s self, varargs: &'s VarArgLink<'s>) -> Derived<'s, Self>;
fn with_position<'s>(&'s self, position: &'s PositionLink<'s>) -> Derived<'s, Self>;
fn with_scope<'s>(&'s self, scope: &'s EvalScope<'s>) -> Derived<'s, Self>;
fn nullified<'s>(&'s self, keep: ContextFeatures, scope: &'s EvalScope<'s>) -> Derived<'s, Self>;
fn modify_footprint(&self, modify: impl FnOnce(&mut Footprint)) -> ModifiedFootprint<'_, Self>
where
Self: ExtractFootprint + Sized,
{
let mut footprint = self.try_footprint().copied();
if let Some(footprint) = &mut footprint {
modify(footprint);
}
ModifiedFootprint { ctx: self, footprint }
}
fn push_vararg<'s>(&'s self, arg: DynSlot<'s>) -> VarArgScope<'s, Self>
where
Self: Sized,
{
VarArgScope {
ctx: self,
link: VarArgLink {
args: VarArgSlots::Single(arg),
outer: self.varargs_head(),
},
}
}
fn push_position(&self, position: DVec2) -> PositionScope<'_, Self>
where
Self: Sized,
{
PositionScope {
ctx: self,
link: PositionLink {
position,
outer: self.position_head(),
},
}
}
}
pub struct PositionScope<'c, C> {
ctx: &'c C,
link: PositionLink<'c>,
}
impl<C: DeriveCtx> PositionScope<'_, C> {
pub fn ctx(&self) -> Derived<'_, C> {
self.ctx.with_position(&self.link)
}
}
#[derive(Clone, Debug, Default)]
pub struct CtxSnapshot {
footprint: Option<Footprint>,
real_time: Option<f64>,
animation_time: Option<f64>,
pointer_position: Option<DVec2>,
index: Vec<usize>,
positions: Vec<DVec2>,
varargs: Vec<Vec<OwnedSlot>>,
generations: Vec<(SourceId, u64)>,
}
impl CtxSnapshot {
pub fn capture<C>(ctx: &C) -> Self
where
C: DeriveCtx + ExtractFootprint + ExtractRealTime + ExtractAnimationTime + ExtractPointerPosition + ExtractIndex + ExtractPosition,
{
Self {
footprint: ctx.try_footprint().copied(),
real_time: ctx.try_real_time(),
animation_time: ctx.try_animation_time(),
pointer_position: ctx.try_pointer_position(),
index: ctx.try_index().map(|levels| levels.collect()).unwrap_or_default(),
positions: ctx.try_position().map(|positions| positions.collect()).unwrap_or_default(),
varargs: std::iter::successors(ctx.varargs_head(), |link| link.outer)
.map(|link| link.args.iter().map(|slot| slot.clone_slot()).collect())
.collect(),
generations: ctx.scope().generations().to_vec(),
}
}
pub fn generations(&self) -> &[(SourceId, u64)] {
&self.generations
}
pub fn scope<'s>(&'s self, arena: &'s Arena) -> EvalScope<'s> {
EvalScope::new(self.real_time, self.animation_time, self.pointer_position, &self.generations, arena)
}
}
impl ExtractFootprint for CtxSnapshot {
fn try_footprint(&self) -> Option<&Footprint> {
self.footprint.as_ref()
}
}
impl ExtractRealTime for CtxSnapshot {
fn try_real_time(&self) -> Option<f64> {
self.real_time
}
}
impl ExtractAnimationTime for CtxSnapshot {
fn try_animation_time(&self) -> Option<f64> {
self.animation_time
}
}
impl ExtractPointerPosition for CtxSnapshot {
fn try_pointer_position(&self) -> Option<DVec2> {
self.pointer_position
}
}
impl ExtractIndex for CtxSnapshot {
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
Some(self.index.iter().copied())
}
}
impl ExtractPosition for CtxSnapshot {
fn try_position(&self) -> Option<impl Iterator<Item = DVec2>> {
Some(self.positions.iter().copied())
}
}
impl ExtractVarArgs for CtxSnapshot {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
if self.varargs.is_empty() {
return Err(VarArgsResult::NoVarArgs);
}
let slot = self.varargs.iter().flatten().nth(index).ok_or(VarArgsResult::IndexOutOfBounds)?;
Ok(&**slot as DynRef<'_>)
}
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
if self.varargs.is_empty() {
return Err(VarArgsResult::NoVarArgs);
}
Ok(self.varargs.iter().map(|level| level.len()).sum())
}
fn hash_varargs(&self, hasher: &mut dyn Hasher) {
let mut count = 0u64;
for slot in self.varargs.iter().flatten() {
slot.dyn_hash(&mut *hasher);
count += 1;
}
count.hash(&mut &mut *hasher);
}
}
pub struct VarArgScope<'c, C> {
ctx: &'c C,
link: VarArgLink<'c>,
}
impl<C: DeriveCtx> VarArgScope<'_, C> {
pub fn ctx(&self) -> Derived<'_, C> {
self.ctx.with_varargs(&self.link)
}
}
pub struct ModifiedFootprint<'c, C> {
ctx: &'c C,
footprint: Option<Footprint>,
}
impl<C: DeriveCtx> ModifiedFootprint<'_, C> {
pub fn ctx(&self) -> Derived<'_, C> {
match &self.footprint {
Some(footprint) => self.ctx.with_footprint(footprint),
None => self.ctx.derived(),
}
}
}
pub struct ContextImplFamily;
impl CtxFamily for ContextImplFamily {
type Ctx<'s> = ContextImpl<'s>;
}
#[derive(Clone, Copy)]
pub struct ContextImpl<'a> {
index: IndexLink<'a>,
position: Option<&'a PositionLink<'a>>,
varargs: Option<&'a VarArgLink<'a>>,
footprint: Option<&'a Footprint>,
scope: &'a EvalScope<'a>,
} }
impl<'a> ContextImpl<'a> { impl<'a> ContextImpl<'a> {
pub fn with_footprint<'f>(&self, new_footprint: &'f Footprint, varargs: Option<&'f impl Borrow<[DynRef<'f>]>>) -> ContextImpl<'f> pub fn root(scope: &'a EvalScope<'a>) -> Self {
Self {
index: IndexLink { index: 0, outer: None },
position: None,
varargs: None,
footprint: None,
scope,
}
}
pub fn scope(&self) -> &'a EvalScope<'a> {
self.scope
}
pub fn index_head(&self) -> IndexLink<'a> {
self.index
}
pub fn with_footprint<'s>(&self, footprint: &'s Footprint) -> ContextImpl<'s>
where where
'a: 'f, 'a: 's,
{
ContextImpl { footprint: Some(footprint), ..*self }
}
pub fn with_scope<'s>(&self, scope: &'s EvalScope<'s>) -> ContextImpl<'s>
where
'a: 's,
{
ContextImpl { scope, ..*self }
}
pub fn with_varargs<'s>(&self, varargs: &'s VarArgLink<'s>) -> ContextImpl<'s>
where
'a: 's,
{
ContextImpl { varargs: Some(varargs), ..*self }
}
pub fn with_position<'s>(&self, position: &'s PositionLink<'s>) -> ContextImpl<'s>
where
'a: 's,
{
ContextImpl { position: Some(position), ..*self }
}
pub fn nullified<'s>(&self, keep: ContextFeatures, scope: &'s EvalScope<'s>) -> ContextImpl<'s>
where
'a: 's,
{ {
ContextImpl { ContextImpl {
footprint: Some(new_footprint), index: match keep.contains(ContextFeatures::INDEX) {
position: self.position.clone(), true => self.index,
index: self.index.clone(), false => IndexLink { index: 0, outer: None },
varargs: varargs.map(|x| x.borrow()), },
position: self.position.filter(|_| keep.contains(ContextFeatures::POSITION)),
varargs: self.varargs.filter(|_| keep.contains(ContextFeatures::VARARGS)),
footprint: self.footprint.filter(|_| keep.contains(ContextFeatures::FOOTPRINT)),
scope,
}
}
pub fn promoted<'s>(&self, spilled_head: &'s IndexLink<'s>, inner_index: u64) -> ContextImpl<'s>
where
'a: 's,
{
ContextImpl {
index: IndexLink {
index: inner_index,
outer: Some(spilled_head),
},
..*self ..*self
} }
} }
} }
impl Ctx for ContextImpl<'_> {}
impl InjectIndex for ContextImpl<'_> {
fn set_index(&mut self, index: u64) {
self.index.index = index;
}
}
impl ExtractFootprint for ContextImpl<'_> {
fn try_footprint(&self) -> Option<&Footprint> {
self.footprint
}
}
impl ExtractRealTime for ContextImpl<'_> {
fn try_real_time(&self) -> Option<f64> {
self.scope.real_time
}
}
impl ExtractAnimationTime for ContextImpl<'_> {
fn try_animation_time(&self) -> Option<f64> {
self.scope.animation_time
}
}
impl ExtractPointerPosition for ContextImpl<'_> {
fn try_pointer_position(&self) -> Option<DVec2> {
self.scope.pointer_position
}
}
impl ExtractIndex for ContextImpl<'_> {
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
Some(std::iter::successors(Some(&self.index), |link| link.outer).map(|link| link.index as usize))
}
}
impl ExtractPosition for ContextImpl<'_> {
fn try_position(&self) -> Option<impl Iterator<Item = DVec2>> {
self.position.map(|head| std::iter::successors(Some(head), |link| link.outer).map(|link| link.position))
}
}
impl ExtractVarArgs for ContextImpl<'_> {
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
let mut link = self.varargs.ok_or(VarArgsResult::NoVarArgs)?;
let mut remaining = index;
loop {
match link.args.get(remaining) {
Some(arg) => return Ok(arg as DynRef<'_>),
None => {
remaining -= link.args.len();
link = link.outer.ok_or(VarArgsResult::IndexOutOfBounds)?;
}
}
}
}
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
let head = self.varargs.ok_or(VarArgsResult::NoVarArgs)?;
Ok(std::iter::successors(Some(head), |link| link.outer).map(|link| link.args.len()).sum())
}
fn hash_varargs(&self, hasher: &mut dyn Hasher) {
let mut count = 0u64;
let mut link = self.varargs;
while let Some(current) = link {
for arg in current.args.iter() {
arg.dyn_hash(&mut *hasher);
count += 1;
}
link = current.outer;
}
count.hash(&mut &mut *hasher);
}
}
impl<'a> ExtractArena for ContextImpl<'a> {
type ArenaRef = &'a Arena;
fn arena(&self) -> &'a Arena {
self.scope.arena
}
}
impl<'a> DeriveCtx for ContextImpl<'a> {
type Family = ContextImplFamily;
fn derived(&self) -> ContextImpl<'_> {
*self
}
fn index_head(&self) -> IndexLink<'_> {
self.index
}
fn scope(&self) -> &EvalScope<'_> {
self.scope
}
fn position_head(&self) -> Option<&PositionLink<'_>> {
self.position
}
fn varargs_head(&self) -> Option<&VarArgLink<'_>> {
self.varargs
}
fn promoted<'s>(&'s self, spilled_head: &'s IndexLink<'s>, inner_index: u64) -> ContextImpl<'s> {
ContextImpl::promoted(self, spilled_head, inner_index)
}
fn with_footprint<'s>(&'s self, footprint: &'s Footprint) -> ContextImpl<'s> {
ContextImpl::with_footprint(self, footprint)
}
fn with_varargs<'s>(&'s self, varargs: &'s VarArgLink<'s>) -> ContextImpl<'s> {
ContextImpl::with_varargs(self, varargs)
}
fn with_position<'s>(&'s self, position: &'s PositionLink<'s>) -> ContextImpl<'s> {
ContextImpl::with_position(self, position)
}
fn with_scope<'s>(&'s self, scope: &'s EvalScope<'s>) -> ContextImpl<'s> {
ContextImpl::with_scope(self, scope)
}
fn nullified<'s>(&'s self, keep: ContextFeatures, scope: &'s EvalScope<'s>) -> ContextImpl<'s> {
ContextImpl::nullified(self, keep, scope)
}
}
impl graphene_hash::CacheHash for ContextImpl<'_> {
fn cache_hash<H: Hasher>(&self, state: &mut H) {
match self.footprint {
Some(footprint) => {
1u8.hash(state);
footprint.cache_hash(state);
}
None => 0u8.hash(state),
}
let mut count = 0u64;
for link in std::iter::successors(Some(&self.index), |link| link.outer) {
link.index.hash(state);
count += 1;
}
count.hash(state);
count = 0;
let mut position = self.position;
while let Some(link) = position {
link.position.x.to_bits().hash(state);
link.position.y.to_bits().hash(state);
count += 1;
position = link.outer;
}
count.hash(state);
self.hash_varargs(state);
self.scope.hash.hash(state);
}
}
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum VarArgsResult { pub enum VarArgsResult {
IndexOutOfBounds, IndexOutOfBounds,
NoVarArgs, NoVarArgs,
} }
#[cfg(test)]
mod context_impl_tests {
use super::*;
use crate::graphene_hash::CacheHash;
fn hash_of(ctx: &ContextImpl) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
ctx.cache_hash(&mut hasher);
hasher.finish()
}
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
EvalScope::new(Some(0.5), Some(1.5), None, generations, arena)
}
#[test]
fn equal_contexts_hash_equal() {
let arena = Arena::new(64);
let generations = [(0, 1), (1, 3)];
let scope = scope_fixture(&generations, &arena);
let a = ContextImpl::root(&scope);
let b = ContextImpl::root(&scope);
assert_eq!(hash_of(&a), hash_of(&b));
}
#[test]
fn each_axis_changes_the_hash() {
let arena = Arena::new(64);
let generations = [(0, 1)];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let footprint = Footprint::DEFAULT;
let mut indexed = root;
indexed.set_index(4);
let position_link = PositionLink {
position: DVec2::new(1.0, 2.0),
outer: None,
};
let time_scope = scope.with_real_time(Some(9.75));
let variants = [root.with_footprint(&footprint), indexed, root.with_position(&position_link), root.with_scope(&time_scope)];
let root_hash = hash_of(&root);
let mut hashes: Vec<u64> = variants.iter().map(hash_of).collect();
hashes.push(root_hash);
hashes.sort();
hashes.dedup();
assert_eq!(hashes.len(), variants.len() + 1, "every axis must contribute to the hash");
}
#[test]
fn index_level_order_matters() {
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let outer_one = IndexLink { index: 1, outer: None };
let mut one_two = root.promoted(&outer_one, 2);
let outer_two = IndexLink { index: 2, outer: None };
let mut two_one = root.promoted(&outer_two, 1);
assert_ne!(hash_of(&one_two), hash_of(&two_one));
one_two.set_index(7);
two_one.set_index(7);
assert_ne!(hash_of(&one_two), hash_of(&two_one), "outer levels must stay hashed after set_index");
}
#[test]
fn axis_boundaries_are_unambiguous() {
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let position = PositionLink {
position: DVec2::new(5.0, 5.0),
outer: None,
};
let spilled = root.index_head();
let mut deep_index = root.promoted(&spilled, 0);
deep_index.set_index(5);
let shallow_with_position = root.with_position(&position);
assert_ne!(hash_of(&deep_index), hash_of(&shallow_with_position), "index levels must not blur into position levels");
}
#[test]
fn retain_scopes_generation_invalidation() {
let arena = Arena::new(64);
let initial = [(0, 1), (1, 3)];
let bumped_unretained = [(0, 2), (1, 3)];
let bumped_retained = [(0, 1), (1, 4)];
let hash_with = |generations: &[(SourceId, u64)]| {
let scope = scope_fixture(generations, &arena).retained(&[1]);
let retained_scope_context = ContextImpl::root(&scope);
hash_of(&retained_scope_context)
};
assert_eq!(hash_with(&initial), hash_with(&bumped_unretained), "unretained source bumps must not invalidate");
assert_ne!(hash_with(&initial), hash_with(&bumped_retained), "retained source bumps must invalidate");
}
#[test]
fn unretained_scope_sees_every_bump() {
let arena = Arena::new(64);
let initial = [(0, 1)];
let bumped = [(0, 2)];
let hash_with = |generations: &[(SourceId, u64)]| {
let scope = scope_fixture(generations, &arena);
hash_of(&ContextImpl::root(&scope))
};
assert_ne!(hash_with(&initial), hash_with(&bumped));
}
#[test]
fn set_index_is_visible_and_keeps_outer_levels() {
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let spilled = root.index_head();
let mut ctx = root.promoted(&spilled, 0);
ctx.set_index(11);
let levels: Vec<usize> = ctx.try_index().unwrap().collect();
assert_eq!(levels, vec![11, 0]);
}
#[test]
fn vararg_chain_concatenates_innermost_first() {
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let outer_value = 7u32;
let outer_args: [DynSlot; 1] = [&outer_value];
let outer_link = VarArgLink {
args: VarArgSlots::Slice(&outer_args),
outer: None,
};
let outer_ctx = root.with_varargs(&outer_link);
let inner_value = String::from("inner");
let inner_link = VarArgLink {
args: VarArgSlots::Single(&inner_value),
outer: Some(&outer_link),
};
let inner_ctx = root.with_varargs(&inner_link);
assert_eq!(root.varargs_len(), Err(VarArgsResult::NoVarArgs));
assert_eq!(outer_ctx.varargs_len(), Ok(1));
assert_eq!(inner_ctx.varargs_len(), Ok(2));
assert!(inner_ctx.vararg(0).unwrap().downcast_ref::<String>().is_some());
assert!(inner_ctx.vararg(1).unwrap().downcast_ref::<u32>().is_some());
assert!(matches!(inner_ctx.vararg(2), Err(VarArgsResult::IndexOutOfBounds)));
assert_ne!(hash_of(&outer_ctx), hash_of(&inner_ctx));
}
#[test]
fn snapshot_captures_vararg_levels() {
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let outer_value = 7u32;
let outer_args: [DynSlot; 1] = [&outer_value];
let outer_link = VarArgLink {
args: VarArgSlots::Slice(&outer_args),
outer: None,
};
let inner_value = String::from("inner");
let inner_link = VarArgLink {
args: VarArgSlots::Single(&inner_value),
outer: Some(&outer_link),
};
let ctx = root.with_varargs(&inner_link);
let snapshot = CtxSnapshot::capture(&ctx);
assert_eq!(snapshot.varargs_len(), Ok(2));
assert_eq!(snapshot.vararg(0).unwrap().downcast_ref::<String>(), Some(&inner_value));
assert_eq!(snapshot.vararg(1).unwrap().downcast_ref::<u32>(), Some(&outer_value));
assert!(matches!(snapshot.vararg(2), Err(VarArgsResult::IndexOutOfBounds)));
let hash_via = |target: &dyn Fn(&mut dyn Hasher)| {
let mut hasher = std::hash::DefaultHasher::new();
target(&mut hasher);
hasher.finish()
};
assert_eq!(
hash_via(&|hasher| snapshot.hash_varargs(hasher)),
hash_via(&|hasher| ctx.hash_varargs(hasher)),
"snapshot varargs must hash like the borrowed chain"
);
let cloned = snapshot.clone();
assert_eq!(cloned.vararg(0).unwrap().downcast_ref::<String>(), Some(&inner_value));
let empty = CtxSnapshot::capture(&root);
assert_eq!(empty.varargs_len(), Err(VarArgsResult::NoVarArgs));
assert!(matches!(empty.vararg(0), Err(VarArgsResult::NoVarArgs)));
}
#[test]
fn scope_arena_reaches_kernels_through_extract_arena() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let (value, _) = ExtractArena::arena(&ctx).alloc(41u32).unwrap();
assert_eq!(*value, 41);
}
}
@@ -0,0 +1,155 @@
use crate::gpoll::Finality;
use std::cell::UnsafeCell;
use std::mem::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>>,
}
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> {
// Keys are forced odd so the empty sentinel (0) can never collide.
let key = hash | 1;
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 {
// 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 { &*(*self.slot.value.get()).write(value) };
let state = match finality {
Finality::AllFinal => SLOT_FINAL,
Finality::Partial => SLOT_PARTIAL,
};
self.slot.state.store(state, Ordering::Release);
lent
}
pub fn release(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 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);
}
}
@@ -0,0 +1,348 @@
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(&'a [T], Finality),
Filled(&'a mut [T], Finality),
Pending,
Error(GraphError),
NeedBuffer,
InvalidRange,
}
/// # 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) }
}
pub trait GNode<Input> {
type Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output>;
fn extent(&self, _input: &Input) -> GPoll<Extent> {
GPoll::Final(Extent::Free)
}
fn eval_batch<'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).map(|len| len as usize) 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(unsafe { assume_init_prefix_mut(scratch, len) }, finality)
}
}
impl<Input, N> GNode<Input> for &N
where
N: GNode<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 eval_batch<'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> GNode<Input> for Box<N>
where
N: GNode<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 eval_batch<'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: GNode<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: GNode<Input>,
{
self.cell.eval_input(self.input_index, self.node, ctx)
}
}
impl<'a, Input, N> GNode<Input> for LazyInput<'a, N>
where
N: GNode<Input>,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
self.node.eval(input)
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
self.node.extent(input)
}
fn eval_batch<'b>(&self, input: &'b Input, range: Range<u64>, scratch: Option<&'b mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'b, Self::Output>
where
Input: InjectIndex + Copy,
{
self.node.eval_batch(input, range, scratch)
}
}
#[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 GNode<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(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes, &[4, 6, 8, 10]);
assert_eq!(finality, Finality::AllFinal);
}
#[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 GNode<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(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes, &[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 GNode<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 GNode<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)));
}
}
@@ -0,0 +1,227 @@
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorKind {
Node(&'static str),
ArenaExhausted,
}
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(),
}))
}
}
#[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"));
}
}
@@ -1,9 +1,13 @@
extern crate log; extern crate log;
pub mod arena;
pub mod bounds; pub mod bounds;
pub mod consts; pub mod consts;
pub mod context; pub mod context;
pub mod frame_table;
pub mod generic; pub mod generic;
pub mod gnode;
pub mod gpoll;
pub mod list; pub mod list;
pub mod math; pub mod math;
pub mod memo; pub mod memo;
@@ -11,9 +15,11 @@ pub mod misc;
pub mod ops; pub mod ops;
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;
pub mod wire;
pub use crate as core_types; pub use crate as core_types;
pub use blending::*; pub use blending::*;
+10 -10
View File
@@ -44,13 +44,13 @@ impl<'i, N: for<'a> Node<'a, I> + Copy, I: 'i> Copy for TypeNode<N, I, <N as Nod
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;
} }
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 +60,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 +76,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 +86,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 +95,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 +115,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 +124,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 +146,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)
} }
} }
@@ -0,0 +1,272 @@
use crate::SourceId;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
#[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 {
fn spawn(&self, source: SourceId, future: SourceFuture);
}
#[derive(Clone)]
pub struct RuntimeHandle(pub Arc<DynRuntime>);
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) {}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::arena::Arena;
use crate::context::{ContextImpl, Ctx, CtxSnapshot, EvalScope, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots};
use crate::gnode::GNode;
use crate::gpoll::GPoll;
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) {
self.futures.lock().unwrap().push((source, future));
}
}
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()
}
}
struct SourceNode<T>(T);
impl<T: Clone, Input> GNode<Input> for SourceNode<T> {
type Output = T;
fn eval(&self, _input: &Input) -> GPoll<T> {
GPoll::Final(self.0.clone())
}
}
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> GNode<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);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = SlowDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(7u64));
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(GNode::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!(GNode::eval(&graph, &ctx), GPoll::Final(42.0));
assert_eq!(GNode::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);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = PreviewDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(1u64));
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Partial(-1.0));
runtime.drain();
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(42.0));
}
#[test]
fn no_partial_maps_the_placeholder_frame_to_pending() {
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = StrictDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(2u64));
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(42.0));
}
#[test]
fn prologue_runs_sync_and_spawns_once() {
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = StagedDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(8u64));
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "the prologue runs synchronously on the miss");
assert_eq!(GNode::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!(GNode::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);
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 = StagedSumNode::new(
SourceNode(40.0f64),
GatedSource(gate.clone(), 2.0),
SourceNode(RuntimeHandle(runtime.clone())),
SourceNode(9u64),
);
assert_eq!(GNode::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!(GNode::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(runtime.drain(), vec![9]);
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(42.0));
}
#[test]
fn async_kernels_read_captured_varargs() {
let arena = Arena::new(64);
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 = SnapshotVarargNode::new(SourceNode(()), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(5u64));
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(21.5));
}
#[test]
fn async_kernels_read_the_captured_context_snapshot() {
let arena = Arena::new(64);
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 = SnapshotResolutionNode::new(SourceNode(()), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(3u64));
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(Footprint::DEFAULT.resolution.x));
}
}
@@ -235,6 +235,7 @@ 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>),
Ref(Box<Type>),
} }
impl Default for Type { impl Default for Type {
@@ -308,6 +309,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::Ref(_) => None,
} }
} }
@@ -317,6 +319,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::Ref(_) => None,
} }
} }
@@ -326,6 +329,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::Ref(inner) => inner.nested_type(),
} }
} }
@@ -338,6 +342,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::Ref(inner) => inner.replace_nested(f),
} }
} }
@@ -347,6 +352,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::Ref(ty) => ty.identifier_name(),
} }
} }
} }
@@ -441,6 +447,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::Ref(ty) => write!(f, "{ty}"),
} }
} }
} }
+560
View File
@@ -0,0 +1,560 @@
use crate::Type;
use crate::arena::{Arena, ArenaCell};
use crate::concrete;
use crate::context::{ContextImpl, Ctx, ExtractArena};
use crate::frame_table::{FrameTable, Lookup};
use crate::gnode::GNode;
use crate::gpoll::{Extent, Finality, GPoll};
use graphene_hash::CacheHash;
use std::any::Any;
use std::hash::Hasher;
use std::sync::Mutex;
pub type ErasedGNode<T> = dyn for<'c> GNode<ContextImpl<'c>, Output = T>;
pub type ErasedLendGNode<T> = dyn for<'c> GNode<ContextImpl<'c>, Output = &'c T>;
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
ctx.cache_hash(&mut hasher);
hasher.finish()
}
#[derive(Debug, PartialEq)]
pub enum WireError {
Arity { expected: usize, got: usize },
Type { expected: Type, found: Type },
MissingCapability { ty: Type },
}
#[derive(Clone, Copy, Default)]
pub struct WireCapabilities {
pub memoize: Option<fn(EdgeHandle) -> Result<EdgeHandle, WireError>>,
pub lend: Option<fn(EdgeHandle) -> Result<EdgeHandle, WireError>>,
}
fn memoize_edge<T: Clone + 'static>(edge: EdgeHandle) -> Result<EdgeHandle, WireError> {
let content = edge.downcast::<T>()?;
Ok(EdgeHandle::new(Box::new(MemoizeNode::new(content)) as Box<ErasedGNode<T>>))
}
fn lend_edge<T: Clone + 'static>(edge: EdgeHandle) -> Result<EdgeHandle, WireError> {
let content = edge.downcast::<T>()?;
Ok(EdgeHandle::new_ref(Box::new(FrameMemoNode::new(content)) as Box<ErasedLendGNode<T>>))
}
pub struct EdgeHandle {
node: Box<dyn Any>,
ty: Type,
capabilities: WireCapabilities,
}
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()
}
}
impl EdgeHandle {
pub fn new<T: Clone + 'static>(node: Box<ErasedGNode<T>>) -> Self {
Self::new_erased(
node,
concrete!(T),
WireCapabilities {
memoize: Some(memoize_edge::<T>),
lend: Some(lend_edge::<T>),
},
)
}
pub fn new_ref<T: 'static>(node: Box<ErasedLendGNode<T>>) -> Self {
Self::new_erased(node, Type::Ref(Box::new(concrete!(T))), WireCapabilities::default())
}
pub fn new_erased<N: ?Sized>(node: Box<N>, ty: Type, capabilities: WireCapabilities) -> Self
where
Box<N>: Any,
{
Self {
node: Box::new(node),
ty,
capabilities,
}
}
pub fn wire_type(&self) -> &Type {
&self.ty
}
pub fn memoized(self) -> Result<EdgeHandle, WireError> {
match self.capabilities.memoize {
Some(wrap) => wrap(self),
None => Err(WireError::MissingCapability { ty: self.ty }),
}
}
pub fn lent(self) -> Result<EdgeHandle, WireError> {
match self.capabilities.lend {
Some(wrap) => wrap(self),
None => Err(WireError::MissingCapability { ty: self.ty }),
}
}
pub fn downcast<T: 'static>(self) -> Result<Box<ErasedGNode<T>>, WireError> {
self.downcast_erased(concrete!(T))
}
pub fn downcast_lend<T: 'static>(self) -> Result<Box<ErasedLendGNode<T>>, WireError> {
self.downcast_erased(Type::Ref(Box::new(concrete!(T))))
}
pub fn downcast_erased<N: ?Sized>(self, expected: Type) -> Result<Box<N>, WireError>
where
Box<N>: Any,
{
let found = self.ty;
self.node.downcast::<Box<N>>().map(|node| *node).map_err(|_| WireError::Type { expected, found })
}
}
pub struct NodeIoRecord {
pub inputs: Vec<Type>,
pub output: Type,
}
pub struct RegistryEntry {
pub io: NodeIoRecord,
pub wire: fn(Vec<EdgeHandle>) -> Result<EdgeHandle, WireError>,
}
pub fn resolve_and_wire(entry: &RegistryEntry, inputs: Vec<EdgeHandle>) -> Result<EdgeHandle, WireError> {
if inputs.len() != entry.io.inputs.len() {
return Err(WireError::Arity {
expected: entry.io.inputs.len(),
got: inputs.len(),
});
}
for (handle, expected) in inputs.iter().zip(&entry.io.inputs) {
if handle.wire_type() != expected {
return Err(WireError::Type {
expected: expected.clone(),
found: handle.wire_type().clone(),
});
}
}
(entry.wire)(inputs)
}
pub struct MemoizeNode<T, NodeContent> {
cache: Mutex<Option<(u64, T, Finality)>>,
content: NodeContent,
}
impl<T, NodeContent> MemoizeNode<T, NodeContent> {
pub fn new(content: NodeContent) -> Self {
Self {
cache: Mutex::new(None),
content,
}
}
}
impl<T, Input, NodeContent> GNode<Input> for MemoizeNode<T, NodeContent>
where
T: Clone,
Input: Ctx + CacheHash,
NodeContent: GNode<Input, Output = T>,
{
type Output = T;
fn eval(&self, input: &Input) -> GPoll<T> {
let key = cache_key(input);
if let Some((hash, value, finality)) = self.cache.lock().unwrap().as_ref() {
if *hash == key {
return match finality {
Finality::AllFinal => GPoll::Final(value.clone()),
Finality::Partial => GPoll::Partial(value.clone()),
};
}
}
let result = self.content.eval(input);
match &result {
GPoll::Final(value) => *self.cache.lock().unwrap() = Some((key, value.clone(), Finality::AllFinal)),
GPoll::Partial(value) => *self.cache.lock().unwrap() = Some((key, value.clone(), Finality::Partial)),
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => {}
}
result
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
self.content.extent(input)
}
}
pub struct FrameMemoNode<T, NodeContent> {
cell: ArenaCell<FrameTable<T, 32>>,
content: NodeContent,
}
impl<T, NodeContent> FrameMemoNode<T, NodeContent> {
pub fn new(content: NodeContent) -> Self {
Self {
cell: ArenaCell::new(),
content,
}
}
}
impl<'e, T, Input, NodeContent> GNode<Input> for FrameMemoNode<T, NodeContent>
where
T: Clone + 'static,
Input: Ctx + CacheHash + ExtractArena<ArenaRef = &'e Arena>,
NodeContent: GNode<Input, Output = T>,
{
type Output = &'e T;
fn eval(&self, input: &Input) -> GPoll<&'e T> {
let arena = input.arena();
let table = match self.cell.load(arena) {
Some(table) => table,
None => match arena.alloc(FrameTable::new()) {
Some((table, weak)) => {
self.cell.store(weak);
table
}
None => return park(arena, self.content.eval(input)),
},
};
match table.lookup(cache_key(input)) {
Lookup::Hit(Finality::AllFinal, value) => GPoll::Final(value),
Lookup::Hit(Finality::Partial, value) => GPoll::Partial(value),
Lookup::Vacant(slot) => match self.content.eval(input) {
GPoll::Final(value) => GPoll::Final(slot.publish(value, Finality::AllFinal)),
GPoll::Partial(value) => GPoll::Partial(slot.publish(value, Finality::Partial)),
unpublishable => {
slot.release();
park(arena, unpublishable)
}
},
Lookup::Full => park(arena, self.content.eval(input)),
}
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
self.content.extent(input)
}
}
pub fn park<'e, T>(arena: &'e Arena, result: GPoll<T>) -> GPoll<&'e T> {
match result {
GPoll::Final(value) => match arena.alloc(value) {
Some((parked, _)) => GPoll::Final(parked),
None => GPoll::arena_exhausted(),
},
GPoll::Partial(value) => match arena.alloc(value) {
Some((parked, _)) => GPoll::Partial(parked),
None => GPoll::arena_exhausted(),
},
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
match arena.alloc(value) {
Some((parked, _)) => GPoll::Fallback(Box::new((parked, error))),
None => GPoll::arena_exhausted(),
}
}
GPoll::Pending => GPoll::Pending,
GPoll::Error(error) => GPoll::Error(error),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::context::EvalScope;
use crate::SourceId;
use std::sync::atomic::{AtomicU32, Ordering};
struct CountingNode(AtomicU32);
impl<Input> GNode<Input> for CountingNode {
type Output = u32;
fn eval(&self, _input: &Input) -> GPoll<u32> {
GPoll::Final(self.0.fetch_add(1, Ordering::Relaxed) + 1)
}
}
struct ValueNode<T>(T);
impl<T: Clone, Input> GNode<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> {
EvalScope::new(Some(0.5), None, None, generations, arena)
}
#[test]
fn memo_capability_wraps_edges_type_blind() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = EdgeHandle::new(Box::new(CountingNode(AtomicU32::new(0))) as Box<ErasedGNode<u32>>);
let memoized = edge.memoized().unwrap().downcast::<u32>().unwrap();
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);
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 edge = EdgeHandle::new(Box::new(CountingNode(AtomicU32::new(0))) as Box<ErasedGNode<u32>>);
let memoized = edge.memoized().unwrap().downcast::<u32>().unwrap();
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 memoized_edges_stack_and_rewire() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = EdgeHandle::new(Box::new(CountingNode(AtomicU32::new(0))) as Box<ErasedGNode<u32>>);
let stacked = edge.memoized().unwrap().memoized().unwrap().downcast::<u32>().unwrap();
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
}
#[test]
fn lend_capability_turns_an_owned_edge_into_a_lending_edge() {
let arena = Arena::new(4096);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = EdgeHandle::new(Box::new(ValueNode("lent out".to_string())) as Box<ErasedGNode<String>>);
let lending = edge.lent().unwrap();
assert_eq!(*lending.wire_type(), Type::Ref(Box::new(concrete!(String))));
let node = lending.downcast_lend::<String>().unwrap();
let GPoll::Final(first) = node.eval(&ctx) else {
panic!("lend must fill the frame table and lend");
};
let GPoll::Final(second) = node.eval(&ctx) else {
panic!("second eval must lend the published value");
};
assert_eq!(first, "lent out");
assert!(std::ptr::eq(first, second));
}
#[test]
fn ref_edges_report_missing_capabilities() {
let edge = EdgeHandle::new(Box::new(ValueNode(5u32)) as Box<ErasedGNode<u32>>);
let lending = edge.lent().unwrap();
match lending.memoized() {
Err(WireError::MissingCapability { ty }) => assert_eq!(ty, Type::Ref(Box::new(concrete!(u32)))),
other => panic!("expected missing capability, got {:?}", other.map(|handle| handle.ty)),
}
}
#[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> GNode<Input> for SplitNode<Node0>
where
Input: Ctx,
Node0: GNode<Input, Output = &'e String>,
{
type Output = SplitBorrow<'e>;
fn eval(&self, input: &Input) -> GPoll<SplitBorrow<'e>> {
self.content.eval(input).map(|value| SplitBorrow(value, value.len()))
}
}
type ErasedSplitEdge = dyn for<'c> GNode<ContextImpl<'c>, Output = SplitBorrow<'c>>;
let arena = Arena::new(4096);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let lending = EdgeHandle::new(Box::new(ValueNode("held".to_string())) as Box<ErasedGNode<String>>).lent().unwrap();
let upstream = lending.downcast_lend::<String>().unwrap();
let node: Box<ErasedSplitEdge> = Box::new(SplitNode { content: upstream });
let handle = EdgeHandle::new_erased(node, concrete!(SplitBorrow<'static>), WireCapabilities::default());
assert_eq!(*handle.wire_type(), concrete!(SplitBorrow<'static>));
let wired = handle.downcast_erased::<ErasedSplitEdge>(concrete!(SplitBorrow<'static>)).unwrap();
let GPoll::Final(split) = wired.eval(&ctx) else {
panic!("borrow-carrying output must eval through the erased edge");
};
assert_eq!(split.0, "held");
assert_eq!(split.1, 4);
}
#[test]
fn derive_ctx_repeat_pushes_index_levels_through_the_erased_edge() {
use crate::context::{Derived, DeriveCtx, ExtractIndex};
struct RepeatNode<Node0> {
content: Node0,
}
impl<C, T, Node0> GNode<C> for RepeatNode<Node0>
where
C: Ctx + DeriveCtx,
Node0: for<'x> GNode<Derived<'x, C>, Output = T>,
{
type Output = Vec<T>;
fn eval(&self, input: &C) -> GPoll<Vec<T>> {
let spilled = input.index_head();
let mut result = Vec::new();
for index in 0..3 {
let derived = input.promoted(&spilled, index);
match self.content.eval(&derived) {
GPoll::Final(value) => result.push(value),
other => return other.map(|_| Vec::new()),
}
}
GPoll::Final(result)
}
}
struct LevelsNode;
impl<Input: ExtractIndex> GNode<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);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let nested = RepeatNode {
content: RepeatNode { content: LevelsNode },
};
let erased: Box<ErasedGNode<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::{Derived, DeriveCtx, ExtractFootprint};
use crate::transform::Footprint;
struct ShiftFootprintNode<Node0> {
content: Node0,
}
impl<C, T, Node0> GNode<C> for ShiftFootprintNode<Node0>
where
C: Ctx + DeriveCtx + ExtractFootprint,
Node0: for<'x> GNode<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> GNode<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);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let graph: Box<ErasedGNode<u32>> = Box::new(ShiftFootprintNode {
content: ShiftFootprintNode { content: ResolutionNode },
});
assert_eq!(graph.eval(&ctx), GPoll::Final(Footprint::DEFAULT.resolution.x + 14));
}
#[test]
fn resolve_and_wire_checks_arity_and_types() {
fn wire_strlen(args: Vec<EdgeHandle>) -> Result<EdgeHandle, WireError> {
let mut args = args.into_iter();
let value = args.next().ok_or(WireError::Arity { expected: 1, got: 0 })?.downcast::<String>()?;
drop(value);
Ok(EdgeHandle::new(Box::new(ValueNode(0u32)) as Box<ErasedGNode<u32>>))
}
let entry = RegistryEntry {
io: NodeIoRecord {
inputs: vec![concrete!(String)],
output: concrete!(u32),
},
wire: wire_strlen,
};
let owned = EdgeHandle::new(Box::new(ValueNode("typed".to_string())) as Box<ErasedGNode<String>>);
assert!(resolve_and_wire(&entry, vec![owned]).is_ok());
assert_eq!(resolve_and_wire(&entry, vec![]).unwrap_err(), WireError::Arity { expected: 1, got: 0 });
let mistyped = EdgeHandle::new(Box::new(ValueNode(1.0f64)) as Box<ErasedGNode<f64>>);
assert_eq!(
resolve_and_wire(&entry, vec![mistyped]).unwrap_err(),
WireError::Type {
expected: concrete!(String),
found: concrete!(f64),
}
);
let lent = EdgeHandle::new(Box::new(ValueNode("typed".to_string())) as Box<ErasedGNode<String>>).lent().unwrap();
assert_eq!(
resolve_and_wire(&entry, vec![lent]).unwrap_err(),
WireError::Type {
expected: concrete!(String),
found: Type::Ref(Box::new(concrete!(String))),
}
);
}
}
@@ -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> {
@@ -9,7 +9,7 @@ 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 std::sync::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;
@@ -19,7 +19,6 @@ 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;
@@ -68,8 +67,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 +81,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 +108,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,7 +2,7 @@ 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 std::sync::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;
@@ -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();
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));
@@ -38,120 +38,17 @@ fn upload_to_texture(device: &wgpu::Device, queue: &wgpu::Queue, image: &Raster<
) )
} }
/// Converts a Raster<GPU> texture to Raster<CPU> by downloading the underlying texture data.
///
/// Assumptions:
/// - 2D texture, mip level 0
/// - 4 bytes-per-pixel RGBA8
/// - Texture has COPY_SRC usage
struct RasterGpuToRasterCpuConverter {
buffer: wgpu::Buffer,
width: u32,
height: u32,
unpadded_bytes_per_row: u32,
padded_bytes_per_row: u32,
_source: raster_types::Texture,
}
impl RasterGpuToRasterCpuConverter {
fn new(device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
let texture = data_gpu.data();
let width = texture.width();
let height = texture.height();
let bytes_per_pixel = 4; // RGBA8
let unpadded_bytes_per_row = width * bytes_per_pixel;
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
let buffer_size = padded_bytes_per_row as u64 * height as u64;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("texture_download_buffer"),
size: buffer_size,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded_bytes_per_row),
rows_per_image: Some(height),
},
},
Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
Self {
buffer,
width,
height,
unpadded_bytes_per_row,
padded_bytes_per_row,
// Keep source texture alive
_source: data_gpu.texture.clone(),
}
}
async fn convert(self, device: &wgpu::Device) -> Result<Raster<CPU>, wgpu::BufferAsyncError> {
let buffer_slice = self.buffer.slice(..);
let (sender, receiver) = futures::channel::oneshot::channel();
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
let _ = sender.send(result);
});
let _ = device.poll(wgpu::wgt::PollType::wait_indefinitely());
receiver.await.expect("Failed to receive map result")?;
let view = buffer_slice.get_mapped_range();
let row_stride = self.padded_bytes_per_row as usize;
let row_bytes = self.unpadded_bytes_per_row as usize;
let mut cpu_data: Vec<Color> = Vec::with_capacity((self.width * self.height) as usize);
for row in 0..self.height as usize {
let start = row * row_stride;
let row_slice = &view[start..start + row_bytes];
for px in row_slice.chunks_exact(4) {
// `Image<Color>` pixels are stored linear-light with associated (premultiplied) alpha
let srgba = SRGBA8::new(px[0], px[1], px[2], px[3]);
cpu_data.push(Color::from(srgba).apply_opacity(px[3] as f32 / 255.));
}
}
drop(view);
self.buffer.unmap();
let cpu_image = Image {
data: cpu_data,
width: self.width,
height: self.height,
base64_string: None,
};
Ok(Raster::new_cpu(cpu_image))
}
}
/// Passthrough conversion for GPU `List`s - no conversion needed /// Passthrough conversion for GPU `List`s - no conversion needed
impl<'i> Convert<List<Raster<GPU>>, &'i WgpuExecutor> for List<Raster<GPU>> { impl<'i> Convert<List<Raster<GPU>>, &'i WgpuExecutor> for List<Raster<GPU>> {
async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<GPU>> { fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<GPU>> {
self self
} }
} }
/// Converts a `List<Raster<CPU>>` to `List<Raster<GPU>>` by uploading each image to a texture /// 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>> { impl<'i> Convert<List<Raster<GPU>>, &'i WgpuExecutor> for List<Raster<CPU>> {
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> List<Raster<GPU>> { fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> List<Raster<GPU>> {
let device = &executor.context().device; let device = &executor.context().device;
let queue = executor.context().queue.lock(); let queue = executor.context().queue.lock();
let list = self let list = self
@@ -171,7 +68,7 @@ impl<'i> Convert<List<Raster<GPU>>, &'i WgpuExecutor> for List<Raster<CPU>> {
/// Converts single CPU raster to GPU by uploading to texture /// Converts single CPU raster to GPU by uploading to texture
impl<'i> Convert<Raster<GPU>, &'i WgpuExecutor> for Raster<CPU> { impl<'i> Convert<Raster<GPU>, &'i WgpuExecutor> for Raster<CPU> {
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<GPU> { fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<GPU> {
let device = &executor.context().device; let device = &executor.context().device;
let queue = executor.context().queue.lock(); let queue = executor.context().queue.lock();
let texture = upload_to_texture(device, &queue, &self); let texture = upload_to_texture(device, &queue, &self);
@@ -183,79 +80,19 @@ impl<'i> Convert<Raster<GPU>, &'i WgpuExecutor> for Raster<CPU> {
/// Passthrough conversion for CPU `List`s - no conversion needed /// Passthrough conversion for CPU `List`s - no conversion needed
impl<'i> Convert<List<Raster<CPU>>, &'i WgpuExecutor> for List<Raster<CPU>> { impl<'i> Convert<List<Raster<CPU>>, &'i WgpuExecutor> for List<Raster<CPU>> {
async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<CPU>> { fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<CPU>> {
self 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.
impl<'i> Convert<List<Raster<CPU>>, &'i WgpuExecutor> for List<Raster<GPU>> {
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> List<Raster<CPU>> {
let device = &executor.context().device;
let queue = &executor.context().queue;
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("batch_texture_download_encoder"),
});
let mut converters = Vec::new();
let mut rows_meta = Vec::new();
for row in self {
let (element, attributes) = row.into_parts();
converters.push(RasterGpuToRasterCpuConverter::new(device, &mut encoder, element));
rows_meta.push(Item::from_parts((), attributes));
}
queue.submit([encoder.finish()]);
let mut map_futures = Vec::new();
for converter in converters {
map_futures.push(converter.convert(device));
}
let map_results = futures::future::try_join_all(map_futures)
.await
.map_err(|_| "Failed to receive map result")
.expect("Buffer mapping communication failed");
map_results
.into_iter()
.zip(rows_meta)
.map(|(element, row)| {
let (_, attributes) = row.into_parts();
Item::from_parts(element, attributes)
})
.collect()
}
}
/// Converts single GPU raster to CPU by downloading texture data
impl<'i> Convert<Raster<CPU>, &'i WgpuExecutor> for Raster<GPU> {
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<CPU> {
let device = &executor.context().device;
let queue = &executor.context().queue;
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("single_texture_download_encoder"),
});
let converter = RasterGpuToRasterCpuConverter::new(device, &mut encoder, self);
queue.submit([encoder.finish()]);
converter.convert(device).await.expect("Failed to download texture data")
}
}
/// Uploads an raster texture from the CPU to the GPU. This is now deprecated and the Convert node should be used in the future. /// Uploads an raster texture from the CPU to the GPU. This is now deprecated and the Convert node should be used in the future.
/// ///
/// 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<'a, T: Convert<List<Raster<GPU>>, &'a WgpuExecutor>>(
_: 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: &'a WgpuExecutor,
) -> 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 }
+29 -334
View File
@@ -1,28 +1,23 @@
use crate::parsing::*; use crate::parsing::*;
use convert_case::{Case, Casing}; use convert_case::{Case, Casing};
use proc_macro2::TokenStream as TokenStream2; use proc_macro2::TokenStream as TokenStream2;
use quote::{ToTokens, format_ident, quote, quote_spanned}; use quote::{ToTokens, format_ident, quote};
use std::sync::atomic::AtomicU64; use std::sync::atomic::AtomicU64;
use syn::punctuated::Punctuated; use syn::punctuated::Punctuated;
use syn::spanned::Spanned; use syn::{Ident, PatIdent};
use syn::token::Comma;
use syn::{Error, Ident, PatIdent, Token, WhereClause, WherePredicate, parse_quote};
static NODE_ID: AtomicU64 = AtomicU64::new(0); static NODE_ID: AtomicU64 = AtomicU64::new(0);
pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn) -> syn::Result<TokenStream2> { pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn) -> syn::Result<TokenStream2> {
let ParsedNodeFn { let ParsedNodeFn {
vis,
attributes, attributes,
fn_name, fn_name,
struct_name, struct_name,
mod_name, mod_name,
fn_generics, fn_generics,
where_clause,
input, input,
output_type, output_type,
is_async, is_async,
fields, fields,
body,
description, description,
.. ..
} = parsed; } = parsed;
@@ -80,13 +75,10 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
// Combined struct generic parameters with bounds for struct definition // Combined struct generic parameters with bounds for struct definition
// struct MemoizeNode<T: Clone, Node0> // struct MemoizeNode<T: Clone, Node0>
let struct_generic_params: Vec<TokenStream2> = data_field_generics.iter().map(|gp| quote!(#gp)).chain(node_generics.iter().map(|id| quote!(#id))).collect(); let struct_generic_params: Vec<TokenStream2> = data_field_generics.iter().map(|gp| quote!(#gp)).chain(node_generics.iter().map(|id| quote!(#id))).collect();
let input_ident = &input.pat_ident;
let context_features = &input.context_features; let context_features = &input.context_features;
// Regular field idents and names (for function parameters) // Regular field idents and names (for function parameters)
let field_idents: Vec<_> = regular_fields.iter().map(|f| &f.pat_ident).collect(); let field_idents: Vec<_> = regular_fields.iter().map(|f| &f.pat_ident).collect();
let field_names: Vec<_> = field_idents.iter().map(|pat_ident| &pat_ident.ident).collect();
let regular_field_names: Vec<_> = regular_fields.iter().map(|f| &f.pat_ident.ident).collect(); let regular_field_names: Vec<_> = regular_fields.iter().map(|f| &f.pat_ident.ident).collect();
let data_field_names: Vec<_> = data_fields.iter().map(|f| &f.pat_ident.ident).collect(); let data_field_names: Vec<_> = data_fields.iter().map(|f| &f.pat_ident.ident).collect();
@@ -119,34 +111,12 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
quote! { pub(super) #name: #r#gen } quote! { pub(super) #name: #r#gen }
}); });
let struct_fields = data_field_defs.chain(regular_field_defs); let async_source = *is_async || crate::gcodegen::is_source_kernel(output_type);
let slot_value_type = crate::gcodegen::slot_value_type(output_type);
let mut future_idents = Vec::new(); let slot_field = async_source
.then(|| quote! { pub(super) slot: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<u64, Option<gcore::gpoll::GPoll<#slot_value_type>>>>> })
// Data fields get passed as references to the underlying function .into_iter();
let data_field_idents: Vec<_> = data_fields.iter().map(|f| &f.pat_ident).collect(); let struct_fields = data_field_defs.chain(regular_field_defs).chain(slot_field);
let data_field_types: Vec<_> = data_fields
.iter()
.map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => {
let ty = ty.clone();
quote!(&#ty)
}
_ => unreachable!("Data fields must be Regular types, not Node types"),
})
.collect();
// Regular fields have types passed to the function
let field_types: Vec<_> = regular_fields
.iter()
.map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
ParsedFieldType::Node(NodeParsedField { output_type, input_type, .. }) => match parsed.is_async {
true => parse_quote!(&'n impl #core_types::Node<'n, #input_type, Output = impl core::future::Future<Output=#output_type>>),
false => parse_quote!(&'n impl #core_types::Node<'n, #input_type, Output = #output_type>),
},
})
.collect();
// Only regular fields have UI metadata (data fields are internal state) // Only regular fields have UI metadata (data fields are internal state)
let widget_override: Vec<_> = regular_fields let widget_override: Vec<_> = regular_fields
@@ -233,39 +203,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
.collect(); .collect();
// Only eval regular fields (data fields are accessed directly as self.field_name) // Only eval regular fields (data fields are accessed directly as self.field_name)
let eval_args = regular_fields.iter().map(|field| {
let name = &field.pat_ident.ident;
match &field.ty {
ParsedFieldType::Regular { .. } => {
quote! { let #name = self.#name.eval(__input.clone()).await; }
}
ParsedFieldType::Node { .. } => {
quote! { let #name = &self.#name; }
}
}
});
// Only regular fields can have min/max constraints
let min_max_args = regular_fields.iter().map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { number_hard_min, number_hard_max, .. }) => {
let name = &field.pat_ident.ident;
let mut tokens = quote!();
if let Some(min) = number_hard_min {
tokens.extend(quote_spanned! {min.span()=>
let #name = #core_types::misc::Clampable::clamp_hard_min(#name, #min);
});
}
if let Some(max) = number_hard_max {
tokens.extend(quote_spanned! {max.span()=>
let #name = #core_types::misc::Clampable::clamp_hard_max(#name, #max);
});
}
tokens
}
ParsedFieldType::Node { .. } => quote!(),
});
let all_implementation_types = fields.iter().flat_map(|field| match &field.ty { let all_implementation_types = fields.iter().flat_map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { implementations, .. }) => implementations.iter().cloned().collect::<Vec<_>>(), ParsedFieldType::Regular(RegularParsedField { implementations, .. }) => implementations.iter().cloned().collect::<Vec<_>>(),
ParsedFieldType::Node(NodeParsedField { implementations, .. }) => implementations ParsedFieldType::Node(NodeParsedField { implementations, .. }) => implementations
@@ -275,61 +212,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
}); });
let all_implementation_types = all_implementation_types.chain(input.implementations.iter().cloned()); let all_implementation_types = all_implementation_types.chain(input.implementations.iter().cloned());
let input_type = &parsed.input.ty;
let mut clauses = Vec::new();
let mut clampable_clauses = Vec::new();
for (field, name) in regular_fields.iter().zip(node_generics.iter()) {
clauses.push(match (&field.ty, *is_async) {
(
ParsedFieldType::Regular(RegularParsedField {
ty, number_hard_min, number_hard_max, ..
}),
_,
) => {
let all_lifetime_ty = substitute_lifetimes(ty.clone(), "all");
let id = future_idents.len();
let fut_ident = format_ident!("F{}", id);
future_idents.push(fut_ident.clone());
// Add Clampable bound if this field uses hard_min or hard_max
if number_hard_min.is_some() || number_hard_max.is_some() {
// The bound applies to the Output type of the future, which is #ty
clampable_clauses.push(quote!(#ty: #core_types::misc::Clampable));
}
quote!(
#fut_ident: core::future::Future<Output = #ty> + #core_types::WasmNotSend + 'n,
for<'all> #all_lifetime_ty: #core_types::WasmNotSend,
#name: #core_types::Node<'n, #input_type, Output = #fut_ident> + #core_types::WasmNotSync
)
}
(ParsedFieldType::Node(NodeParsedField { input_type, output_type, .. }), true) => {
let id = future_idents.len();
let fut_ident = format_ident!("F{}", id);
future_idents.push(fut_ident.clone());
quote!(
#fut_ident: core::future::Future<Output = #output_type> + #core_types::WasmNotSend + 'n,
#name: #core_types::Node<'n, #input_type, Output = #fut_ident > + #core_types::WasmNotSync
)
}
(ParsedFieldType::Node { .. }, false) => unreachable!("Found node which takes an impl Node<> input but is not async"),
});
}
let where_clause = where_clause.clone().unwrap_or(WhereClause {
where_token: Token![where](output_type.span()),
predicates: Default::default(),
});
let mut struct_where_clause = where_clause.clone();
let extra_where: Punctuated<WherePredicate, Comma> = parse_quote!(
#(#clauses,)*
#(#clampable_clauses,)*
#output_type: 'n,
);
struct_where_clause.predicates.extend(extra_where);
// Only regular fields are parameters to new() // Only regular fields are parameters to new()
let new_args = node_generics.iter().zip(regular_field_names.iter()).map(|(r#gen, name)| { let new_args = node_generics.iter().zip(regular_field_names.iter()).map(|(r#gen, name)| {
quote! { #name: #r#gen } quote! { #name: #r#gen }
@@ -342,46 +224,16 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let regular_inits = regular_field_names.iter().map(|name| { let regular_inits = regular_field_names.iter().map(|name| {
quote! { #name } quote! { #name }
}); });
let all_field_inits = data_inits.chain(regular_inits); let slot_init = async_source.then(|| quote! { slot: Default::default() }).into_iter();
let all_field_inits = data_inits.chain(regular_inits).chain(slot_init);
let async_keyword = is_async.then(|| quote!(async));
let await_keyword = is_async.then(|| quote!(.await));
// Data fields may not implement Copy, PartialEq, etc., so only derive Debug and Clone // Data fields may not implement Copy, PartialEq, etc., so only derive Debug and Clone
let struct_derives = if data_fields.is_empty() { let struct_derives = if data_fields.is_empty() && !async_source {
quote!(#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]) quote!(#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)])
} else { } else {
quote!(#[derive(Debug, Clone)]) quote!(#[derive(Debug, Clone)])
}; };
// Generate serialize method if serialize attribute is specified
let serialize_impl = if let Some(serialize_fn) = &parsed.attributes.serialize {
let data_field_refs = data_field_names.iter().map(|name| quote!(&self.#name));
quote! {
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
#serialize_fn(#(#data_field_refs),*)
}
}
} else {
quote!()
};
let eval_impl = quote! {
type Output = #core_types::registry::DynFuture<'n, #output_type>;
#[inline]
fn eval(&'n self, __input: #input_type) -> Self::Output {
Box::pin(async move {
use #core_types::misc::Clampable;
#(#eval_args)*
#(#min_max_args)*
self::#fn_name(__input #(, &self.#data_field_names)* #(, #regular_field_names)*) #await_keyword
})
}
#serialize_impl
};
let identifier = format_ident!("{}_proto_ident", fn_name); let identifier = format_ident!("{}_proto_ident", fn_name);
let identifier_path = match parsed.attributes.path.as_ref() { let identifier_path = match parsed.attributes.path.as_ref() {
Some(path) => { Some(path) => {
@@ -391,8 +243,18 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
None => quote!(std::module_path!()), None => quote!(std::module_path!()),
}; };
let register_node_impl = generate_register_node_impl(parsed, &field_names, &struct_name, &identifier)?; let registry_name = format_ident!("__node_registry_{}_{}", NODE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst), struct_name);
let register_node_impl = quote! {
#[cfg(target_family = "wasm")]
#[unsafe(no_mangle)]
extern "C" fn #registry_name() {
register_metadata();
}
};
let import_name = format_ident!("_IMPORT_STUB_{}", mod_name.to_string().to_case(Case::UpperSnake)); let import_name = format_ident!("_IMPORT_STUB_{}", mod_name.to_string().to_case(Case::UpperSnake));
let gnode = crate::gcodegen::generate_gnode_code(crate_ident, parsed)?;
let gnode_in_mod = gnode.in_mod;
let gnode_top_level = gnode.top_level;
let properties = &attributes.properties_string.as_ref().map(|value| quote!(Some(#value))).unwrap_or(quote!(None)); let properties = &attributes.properties_string.as_ref().map(|value| quote!(Some(#value))).unwrap_or(quote!(None));
let memoize_flag = attributes.memoize; let memoize_flag = attributes.memoize;
@@ -428,17 +290,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
Ok(quote! { Ok(quote! {
#(#description_doc_attrs)* #(#description_doc_attrs)*
#[inline] #gnode_top_level
#[allow(clippy::too_many_arguments)]
#vis #async_keyword fn #fn_name <'n, #(#fn_generics,)*> (#input_ident: #input_type #(, #data_field_idents: #data_field_types)* #(, #field_idents: #field_types)*) -> #output_type #where_clause #body
#cfg
#[automatically_derived]
impl<'n, #(#fn_generics,)* #(#node_generics,)* #(#future_idents,)*> #core_types::Node<'n, #input_type> for #mod_name::#struct_name<#(#struct_type_params,)*>
#struct_where_clause
{
#eval_impl
}
#cfg #cfg
const fn #identifier() -> #core_types::ProtoNodeIdentifier { const fn #identifier() -> #core_types::ProtoNodeIdentifier {
@@ -458,10 +310,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
mod #mod_name { mod #mod_name {
use super::*; use super::*;
use #core_types as gcore; use #core_types as gcore;
use gcore::{Node, NodeIOTypes, concrete, fn_type, fn_type_fut, future, ProtoNodeIdentifier, WasmNotSync, NodeIO, ContextFeature}; use gcore::{ContextFeature, concrete};
use gcore::value::ClonedNode; use gcore::registry::{NodeMetadata, FieldMetadata, NODE_METADATA, RegistryValueSource, RegistryWidgetOverride};
use gcore::ops::TypeNode;
use gcore::registry::{NodeMetadata, FieldMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, DynFuture, TypeErasedBox, PanicNode, RegistryValueSource, RegistryWidgetOverride};
use gcore::ctor::ctor; use gcore::ctor::ctor;
// Use the types specified in the implementation // Use the types specified in the implementation
@@ -484,6 +334,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
} }
} }
#gnode_in_mod
#register_node_impl #register_node_impl
#[cfg_attr(not(target_family = "wasm"), ctor)] #[cfg_attr(not(target_family = "wasm"), ctor)]
@@ -619,167 +471,10 @@ fn generate_phantom_data<'a>(fn_generics: impl Iterator<Item = &'a crate::Generi
(fn_generic_params, phantom_data_declerations) (fn_generic_params, phantom_data_declerations)
} }
fn generate_register_node_impl(parsed: &ParsedNodeFn, field_names: &[&Ident], struct_name: &Ident, identifier: &Ident) -> Result<TokenStream2, Error> {
// On native, `register_node` and `register_metadata` run automatically via `#[ctor]`.
// On Wasm, `ctor` isn't available, so this `extern "C"` fn is invoked from JS to register the same way.
// `skip_impl` nodes don't generate a `register_node`, so the shim calls only `register_metadata` for them.
let registry_name = format_ident!("__node_registry_{}_{}", NODE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst), struct_name);
let register_node_call = if parsed.attributes.skip_impl { quote!() } else { quote!(register_node();) };
let wasm_shim = quote! {
#[cfg(target_family = "wasm")]
#[unsafe(no_mangle)]
extern "C" fn #registry_name() {
#register_node_call
register_metadata();
}
};
if parsed.attributes.skip_impl {
return Ok(wasm_shim);
}
let mut constructors = Vec::new();
let unit = parse_quote!(gcore::Context);
let regular_fields: Vec<_> = parsed.fields.iter().filter(|f| !f.is_data_field).collect();
let parameter_types: Vec<_> = regular_fields
.iter()
.map(|field| {
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { implementations, ty, .. }) => {
if !implementations.is_empty() {
implementations.iter().map(|ty| (&unit, ty)).collect()
} else {
vec![(&unit, ty)]
}
}
ParsedFieldType::Node(NodeParsedField {
implementations,
input_type,
output_type,
..
}) => {
if !implementations.is_empty() {
implementations.iter().map(|impl_| (&impl_.input, &impl_.output)).collect()
} else {
vec![(input_type, output_type)]
}
}
}
.into_iter()
.map(|(input, out)| (substitute_lifetimes(input.clone(), "_"), substitute_lifetimes(out.clone(), "_")))
.collect::<Vec<_>>()
})
.collect();
let max_implementations = parameter_types.iter().map(|x| x.len()).chain([parsed.input.implementations.len().max(1)]).max();
for i in 0..max_implementations.unwrap_or(0) {
let mut temp_constructors = Vec::new();
let mut temp_node_io = Vec::new();
let mut panic_node_types = Vec::new();
for (j, types) in parameter_types.iter().enumerate() {
let field_name = field_names[j];
let (input_type, output_type) = &types[i.min(types.len() - 1)];
let node = matches!(regular_fields[j].ty, ParsedFieldType::Node { .. });
let downcast_node = quote!(
let #field_name: DowncastBothNode<#input_type, #output_type> = DowncastBothNode::new(args[#j].clone());
);
if node && !parsed.is_async {
return Err(Error::new_spanned(&parsed.fn_name, "Node needs to be async if you want to use lambda parameters"));
}
temp_constructors.push(downcast_node);
temp_node_io.push(quote!(fn_type_fut!(#input_type, #output_type, alias: #output_type)));
panic_node_types.push(quote!(#input_type, DynFuture<'static, #output_type>));
}
let input_type = match parsed.input.implementations.is_empty() {
true => parsed.input.ty.clone(),
false => parsed.input.implementations[i.min(parsed.input.implementations.len() - 1)].clone(),
};
constructors.push(quote!(
(
|args| {
Box::pin(async move {
#(#temp_constructors;)*
let node = #struct_name::new(#(#field_names,)*);
// try polling futures
let any: DynAnyNode<#input_type, _, _> = DynAnyNode::new(node);
Box::new(any) as TypeErasedBox<'_>
})
}, {
let node = #struct_name::new(#(PanicNode::<#panic_node_types>::new(),)*);
let params = vec![#(#temp_node_io,)*];
let mut node_io = NodeIO::<'_, #input_type>::to_async_node_io(&node, params);
node_io
}
)
));
}
let native = quote! {
#[cfg_attr(not(target_family = "wasm"), ctor)]
fn register_node() {
let mut registry = NODE_REGISTRY.lock().unwrap();
registry.insert(
#identifier(),
vec![
#(#constructors,)*
]
);
}
};
if cfg!(feature = "disable-registration") {
return Ok(native);
}
Ok(quote! {
#native
#wasm_shim
})
}
use crate::crate_ident::CrateIdent; use crate::crate_ident::CrateIdent;
use crate::shader_nodes::{ShaderCodegen, ShaderTokens}; use crate::shader_nodes::{ShaderCodegen, ShaderTokens};
use syn::visit_mut::VisitMut; use syn::visit_mut::VisitMut;
use syn::{GenericArgument, Lifetime, Type}; use syn::{Lifetime, Type};
struct LifetimeReplacer(&'static str);
impl VisitMut for LifetimeReplacer {
fn visit_lifetime_mut(&mut self, lifetime: &mut Lifetime) {
lifetime.ident = Ident::new(self.0, lifetime.ident.span());
}
fn visit_type_mut(&mut self, ty: &mut Type) {
match ty {
Type::Reference(type_reference) => {
if let Some(lifetime) = &mut type_reference.lifetime {
self.visit_lifetime_mut(lifetime);
}
self.visit_type_mut(&mut type_reference.elem);
}
_ => syn::visit_mut::visit_type_mut(self, ty),
}
}
fn visit_generic_argument_mut(&mut self, arg: &mut GenericArgument) {
if let GenericArgument::Lifetime(lifetime) = arg {
self.visit_lifetime_mut(lifetime);
} else {
syn::visit_mut::visit_generic_argument_mut(self, arg);
}
}
}
#[must_use]
fn substitute_lifetimes(mut ty: Type, lifetime: &'static str) -> Type {
LifetimeReplacer(lifetime).visit_type_mut(&mut ty);
ty
}
/// Get only the necessary generics. /// Get only the necessary generics.
struct FilterUsedGenerics { struct FilterUsedGenerics {
@@ -862,7 +557,7 @@ impl FilterUsedGenerics {
} }
/// Check if a type contains a reference to a specific identifier (e.g., a generic type parameter) /// Check if a type contains a reference to a specific identifier (e.g., a generic type parameter)
fn type_contains_ident(ty: &Type, ident: &Ident) -> bool { pub(crate) fn type_contains_ident(ty: &Type, ident: &Ident) -> bool {
struct IdentChecker<'a> { struct IdentChecker<'a> {
target: &'a Ident, target: &'a Ident,
found: bool, found: bool,
+661
View File
@@ -0,0 +1,661 @@
use crate::crate_ident::CrateIdent;
use crate::parsing::*;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::visit::Visit;
use syn::{GenericArgument, GenericParam, Ident, Lifetime, PathArguments, Type, TypeParam, TypeParamBound};
pub(crate) struct GNodeTokens {
pub(crate) in_mod: TokenStream2,
pub(crate) top_level: TokenStream2,
}
pub(crate) fn generate_gnode_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn) -> syn::Result<GNodeTokens> {
let core_types = crate_ident.gcore()?;
let ctx_param = context_param(parsed);
let ctx_ident = match ctx_param {
Some(ctx_param) => ctx_param.ident.clone(),
None => format_ident!("__Ctx"),
};
let async_fn = parsed.is_async;
let future_kernel = is_source_kernel(&parsed.output_type);
let async_source = async_fn || future_kernel;
if async_fn && parsed.fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_))) {
return Ok(GNodeTokens {
in_mod: quote!(),
top_level: quote!(),
});
}
let snapshot_ctx = async_fn && matches!(&parsed.input.ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "CtxSnapshot"));
let mut ctx_bounds: Vec<TokenStream2> = match ctx_param {
Some(ctx_param) => ctx_param
.bounds
.iter()
.filter_map(|bound| match bound {
TypeParamBound::Lifetime(_) => None,
bound => Some(desugar_extract_lifetime(bound, core_types)),
})
.collect(),
None => vec![quote!(#core_types::Ctx)],
};
if async_source {
ctx_bounds.push(quote!(#core_types::CacheHash));
}
if snapshot_ctx {
ctx_bounds.extend([
quote!(#core_types::context::DeriveCtx),
quote!(#core_types::context::ExtractFootprint),
quote!(#core_types::context::ExtractRealTime),
quote!(#core_types::context::ExtractAnimationTime),
quote!(#core_types::context::ExtractPointerPosition),
quote!(#core_types::context::ExtractIndex),
quote!(#core_types::context::ExtractPosition),
]);
}
let derives = ctx_param.is_some_and(|ctx_param| {
ctx_param.bounds.iter().any(|bound| match bound {
TypeParamBound::Trait(trait_bound) => trait_bound.path.segments.last().is_some_and(|segment| segment.ident == "DeriveCtx"),
_ => false,
})
});
let ctx_generic = match ctx_bounds.is_empty() {
true => quote!(#ctx_ident),
false => quote!(#ctx_ident: #(#ctx_bounds)+*),
};
let mut generics: Vec<TokenStream2> = parsed
.fn_generics
.iter()
.map(|param| match param {
GenericParam::Type(type_param) if Some(&type_param.ident) == ctx_param.map(|ctx_param| &ctx_param.ident) => ctx_generic.clone(),
param => quote!(#param),
})
.collect();
if ctx_param.is_none() {
generics.push(ctx_generic);
}
let fn_name = &parsed.fn_name;
let mod_name = format_ident!("_{}_mod", parsed.mod_name);
let struct_name = format_ident!("{}Node", parsed.struct_name);
let output_type = &parsed.output_type;
let trait_output = slot_value_type(&parsed.output_type);
let raw_lazy = matches!(kernel_kind(&parsed.output_type), KernelKind::Poll(_));
let injected_name = |ident: &Ident| async_source && (ident == "_runtime" || ident == "_source");
let where_predicates: Vec<TokenStream2> = parsed.where_clause.iter().flat_map(|clause| clause.predicates.iter()).map(|predicate| quote!(#predicate)).collect();
let (data_fields, regular_fields): (Vec<_>, Vec<_>) = parsed.fields.iter().partition(|field| field.is_data_field);
let data_field_generic_idents: Vec<Ident> = parsed
.fn_generics
.iter()
.filter_map(|generic| match generic {
GenericParam::Type(type_param) => Some(type_param.ident.clone()),
_ => None,
})
.filter(|ident| {
data_fields.iter().any(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => crate::codegen::type_contains_ident(ty, ident),
_ => false,
})
})
.collect();
let node_generics: Vec<Ident> = regular_fields.iter().enumerate().map(|(index, _)| format_ident!("Node{}", index)).collect();
let struct_type_params: Vec<Ident> = data_field_generic_idents.iter().cloned().chain(node_generics.iter().cloned()).collect();
let data_names: Vec<&Ident> = data_fields.iter().map(|field| &field.pat_ident.ident).collect();
let data_params = data_fields.iter().map(|field| {
let pat = &field.pat_ident;
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
unreachable!("data fields are regular types");
};
quote!(#pat: &#ty)
});
let lazy_bound = |output_type: &Type| match derives {
true => quote!(for<'__derived> #core_types::gnode::GNode<#core_types::context::Derived<'__derived, #ctx_ident>, Output = #output_type>),
false => quote!(#core_types::gnode::GNode<#ctx_ident, Output = #output_type>),
};
let kernel_params = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).map(|field| {
let pat = &field.pat_ident;
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(#pat: #ty),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) if raw_lazy => {
let bound = lazy_bound(output_type);
quote!(#pat: &impl #bound)
}
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
let bound = lazy_bound(output_type);
quote!(#pat: #core_types::gnode::LazyInput<'_, impl #bound>)
}
}
});
let node_bounds = regular_fields.iter().zip(&node_generics).map(|(field, node_generic)| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(#node_generic: #core_types::gnode::GNode<#ctx_ident, Output = #ty>),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
let bound = lazy_bound(output_type);
quote!(#node_generic: #bound)
}
});
let async_bounds = match (async_fn, future_kernel) {
(false, false) => Vec::new(),
(false, true) => vec![quote!(#trait_output: Clone)],
(true, _) => {
let output_clone = std::iter::once(quote!(#trait_output: Clone));
let value_clones = regular_fields.iter().filter_map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => Some(quote!(#ty: Clone)),
_ => None,
});
let data_clones = data_fields.iter().filter_map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => Some(quote!(#ty: Clone)),
_ => None,
});
output_clone.chain(value_clones).chain(data_clones).collect()
}
};
let clampable_bounds = regular_fields.iter().filter_map(|field| {
let ParsedFieldType::Regular(RegularParsedField { ty, number_hard_min, number_hard_max, .. }) = &field.ty else {
return None;
};
(number_hard_min.is_some() || number_hard_max.is_some()).then(|| quote!(#ty: #core_types::misc::Clampable))
});
let eval_values = regular_fields.iter().enumerate().map(|(index, field)| {
let name = &field.pat_ident.ident;
match &field.ty {
ParsedFieldType::Regular(_) => quote! {
let #name = match __cell.eval_input(#index, &self.#name, __input) {
Ok(value) => value,
Err(interrupt) => return interrupt.into(),
};
},
ParsedFieldType::Node(_) if raw_lazy => quote!(),
ParsedFieldType::Node(_) => quote! {
let #name = #core_types::gnode::LazyInput::new(&self.#name, &__cell, #index);
},
}
});
let clamps = regular_fields.iter().filter_map(|field| {
let ParsedFieldType::Regular(RegularParsedField { number_hard_min, number_hard_max, .. }) = &field.ty else {
return None;
};
let name = &field.pat_ident.ident;
let mut tokens = quote!();
if let Some(min) = number_hard_min {
tokens.extend(quote!(let #name = #core_types::misc::Clampable::clamp_hard_min(#name, #min);));
}
if let Some(max) = number_hard_max {
tokens.extend(quote!(let #name = #core_types::misc::Clampable::clamp_hard_max(#name, #max);));
}
(!tokens.is_empty()).then_some(tokens)
});
let call_args = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).map(|field| {
let name = &field.pat_ident.ident;
match &field.ty {
ParsedFieldType::Node(_) if raw_lazy => quote!(&self.#name),
_ => quote!(#name),
}
});
let value_field_names: Vec<&Ident> = regular_fields
.iter()
.filter(|field| matches!(field.ty, ParsedFieldType::Regular(_)))
.map(|field| &field.pat_ident.ident)
.collect();
let extent_impl = match &parsed.attributes.extent {
Some(path) => quote! {
fn extent(&self, __input: &#ctx_ident) -> #core_types::gpoll::GPoll<#core_types::gpoll::Extent> {
#path(self, __input)
}
},
None if value_field_names.is_empty() => quote!(),
None => {
let first = value_field_names[0];
let mut meet = quote!(self.#first.extent(__input));
for name in &value_field_names[1..] {
meet = quote!(#core_types::gpoll::Extent::meet(#meet, self.#name.extent(__input)));
}
quote! {
fn extent(&self, __input: &#ctx_ident) -> #core_types::gpoll::GPoll<#core_types::gpoll::Extent> {
#meet
}
}
}
};
let batch_impl = match &parsed.attributes.batch {
Some(path) => quote! {
fn eval_batch<'__batch>(
&self,
__input: &'__batch #ctx_ident,
__range: ::std::ops::Range<u64>,
__scratch: Option<&'__batch mut [::std::mem::MaybeUninit<Self::Output>]>,
) -> #core_types::gnode::BatchStatus<'__batch, Self::Output>
where
#ctx_ident: #core_types::context::InjectIndex + Copy,
{
#path(self, __input, __range, __scratch)
}
},
None => quote!(),
};
let ctx_pat = &parsed.input.pat_ident;
let fn_where = &parsed.where_clause;
let body = &parsed.body;
let vis = &parsed.vis;
let kernel_fields: Vec<&&ParsedField> = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).collect();
let kernel = match async_fn {
false => quote! {
#[allow(clippy::too_many_arguments)]
#vis fn #fn_name<#(#generics,)*>(#ctx_pat: &#ctx_ident #(, #data_params)* #(, #kernel_params)*) -> #output_type #fn_where #body
},
true => {
let kernel_generics = parsed.fn_generics.iter().filter(|param| match param {
GenericParam::Type(type_param) => Some(&type_param.ident) != ctx_param.map(|ctx_param| &ctx_param.ident),
_ => true,
});
let snapshot_param = snapshot_ctx.then(|| quote!(#ctx_pat: #core_types::context::CtxSnapshot)).into_iter();
let data_kernel_params = data_fields.iter().map(|field| {
let pat = &field.pat_ident;
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
unreachable!("data fields are regular types");
};
quote!(#pat: #ty)
});
let value_kernel_params = kernel_fields.iter().map(|field| {
let pat = &field.pat_ident;
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
unreachable!("async source fields are eager values");
};
quote!(#pat: #ty)
});
let params = snapshot_param.chain(data_kernel_params).chain(value_kernel_params);
quote! {
#[allow(clippy::too_many_arguments)]
#vis async fn #fn_name<#(#kernel_generics,)*>(#(#params),*) -> #output_type #fn_where #body
}
}
};
let cell_constructor = match parsed.attributes.no_partial {
true => quote!(#core_types::gnode::StatusCell::no_partial()),
false => quote!(#core_types::gnode::StatusCell::new()),
};
let kernel_call = quote!(self::#fn_name(__input #(, &self.#data_names)* #(, #call_args)*));
let lift = match kernel_kind(&parsed.output_type) {
KernelKind::Interrupt(_) => quote! {
match #kernel_call {
Ok(value) => __cell.finish(value),
Err(interrupt) => interrupt.into(),
}
},
KernelKind::Poll(_) => quote!(__cell.merge(#kernel_call)),
_ => quote!(__cell.finish(#kernel_call)),
};
let placeholder_value_names: Vec<&Ident> = kernel_fields
.iter()
.filter(|field| matches!(field.ty, ParsedFieldType::Regular(_)))
.map(|field| &field.pat_ident.ident)
.collect();
let inflight = match &parsed.attributes.placeholder {
Some(path) => quote!(__cell.merge(#core_types::gpoll::GPoll::Partial(#path(#(&#placeholder_value_names),*)))),
None => quote!(#core_types::gpoll::GPoll::Pending),
};
let slot_check = quote! {
let __key = #core_types::wire::cache_key(__input);
{
let __entries = self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(__state) = __entries.get(&__key) {
return match __state {
Some(value) => __cell.merge(value.clone()),
None => #inflight,
};
}
}
};
let future_completion = |payload: &Type| match kernel_kind(payload) {
KernelKind::Poll(_) => quote!(__future.await),
KernelKind::Interrupt(_) => quote! {
match __future.await {
Ok(value) => #core_types::gpoll::GPoll::Final(value),
Err(interrupt) => interrupt.into(),
}
},
_ => quote!(#core_types::gpoll::GPoll::Final(__future.await)),
};
let eval_tail = match (async_fn, future_kernel) {
(false, false) => lift,
(true, _) => {
let kernel_value_names: Vec<&Ident> = kernel_fields.iter().map(|field| &field.pat_ident.ident).collect();
let snapshot_binding = snapshot_ctx.then(|| quote!(let __snapshot = #core_types::context::CtxSnapshot::capture(__input);)).into_iter();
let snapshot_arg = snapshot_ctx.then(|| quote!(__snapshot)).into_iter();
let future_args = snapshot_arg
.chain(data_names.iter().map(|name| quote!(self.#name.clone())))
.chain(kernel_value_names.iter().map(|name| quote!(#name.clone())));
let completion = future_completion(&parsed.output_type);
quote! {
#slot_check
self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, None);
let __slot = std::sync::Arc::clone(&self.slot);
#(#snapshot_binding)*
let __future = self::#fn_name(#(#future_args),*);
_runtime.0.spawn(_source, Box::pin(async move {
let __value = #completion;
__slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, Some(__value));
}));
#inflight
}
}
(false, true) => {
let (placeholder_binding, spawn_return) = match &parsed.attributes.placeholder {
Some(path) => (
quote!(let __placeholder = #path(#(&#placeholder_value_names),*);),
quote!(__cell.merge(#core_types::gpoll::GPoll::Partial(__placeholder))),
),
None => (quote!(), quote!(#core_types::gpoll::GPoll::Pending)),
};
let acquire = match kernel_kind(&parsed.output_type) {
KernelKind::FutureInterrupt(_) => quote! {
let __future = match #kernel_call {
Ok(future) => future,
Err(interrupt) => return interrupt.into(),
};
},
_ => quote!(let __future = #kernel_call;),
};
let payload = match kernel_kind(&parsed.output_type) {
KernelKind::Future(payload) | KernelKind::FutureInterrupt(payload) => payload,
_ => unreachable!("guarded by future_kernel"),
};
let completion = future_completion(&payload);
quote! {
#slot_check
#placeholder_binding
#acquire
self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, None);
let __slot = std::sync::Arc::clone(&self.slot);
_runtime.0.spawn(_source, Box::pin(async move {
let __value = #completion;
__slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, Some(__value));
}));
#spawn_return
}
}
};
let wire = entries_tokens(parsed, &struct_name, &data_field_generic_idents, &regular_fields);
let cfg = crate::shader_nodes::modify_cfg(&parsed.attributes);
let wire_reexport = match wire.is_empty() {
true => quote!(),
false => {
let entries_name = format_ident!("{}_entries", fn_name);
quote! {
#cfg
#[doc(hidden)]
pub use #mod_name::#entries_name;
}
}
};
let top_level = quote! {
#wire_reexport
#cfg
#[automatically_derived]
impl<#(#generics,)* #(#node_generics,)*> #core_types::gnode::GNode<#ctx_ident> for #mod_name::#struct_name<#(#struct_type_params,)*>
where
#(#node_bounds,)*
#(#clampable_bounds,)*
#(#async_bounds,)*
#(#where_predicates,)*
{
type Output = #trait_output;
fn eval(&self, __input: &#ctx_ident) -> #core_types::gpoll::GPoll<Self::Output> {
let __cell = #cell_constructor;
#(#eval_values)*
#(#clamps)*
#eval_tail
}
#extent_impl
#batch_impl
}
};
Ok(GNodeTokens {
in_mod: wire,
top_level: quote! {
#kernel
#top_level
},
})
}
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(_))
}
enum KernelKind {
Plain,
Interrupt(Type),
Poll(Type),
Future(Type),
FutureInterrupt(Type),
}
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!(()))
}
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_some_and(|segment| segment.ident == "Interrupt") {
return plain();
}
if let Type::Path(inner_path) = inner {
if let Some(inner_segment) = inner_path.path.segments.last() {
if inner_segment.ident == "SourceFuture" {
return KernelKind::FutureInterrupt(source_future_payload(inner_segment));
}
}
}
KernelKind::Interrupt(inner.clone())
}
_ => plain(),
}
}
fn context_param<'a>(parsed: &'a ParsedNodeFn) -> Option<&'a 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,
})
}
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
}
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>)
}
fn entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
if !data_field_generic_idents.is_empty() {
return quote!();
}
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 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 entries = rows.iter().map(|row| {
let types = row.iter();
let boxed_types = row.iter().map(|ty| quote!(::std::boxed::Box<gcore::wire::ErasedGNode<#ty>>));
let output = quote!(<#struct_name<#(#boxed_types),*> as gcore::gnode::GNode<gcore::context::ContextImpl<'static>>>::Output);
let downcasts = names.iter().zip(row.iter()).map(|(name, ty)| {
quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;)
});
quote! {
gcore::wire::RegistryEntry {
io: gcore::wire::NodeIoRecord {
inputs: vec![#(gcore::concrete!(#types)),*],
output: gcore::concrete!(#output),
},
wire: |inputs| {
if inputs.len() != #arity {
return Err(gcore::wire::WireError::Arity { expected: #arity, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
#(#downcasts)*
Ok(gcore::wire::EdgeHandle::new(::std::boxed::Box::new(#struct_name::new(#(#names),*)) as ::std::boxed::Box<gcore::wire::ErasedGNode<#output>>))
},
}
}
});
quote! {
pub fn #entries_name() -> ::std::vec::Vec<gcore::wire::RegistryEntry> {
vec![#(#entries),*]
}
}
}
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(),
)
}
+1
View File
@@ -7,6 +7,7 @@ mod buffer_struct;
mod codegen; mod codegen;
mod crate_ident; mod crate_ident;
mod derive_choice_type; mod derive_choice_type;
mod gcodegen;
mod parsing; mod parsing;
mod shader_nodes; mod shader_nodes;
mod validation; mod validation;
+136 -1
View File
@@ -56,6 +56,14 @@ 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,
} }
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
@@ -311,6 +319,10 @@ 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 content = input; let content = input;
// let content; // let content;
@@ -453,13 +465,63 @@ 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, ...)]
"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 +555,10 @@ impl Parse for NodeFnAttributes {
serialize, serialize,
memoize, memoize,
inject_scope, inject_scope,
placeholder,
extent,
batch,
no_partial,
}) })
} }
} }
@@ -931,6 +997,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.is_async || crate::gcodegen::is_source_kernel(&parsed_node.output_type) {
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 +1028,43 @@ 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 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,
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,
};
self.fields.push(hidden_field(
"_runtime",
parse_quote!(#core_types::runtime::RuntimeHandle),
ParsedValueSource::Scope(parse_quote!("graphene_std::runtime::RuntimeNode")),
));
self.fields.push(hidden_field("_source", parse_quote!(#core_types::SourceId), ParsedValueSource::None));
}
} }
#[cfg(test)] #[cfg(test)]
@@ -1082,6 +1189,10 @@ 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,
}, },
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()),
@@ -1152,6 +1263,10 @@ 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,
}, },
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()),
@@ -1236,6 +1351,10 @@ 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,
}, },
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()),
@@ -1302,6 +1421,10 @@ 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,
}, },
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()),
@@ -1380,6 +1503,10 @@ 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,
}, },
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()),
@@ -1461,6 +1588,10 @@ 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,
}, },
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()),
@@ -1527,6 +1658,10 @@ 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,
}, },
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,9 @@ 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!(std::sync::Arc<WgpuExecutor>),
exposed: true, exposed: true,
value_source: ParsedValueSource::Scope(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode")), value_source: ParsedValueSource::Scope(parse_quote!("graphene_std::platform_application_io::WgpuExecutorArcNode")),
number_soft_min: None, number_soft_min: None,
number_soft_max: None, number_soft_max: None,
number_hard_min: None, number_hard_min: None,
@@ -287,7 +287,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 +305,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 +314,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(),
+47
View File
@@ -11,6 +11,7 @@ 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,
]; ];
for validator in validators { for validator in validators {
@@ -20,6 +21,52 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
Ok(()) Ok(())
} }
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::gcodegen::is_source_kernel(&parsed.output_type);
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"
);
}
}
}
let ctx_ident = match &parsed.input.ty {
Type::Path(path) => path.path.get_ident(),
_ => None,
};
for param in &parsed.fn_generics {
let GenericParam::Type(type_param) = param else { continue };
if Some(&type_param.ident) == ctx_ident {
continue;
}
if crate::codegen::type_contains_ident(&parsed.output_type, &type_param.ident) {
emit_error!(
parsed.output_type.span(),
"async source nodes do not support generic output types yet; the slot map needs the output type stated per implementation row, which is not wired up until a node requires it"
);
}
}
}
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 {
+25 -40
View File
@@ -3,15 +3,12 @@ use crate::brush_stroke::{BrushStroke, BrushStyle};
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 core_types::Ctx;
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,13 @@ 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| blend_colors(a, b, mask_blend_mode, 1.))
let blit_node = BlitNode::new( .into_iter()
FutureWrapperNode::new(ClonedNode::new(brush_texture)), .next()
FutureWrapperNode::new(ClonedNode::new(positions)), .unwrap_or_default();
FutureWrapperNode::new(ClonedNode::new(blend_params)),
);
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 +396,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 +419,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,5 +1,6 @@
use core::f64; use core::f64;
use core_types::context::{CloneVarArgs, Context, ContextFeatures, Ctx, ExtractAll}; use core_types::context::{Context, ContextFeatures, Ctx, DeriveCtx};
use core_types::gpoll::GPoll;
use core_types::list::{AttributeDyn, AttributeValueDyn, List, ListDyn}; use core_types::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
use core_types::transform::Footprint; use core_types::transform::Footprint;
use core_types::uuid::NodeId; use core_types::uuid::NodeId;
@@ -12,8 +13,8 @@ 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( #[implementations(
Context -> (), Context -> (),
@@ -41,13 +42,12 @@ async fn context_modification<T>(
Context -> AttributeValueDyn, Context -> AttributeValueDyn,
Context -> ListDyn, Context -> ListDyn,
)] )]
value: impl Node<Context<'static>, Output = T>, value: impl Node<Context<'_>, 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, features_to_keep: ContextFeatures,
) -> T { ) -> GPoll<T> {
let new_context = OwnedContextImpl::from_flags(ctx, features_to_keep); let scope = ctx.scope().nullified(features_to_keep);
value.eval(&ctx.nullified(features_to_keep, &scope))
value.eval(Some(new_context.into())).await
} }
#[cfg(test)] #[cfg(test)]
+13 -10
View File
@@ -1,4 +1,4 @@
use core_types::WasmNotSend; use core_types::gpoll::Interrupt;
use core_types::graphene_hash::CacheHash; use core_types::graphene_hash::CacheHash;
use core_types::memo::*; use core_types::memo::*;
use std::hash::DefaultHasher; use std::hash::DefaultHasher;
@@ -10,7 +10,7 @@ use std::sync::Mutex;
/// ///
/// 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 the last evaluated data that flowed through this node and immediately returns that data 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), skip_impl)]
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<I: CacheHash, T: Clone>(input: I, #[data] cache: Arc<Mutex<Option<(u64, T)>>>, content: impl Node<I, Output = T>) -> Result<T, Interrupt> {
// Caches the output of a given node called with a specific input. // Caches the output of a given node called with a specific input.
// //
// A cache miss occurs when the Option is None. In this case, the node evaluates the inner node and memoizes (stores) the result. // A cache miss occurs when the Option is None. In this case, the node evaluates the inner node and memoizes (stores) the result.
@@ -24,28 +24,31 @@ async fn memoize<I: CacheHash + Send + 'n, T: Clone + WasmNotSend>(input: I, #[d
let hash = hasher.finish(); let hash = hasher.finish();
if let Some(data) = cache.lock().as_ref().unwrap().as_ref().and_then(|data| (data.0 == hash).then_some(data.1.clone())) { if let Some(data) = cache.lock().as_ref().unwrap().as_ref().and_then(|data| (data.0 == hash).then_some(data.1.clone())) {
return data; return Ok(data);
} }
let value = content.eval(input).await; let value = content.eval(input)?;
*cache.lock().unwrap() = Some((hash, value.clone())); *cache.lock().unwrap() = Some((hash, value.clone()));
value Ok(value)
} }
type MonitorValue<I, T> = Arc<Mutex<Option<Arc<IORecord<I, T>>>>>; type MonitorValue<I, T> = Arc<Mutex<Option<Arc<IORecord<I, T>>>>>;
/// 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"), skip_impl)]
async fn monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>( fn monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>(
input: I, input: I,
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
#[data] #[data]
io: MonitorValue<I, T>, io: MonitorValue<I, T>,
content: impl Node<I, Output = T>, content: impl Node<I, Output = T>,
) -> T { ) -> Result<T, Interrupt> {
let output = content.eval(input.clone()).await; let output = content.eval(input)?;
*io.lock().unwrap() = Some(Arc::new(IORecord { input, output: output.clone() })); *io.lock().unwrap() = Some(Arc::new(IORecord {
output input: input.clone(),
output: output.clone(),
}));
Ok(output)
} }
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<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>(io: &MonitorValue<I, T>) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
+2 -2
View File
@@ -16,8 +16,8 @@ fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty
} }
#[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 + ExtractFootprint, value: T, converter: C, _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)
} }
#[cfg(test)] #[cfg(test)]
+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, ExtractFootprint};
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 + ExtractFootprint + DeriveCtx,
/// 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
@@ -2,7 +2,8 @@ use core_types::bounds::{BoundingBox, RenderBoundingBox};
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::gpoll::Interrupt;
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()
} }
@@ -10,6 +10,8 @@ use core_types::math::bbox::Bbox;
use core_types::transform::Footprint; use core_types::transform::Footprint;
#[cfg(target_family = "wasm")] #[cfg(target_family = "wasm")]
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, WasmNotSend}; use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, WasmNotSend};
use core_types::gpoll::GPoll;
use core_types::runtime::SourceFuture;
use core_types::{Color, Ctx}; use core_types::{Color, Ctx};
pub use graph_craft::application_io::resource::{Resource, ResourceHash}; pub use graph_craft::application_io::resource::{Resource, ResourceHash};
pub use graph_craft::application_io::*; pub use graph_craft::application_io::*;
@@ -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>( fn rasterize<T: WasmNotSend + Clone>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
List<Vector>, List<Vector>,
@@ -262,20 +264,26 @@ 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<'a>(_: impl Ctx, #[scope("editor-api")] editor_api: &'a PlatformEditorApi) -> &'a 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<'a>(_: impl Ctx, hash: ResourceHash, #[scope(editor_api::IDENTIFIER)] editor_api: &'a 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<'a>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> &'a ::wgpu_executor::WgpuExecutor {
editor_api editor_api
.application_io .application_io
.as_ref() .as_ref()
@@ -285,6 +293,16 @@ pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)]
} }
#[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<'a>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Option<&'a ::wgpu_executor::WgpuExecutor> {
editor_api.application_io.as_ref()?.gpu_executor() editor_api.application_io.as_ref()?.gpu_executor()
} }
#[node_macro::node(category(""), inject_scope)]
pub fn wgpu_executor_arc<'a>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> std::sync::Arc<::wgpu_executor::WgpuExecutor> {
editor_api
.application_io
.as_ref()
.expect("ApplicationIo not available")
.gpu_executor_arc()
.expect("GPU executor not available")
}
+8 -10
View File
@@ -9,10 +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<'a>(
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache, #[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
data: RenderOutput, data: RenderOutput,
@@ -35,14 +35,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,7 +119,7 @@ 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<'a>(
_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<&'a WgpuExecutor>,
#[data] pipeline: WgpuPipelineCache, #[data] pipeline: WgpuPipelineCache,
@@ -148,7 +146,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 +329,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 +338,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;
+45 -66
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::{Context, 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};
@@ -321,25 +322,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<'a>(
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<&'a WgpuExecutor>,
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi, #[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: &'a 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 +374,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 +414,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(
+89 -28
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};
@@ -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,11 +68,11 @@ 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<'a>(
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<&'a WgpuExecutor>,
data: RenderIntermediate, data: RenderIntermediate,
@@ -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,78 @@ 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::gnode::GNode;
use core_types::gpoll::GPoll;
use core_types::{ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
use graphene_application_io::TimingInformation;
struct ProbeNode;
impl<'a> GNode<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);
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 GNode<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::{Context, 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,31 +50,29 @@ 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<'a>(
_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<&'a WgpuExecutor>,
#[data] pipeline: WgpuPipelineCache, #[data] pipeline: WgpuPipelineCache,
@@ -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());
+217 -14
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.
@@ -995,36 +996,36 @@ mod 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.);
} }
@@ -1036,26 +1037,228 @@ mod test {
#[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::gnode::{BatchStatus, GNode};
use core_types::gpoll::{Finality, GPoll};
use core_types::wire::{EdgeHandle, ErasedGNode, resolve_and_wire};
use std::mem::MaybeUninit;
struct SourceNode<T>(T);
impl<T: Clone, Input> GNode<Input> for SourceNode<T> {
type Output = T;
fn eval(&self, _input: &Input) -> GPoll<T> {
GPoll::Final(self.0.clone())
}
}
struct IndexNode;
impl<Input: ExtractIndex> GNode<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)
}
#[test]
fn generated_add_evaluates_through_the_gnode_path() {
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let graph = AddNode::new(SourceNode(1.0f64), SourceNode(2.0f64));
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(3.0));
}
#[test]
fn generated_add_batches_through_the_erased_edge() {
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let erased: Box<ErasedGNode<f64>> = Box::new(AddNode::new(IndexNode, SourceNode(10.0f64)));
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = erased.eval_batch(&ctx, 2..6, Some(&mut scratch));
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes, &[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);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let entries = logical_or_entries();
let value = EdgeHandle::new(Box::new(SourceNode(true)) as Box<ErasedGNode<bool>>);
let other_value = EdgeHandle::new(Box::new(SourceNode(false)) as Box<ErasedGNode<bool>>);
let wired = resolve_and_wire(&entries[0], vec![value, other_value]).unwrap().downcast::<bool>().unwrap();
assert_eq!(GNode::eval(&wired, &ctx), GPoll::Final(true));
}
#[test]
fn generic_add_registers_one_entry_per_implementation() {
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let entries = add_entries();
assert_eq!(entries.len(), 6);
assert_eq!(entries[0].io.inputs, vec![core_types::concrete!(f64), core_types::concrete!(f64)]);
assert_eq!(entries[0].io.output, core_types::concrete!(f64));
assert_eq!(entries[3].io.inputs, vec![core_types::concrete!(DVec2), core_types::concrete!(DVec2)]);
assert_eq!(entries[3].io.output, core_types::concrete!(DVec2));
let augend = EdgeHandle::new(Box::new(SourceNode(1.5f64)) as Box<ErasedGNode<f64>>);
let addend = EdgeHandle::new(Box::new(SourceNode(2.5f64)) as Box<ErasedGNode<f64>>);
let wired = resolve_and_wire(&entries[0], vec![augend, addend]).unwrap().downcast::<f64>().unwrap();
assert_eq!(GNode::eval(&wired, &ctx), GPoll::Final(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> GNode<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);
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 graph = SwitchNode::new(SourceNode(true), CountingSource(taken.clone(), 1.0), CountingSource(untaken.clone(), 2.0));
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(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> GNode<Input> for PendingSource {
type Output = f64;
fn eval(&self, _input: &Input) -> GPoll<f64> {
GPoll::Pending
}
}
struct PartialSource;
impl<Input> GNode<Input> for PartialSource {
type Output = f64;
fn eval(&self, _input: &Input) -> GPoll<f64> {
GPoll::Partial(7.0)
}
}
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let pending = SwitchNode::new(SourceNode(true), PendingSource, PartialSource);
assert_eq!(GNode::eval(&pending, &ctx), GPoll::Pending);
let partial = SwitchNode::new(SourceNode(false), PendingSource, PartialSource);
assert_eq!(GNode::eval(&partial, &ctx), GPoll::Partial(7.0));
}
#[test]
fn converted_switch_merges_condition_status_into_the_branch_result() {
struct PartialCondition;
impl<Input> GNode<Input> for PartialCondition {
type Output = bool;
fn eval(&self, _input: &Input) -> GPoll<bool> {
GPoll::Partial(true)
}
}
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let graph = SwitchNode::new(PartialCondition, SourceNode(1.0f64), SourceNode(2.0f64));
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Partial(1.0));
}
#[test]
fn generated_eval_computes_on_stand_in_and_traces_fallback() {
struct FallbackNode;
impl<Input> GNode<Input> for FallbackNode {
type Output = f64;
fn eval(&self, _input: &Input) -> GPoll<f64> {
GPoll::fallback(0.0, "upstream failed")
}
}
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let graph = AddNode::new(FallbackNode, SourceNode(5.0f64));
let GPoll::Fallback(boxed) = GNode::eval(&graph, &ctx) else {
panic!("fallback must propagate with the computed stand-in");
};
assert_eq!(boxed.0, 5.0);
assert!(boxed.1.kind == "upstream failed");
assert_eq!(boxed.1.trace, vec![0]);
} }
} }
+1 -1
View File
@@ -23,7 +23,7 @@ pub use vector_types::vector::misc::BooleanOperation;
/// Combines the geometric forms of one or more closed paths into a new vector path that results from cutting or joining the paths by the chosen method. /// Combines the geometric forms of one or more closed paths into a new vector path that results from cutting or joining the paths by the chosen method.
#[node_macro::node(category("Vector: Modifier"), memoize)] #[node_macro::node(category("Vector: Modifier"), memoize)]
async fn boolean_operation<I: graphic_types::IntoGraphicList>( fn boolean_operation<I: graphic_types::IntoGraphicList>(
_: impl Ctx, _: impl Ctx,
/// The `List` of vector paths to perform the boolean operation on. Nested `List`s are automatically flattened. /// The `List` of vector paths to perform the boolean operation on. Nested `List`s are automatically flattened.
#[implementations(List<Graphic>, List<Vector>)] #[implementations(List<Graphic>, List<Vector>)]
+1 -1
View File
@@ -8,7 +8,7 @@ use raster_types::{CPU, Raster};
use std::cmp::{max, min}; use std::cmp::{max, min};
#[node_macro::node(category("Raster: Filter"))] #[node_macro::node(category("Raster: Filter"))]
async fn dehaze(_: impl Ctx, image_frame: List<Raster<CPU>>, strength: Percentage) -> List<Raster<CPU>> { fn dehaze(_: impl Ctx, image_frame: List<Raster<CPU>>, strength: Percentage) -> List<Raster<CPU>> {
image_frame image_frame
.into_iter() .into_iter()
.map(|mut row| { .map(|mut row| {
+2 -2
View File
@@ -87,7 +87,7 @@ fn unpremultiply_gamma_to_linear(buffer: Image<PremultipliedGammaPixel>) -> Imag
/// Blurs the image with a Gaussian or box blur kernel filter. /// Blurs the image with a Gaussian or box blur kernel filter.
#[node_macro::node(category("Raster: Filter"))] #[node_macro::node(category("Raster: Filter"))]
async fn blur( fn blur(
_: impl Ctx, _: impl Ctx,
/// The image to be blurred. /// The image to be blurred.
image_frame: List<Raster<CPU>>, image_frame: List<Raster<CPU>>,
@@ -124,7 +124,7 @@ async fn blur(
/// Applies a median filter to reduce noise while preserving edges. /// Applies a median filter to reduce noise while preserving edges.
#[node_macro::node(category("Raster: Filter"))] #[node_macro::node(category("Raster: Filter"))]
async fn median_filter( fn median_filter(
_: impl Ctx, _: impl Ctx,
/// The image to be filtered. /// The image to be filtered.
image_frame: List<Raster<CPU>>, image_frame: List<Raster<CPU>>,
+1 -1
View File
@@ -10,7 +10,7 @@ use vector_types::GradientStops;
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27grdm%27%20%3D%20Gradient%20Map // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27grdm%27%20%3D%20Gradient%20Map
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Gradient%20settings%20(Photoshop%206.0) // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Gradient%20settings%20(Photoshop%206.0)
#[node_macro::node(category("Raster: Adjustment"))] #[node_macro::node(category("Raster: Adjustment"))]
async fn gradient_map<T: Adjust<Color>>( fn gradient_map<T: Adjust<Color>>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
List<Raster<CPU>>, List<Raster<CPU>>,
@@ -4,7 +4,7 @@ use core_types::list::{Item, List};
use raster_types::{CPU, Raster}; use raster_types::{CPU, Raster};
#[node_macro::node(category("Color"))] #[node_macro::node(category("Color"))]
async fn image_color_palette( fn image_color_palette(
_: impl Ctx, _: impl Ctx,
image: List<Raster<CPU>>, image: List<Raster<CPU>>,
#[default(4)] #[default(4)]
+2 -2
View File
@@ -241,7 +241,7 @@ pub fn extend_image_to_bounds(_: impl Ctx, image: List<Raster<CPU>>, bounds: DAf
let image_data = &row.element().data; let image_data = &row.element().data;
let (image_width, image_height) = (row.element().width, row.element().height); let (image_width, image_height) = (row.element().width, row.element().height);
if image_width == 0 || image_height == 0 { if image_width == 0 || image_height == 0 {
return empty_image((), bounds, List::new_from_element(Color::TRANSPARENT)).into_iter().next().unwrap(); return empty_image(&(), bounds, List::new_from_element(Color::TRANSPARENT)).into_iter().next().unwrap();
} }
let orig_image_scale = DVec2::new(image_width as f64, image_height as f64); let orig_image_scale = DVec2::new(image_width as f64, image_height as f64);
@@ -290,7 +290,7 @@ pub fn empty_image(_: impl Ctx, transform: DAffine2, color: List<Color>) -> List
} }
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
pub fn image<'a: 'n>(_: impl Ctx, resource: Resource) -> List<Raster<CPU>> { pub fn image(_: impl Ctx, resource: Resource) -> List<Raster<CPU>> {
let image_data = resource.as_ref(); let image_data = resource.as_ref();
let Some(image) = ::image::load_from_memory(image_data).ok() else { let Some(image) = ::image::load_from_memory(image_data).ok() else {
+39 -42
View File
@@ -1,16 +1,17 @@
use crate::gcore::Context; use crate::gcore::Context;
use core::f64::consts::TAU; use core::f64::consts::TAU;
use core_types::gpoll::Interrupt;
use core_types::list::List; use core_types::list::List;
use core_types::registry::types::{Angle, PixelSize}; use core_types::registry::types::{Angle, PixelSize};
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, OwnedContextImpl}; use core_types::{ATTR_TRANSFORM, Color, Ctx, DeriveCtx, InjectVarArgs};
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use graphic_types::{Graphic, Vector}; use graphic_types::{Graphic, Vector};
use raster_types::{CPU, Raster}; use raster_types::{CPU, Raster};
use vector_types::GradientStops; use vector_types::GradientStops;
#[node_macro::node(category("Repeat"))] #[node_macro::node(category("Repeat"))]
async fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>( fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx, ctx: impl Ctx + DeriveCtx,
#[implementations( #[implementations(
Context -> List<Graphic>, Context -> List<Graphic>,
Context -> List<Vector>, Context -> List<Vector>,
@@ -18,35 +19,35 @@ async fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
Context -> List<Color>, Context -> List<Color>,
Context -> List<GradientStops>, Context -> List<GradientStops>,
)] )]
content: impl Node<'n, Context<'static>, Output = List<T>>, content: impl Node<Context<'_>, Output = List<T>>,
#[default(1)] #[default(1)]
#[hard(1..)] #[hard(1..)]
count: u32, count: u32,
reverse: bool, reverse: bool,
) -> List<T> { ) -> Result<List<T>, Interrupt> {
// Someday this node can have the option to generate infinitely instead of a fixed count (basically `std::iter::repeat`). // Someday this node can have the option to generate infinitely instead of a fixed count (basically `std::iter::repeat`).
let count = count as usize; let count = count as u64;
let spilled = ctx.index_head();
let mut result_list = List::new(); let mut result_list = List::new();
for index in 0..count { for index in 0..count {
let index = if reverse { count - index - 1 } else { index }; let index = if reverse { count - index - 1 } else { index };
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index); let generated_content = content.eval(&ctx.promoted(&spilled, index))?;
let generated_content = content.eval(new_ctx.into_context()).await;
for generated_row in generated_content.into_iter() { for generated_row in generated_content.into_iter() {
result_list.push(generated_row); result_list.push(generated_row);
} }
} }
result_list Ok(result_list)
} }
#[node_macro::node(category("Repeat"))] #[node_macro::node(category("Repeat"))]
pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>( pub fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx, ctx: impl Ctx + DeriveCtx,
#[implementations( #[implementations(
Context -> List<Graphic>, Context -> List<Graphic>,
Context -> List<Vector>, Context -> List<Vector>,
@@ -54,7 +55,7 @@ pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
Context -> List<Color>, Context -> List<Color>,
Context -> List<GradientStops>, Context -> List<GradientStops>,
)] )]
content: impl Node<'n, Context<'static>, Output = List<T>>, content: impl Node<Context<'_>, Output = List<T>>,
#[default(100., 100.)] #[default(100., 100.)]
// TODO: When using a custom Properties panel layout in document_node_definitions.rs and this default is set, the widget weirdly doesn't show up in the Properties panel. Investigation is needed. // TODO: When using a custom Properties panel layout in document_node_definitions.rs and this default is set, the widget weirdly doesn't show up in the Properties panel. Investigation is needed.
direction: PixelSize, direction: PixelSize,
@@ -62,10 +63,11 @@ pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
#[default(5)] #[default(5)]
#[hard(1..)] #[hard(1..)]
count: u32, count: u32,
) -> List<T> { ) -> Result<List<T>, Interrupt> {
let angle = angle.to_radians(); let angle = angle.to_radians();
// A single copy has no steps between copies, so the denominator is kept at 1 to avoid `0. / 0.` producing a NaN transform // A single copy has no steps between copies, so the denominator is kept at 1 to avoid `0. / 0.` producing a NaN transform
let total = (count - 1).max(1) as f64; let total = (count - 1).max(1) as f64;
let spilled = ctx.index_head();
let mut result_list = List::new(); let mut result_list = List::new();
@@ -74,8 +76,7 @@ pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
let translation = index as f64 * direction / total; let translation = index as f64 * direction / total;
let transform = DAffine2::from_angle(angle) * DAffine2::from_translation(translation); let transform = DAffine2::from_angle(angle) * DAffine2::from_translation(translation);
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index as usize); let generated_content = content.eval(&ctx.promoted(&spilled, index as u64))?;
let generated_content = content.eval(new_ctx.into_context()).await;
for row_index in 0..generated_content.len() { for row_index in 0..generated_content.len() {
let Some(mut row) = generated_content.clone_item(row_index) else { continue }; let Some(mut row) = generated_content.clone_item(row_index) else { continue };
@@ -89,12 +90,12 @@ pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
} }
} }
result_list Ok(result_list)
} }
#[node_macro::node(category("Repeat"))] #[node_macro::node(category("Repeat"))]
async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>( fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx, ctx: impl Ctx + DeriveCtx,
#[implementations( #[implementations(
Context -> List<Graphic>, Context -> List<Graphic>,
Context -> List<Vector>, Context -> List<Vector>,
@@ -102,7 +103,7 @@ async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
Context -> List<Color>, Context -> List<Color>,
Context -> List<GradientStops>, Context -> List<GradientStops>,
)] )]
content: impl Node<'n, Context<'static>, Output = List<T>>, content: impl Node<Context<'_>, Output = List<T>>,
start_angle: Angle, start_angle: Angle,
#[unit(" px")] #[unit(" px")]
#[default(5)] #[default(5)]
@@ -110,7 +111,8 @@ async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
#[default(5)] #[default(5)]
#[hard(1..)] #[hard(1..)]
count: u32, count: u32,
) -> List<T> { ) -> Result<List<T>, Interrupt> {
let spilled = ctx.index_head();
let mut result_list = List::new(); let mut result_list = List::new();
for index in 0..count { for index in 0..count {
@@ -118,8 +120,7 @@ async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
let translation = DAffine2::from_translation(radius * DVec2::Y); let translation = DAffine2::from_translation(radius * DVec2::Y);
let transform = angle * translation; let transform = angle * translation;
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index as usize); let generated_content = content.eval(&ctx.promoted(&spilled, index as u64))?;
let generated_content = content.eval(new_ctx.into_context()).await;
for row_index in 0..generated_content.len() { for row_index in 0..generated_content.len() {
let Some(mut row) = generated_content.clone_item(row_index) else { continue }; let Some(mut row) = generated_content.clone_item(row_index) else { continue };
@@ -133,12 +134,12 @@ async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
} }
} }
result_list Ok(result_list)
} }
#[node_macro::node(category("Repeat"), name("Repeat on Points"))] #[node_macro::node(category("Repeat"), name("Repeat on Points"))]
async fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>( fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs, ctx: impl Ctx + DeriveCtx + InjectVarArgs,
points: List<Vector>, points: List<Vector>,
#[implementations( #[implementations(
Context -> List<Graphic>, Context -> List<Graphic>,
@@ -147,40 +148,36 @@ async fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
Context -> List<Color>, Context -> List<Color>,
Context -> List<GradientStops>, Context -> List<GradientStops>,
)] )]
content: impl Node<'n, Context<'static>, Output = List<T>>, content: impl Node<Context<'_>, Output = List<T>>,
reverse: bool, reverse: bool,
) -> List<T> { ) -> Result<List<T>, Interrupt> {
let spilled = ctx.index_head();
let mut result_list = List::new(); let mut result_list = List::new();
for points_index in 0..points.len() { for points_index in 0..points.len() {
let Some(points_element) = points.element(points_index) else { continue }; let Some(points_element) = points.element(points_index) else { continue };
let transform: DAffine2 = points.attribute_cloned_or_default(ATTR_TRANSFORM, points_index); let transform: DAffine2 = points.attribute_cloned_or_default(ATTR_TRANSFORM, points_index);
let mut iteration = async |index, point| { let positions = points_element.point_domain.positions();
let range: Box<dyn Iterator<Item = (usize, &DVec2)>> = match reverse {
true => Box::new(positions.iter().enumerate().rev()),
false => Box::new(positions.iter().enumerate()),
};
for (index, &point) in range {
let transformed_point = transform.transform_point2(point); let transformed_point = transform.transform_point2(point);
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(transformed_point); let scoped = ctx.push_position(transformed_point);
let generated_content = content.eval(new_ctx.into_context()).await; let generated_content = content.eval(&scoped.ctx().promoted(&spilled, index as u64))?;
for mut generated_row in generated_content.into_iter() { for mut generated_row in generated_content.into_iter() {
generated_row.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM).translation = transformed_point; generated_row.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM).translation = transformed_point;
result_list.push(generated_row); result_list.push(generated_row);
} }
};
let range = points_element.point_domain.positions().iter().enumerate();
if reverse {
for (index, &point) in range.rev() {
iteration(index, point).await;
}
} else {
for (index, &point) in range {
iteration(index, point).await;
}
} }
} }
result_list Ok(result_list)
} }
#[cfg(test)] #[cfg(test)]
+10 -9
View File
@@ -7,10 +7,11 @@ mod text_context;
mod to_path; mod to_path;
use convert_case::{Boundary, Converter, pattern}; use convert_case::{Boundary, Converter, pattern};
use core_types::gpoll::Interrupt;
use core_types::graphene_hash::CacheHash; use core_types::graphene_hash::CacheHash;
use core_types::list::{Item, List}; use core_types::list::{Item, List};
use core_types::registry::types::{SignedInteger, TextArea}; use core_types::registry::types::{SignedInteger, TextArea};
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, OwnedContextImpl}; use core_types::{Context, Ctx, DeriveCtx, ExtractVarArgs};
use dyn_any::DynAny; use dyn_any::DynAny;
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
@@ -768,25 +769,25 @@ fn string_join(
/// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop. /// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop.
#[node_macro::node(category("Text"))] #[node_macro::node(category("Text"))]
async fn map_string( fn map_string(
ctx: impl Ctx + CloneVarArgs + ExtractAll, ctx: impl Ctx + DeriveCtx,
strings: List<String>, strings: List<String>,
#[expose] #[expose]
#[implementations(Context -> String)] #[implementations(Context -> String)]
mapped: impl Node<Context<'static>, Output = String>, mapped: impl Node<Context<'_>, Output = String>,
) -> List<String> { ) -> Result<List<String>, Interrupt> {
let spilled = ctx.index_head();
let mut result = List::new(); let mut result = List::new();
for (i, row) in strings.into_iter().enumerate() { for (i, row) in strings.into_iter().enumerate() {
let string = row.into_element(); let string = row.into_element();
let owned_ctx = OwnedContextImpl::from(ctx.clone()); let scoped = ctx.push_vararg(&string);
let owned_ctx = owned_ctx.with_vararg(Box::new(string)).with_index(i); let mapped_string = mapped.eval(&scoped.ctx().promoted(&spilled, i as u64))?;
let mapped_string = mapped.eval(owned_ctx.into_context()).await;
result.push(Item::new_from_element(mapped_string)); result.push(Item::new_from_element(mapped_string));
} }
result Ok(result)
} }
/// Reads the current string from within a **Map String** node's loop. /// Reads the current string from within a **Map String** node's loop.
@@ -2,7 +2,8 @@ use core::f64;
use core_types::color::Color; use core_types::color::Color;
use core_types::list::{List, ListDyn}; use core_types::list::{List, ListDyn};
use core_types::transform::{ApplyTransform, ScaleType, Transform}; use core_types::transform::{ApplyTransform, ScaleType, Transform};
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, ModifyFootprint, OwnedContextImpl}; use core_types::gpoll::Interrupt;
use core_types::{ATTR_TRANSFORM, Context, Ctx, DeriveCtx, ExtractFootprint, InjectFootprint, ModifyFootprint};
use glam::{DAffine2, DMat2, DVec2}; use glam::{DAffine2, DMat2, DVec2};
use graphic_types::Graphic; use graphic_types::Graphic;
use graphic_types::Vector; use graphic_types::Vector;
@@ -11,8 +12,8 @@ use vector_types::GradientStops;
/// Applies the specified transform to the input value, which may be a graphic type or another transform. /// Applies the specified transform to the input value, which may be a graphic type or another transform.
#[node_macro::node(category("Math: Transform"))] #[node_macro::node(category("Math: Transform"))]
async fn transform<T: ApplyTransform + 'n + 'static>( fn transform<T: ApplyTransform + 'static>(
ctx: impl Ctx + CloneVarArgs + ExtractAll + ModifyFootprint, ctx: impl Ctx + ExtractFootprint + DeriveCtx + ModifyFootprint,
#[implementations( #[implementations(
Context -> DAffine2, Context -> DAffine2,
Context -> DVec2, Context -> DVec2,
@@ -24,31 +25,24 @@ async fn transform<T: ApplyTransform + 'n + 'static>(
Context -> List<Color>, Context -> List<Color>,
Context -> List<GradientStops>, Context -> List<GradientStops>,
)] )]
content: impl Node<Context<'static>, Output = T>, content: impl Node<Context<'_>, Output = T>,
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: DVec2, #[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: DVec2,
#[widget(ParsedWidgetOverride::Custom = "transform_rotation")] rotation: f64, #[widget(ParsedWidgetOverride::Custom = "transform_rotation")] rotation: f64,
#[widget(ParsedWidgetOverride::Custom = "transform_scale")] #[widget(ParsedWidgetOverride::Custom = "transform_scale")]
#[default(1., 1.)] #[default(1., 1.)]
scale: DVec2, scale: DVec2,
#[widget(ParsedWidgetOverride::Custom = "transform_skew")] skew: DVec2, #[widget(ParsedWidgetOverride::Custom = "transform_skew")] skew: DVec2,
) -> T { ) -> Result<T, Interrupt> {
let trs = DAffine2::from_scale_angle_translation(scale, rotation.to_radians(), translation); let trs = DAffine2::from_scale_angle_translation(scale, rotation.to_radians(), translation);
let skew = DAffine2::from_cols_array(&[1., skew.y.to_radians().tan(), skew.x.to_radians().tan(), 1., 0., 0.]); let skew = DAffine2::from_cols_array(&[1., skew.y.to_radians().tan(), skew.x.to_radians().tan(), 1., 0., 0.]);
let matrix = trs * skew; let matrix = trs * skew;
let footprint = ctx.try_footprint().copied(); let transformed = ctx.modify_footprint(|footprint| footprint.apply_transform(&matrix));
let mut transform_target = content.eval(&transformed.ctx())?;
let mut ctx = OwnedContextImpl::from(ctx);
if let Some(mut footprint) = footprint {
footprint.apply_transform(&matrix);
ctx = ctx.with_footprint(footprint);
}
let mut transform_target = content.eval(ctx.into_context()).await;
transform_target.left_apply_transform(&matrix); transform_target.left_apply_transform(&matrix);
transform_target Ok(transform_target)
} }
/// Resets the desired components of the input transform to their default values. If all components are reset, the output will be set to the identity transform. /// Resets the desired components of the input transform to their default values. If all components are reset, the output will be set to the identity transform.
@@ -114,7 +108,7 @@ fn replace_transform<T>(
// TODO: Figure out how this node should behave once #2982 is implemented. // TODO: Figure out how this node should behave once #2982 is implemented.
/// Obtains the transform of the first item in the input `List`, if present. /// Obtains the transform of the first item in the input `List`, if present.
#[node_macro::node(category("Math: Transform"), path(core_types::vector))] #[node_macro::node(category("Math: Transform"), path(core_types::vector))]
async fn extract_transform(_: impl Ctx, content: ListDyn) -> DAffine2 { fn extract_transform(_: impl Ctx, content: ListDyn) -> DAffine2 {
content.attribute::<DAffine2>(ATTR_TRANSFORM, 0).copied().unwrap_or_default() content.attribute::<DAffine2>(ATTR_TRANSFORM, 0).copied().unwrap_or_default()
} }
@@ -7,7 +7,7 @@ use vector_types::vector::VectorModification;
/// Applies a differential modification to a vector path, associating changes made by the Pen and Path tools to indices of edited points and segments. /// Applies a differential modification to a vector path, associating changes made by the Pen and Path tools to indices of edited points and segments.
#[node_macro::node(category(""))] #[node_macro::node(category(""))]
async fn path_modify(_ctx: impl Ctx, mut vector: List<Vector>, modification: Box<VectorModification>, node_path: List<NodeId>) -> List<Vector> { fn path_modify(_ctx: impl Ctx, mut vector: List<Vector>, modification: Box<VectorModification>, node_path: List<NodeId>) -> List<Vector> {
use core_types::list::Item; use core_types::list::Item;
if vector.is_empty() { if vector.is_empty() {
@@ -35,7 +35,7 @@ async fn path_modify(_ctx: impl Ctx, mut vector: List<Vector>, modification: Box
/// Applies the vector path's local transformation to its geometry and resets the transform to the identity. /// Applies the vector path's local transformation to its geometry and resets the transform to the identity.
#[node_macro::node(category("Vector"))] #[node_macro::node(category("Vector"))]
async fn apply_transform(_ctx: impl Ctx, mut vector: List<Vector>) -> List<Vector> { fn apply_transform(_ctx: impl Ctx, mut vector: List<Vector>) -> List<Vector> {
let (elements, transforms) = vector.element_and_attribute_slices_mut::<DAffine2>(ATTR_TRANSFORM); let (elements, transforms) = vector.element_and_attribute_slices_mut::<DAffine2>(ATTR_TRANSFORM);
for (element, transform) in elements.iter_mut().zip(transforms.iter_mut()) { for (element, transform) in elements.iter_mut().zip(transforms.iter_mut()) {
for (_, point) in element.point_domain.positions_mut() { for (_, point) in element.point_domain.positions_mut() {
+52 -53
View File
@@ -7,9 +7,10 @@ use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, ItemAttributeValues, List,
use core_types::registry::types::{Angle, Length, Multiplier, Percentage, PixelLength, Progression, SeedValue}; use core_types::registry::types::{Angle, Length, Multiplier, Percentage, PixelLength, Progression, SeedValue};
use core_types::transform::{Footprint, Transform}; use core_types::transform::{Footprint, Transform};
use core_types::uuid::NodeId; use core_types::uuid::NodeId;
use core_types::gpoll::Interrupt;
use core_types::{ use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, CloneVarArgs, ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color, Context,
Color, Context, Ctx, ExtractAll, OwnedContextImpl, Ctx, DeriveCtx,
}; };
use glam::{DAffine2, DMat2, DVec2}; use glam::{DAffine2, DMat2, DVec2};
use graphic_types::Vector; use graphic_types::Vector;
@@ -88,7 +89,7 @@ impl VectorListIterMut for List<Vector> {
/// Uniquely sets the fill and/or stroke style of every vector element to individual colors sampled along a chosen gradient. /// Uniquely sets the fill and/or stroke style of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Style"), path(graphene_core::vector))]
async fn assign_colors<T>( fn assign_colors<T>(
_: impl Ctx, _: impl Ctx,
/// The content with vector paths to apply the fill and/or stroke style to. /// The content with vector paths to apply the fill and/or stroke style to.
#[implementations(List<Graphic>, List<Vector>)] #[implementations(List<Graphic>, List<Vector>)]
@@ -115,7 +116,7 @@ async fn assign_colors<T>(
repeat_every: u32, repeat_every: u32,
) -> T ) -> T
where where
T: VectorListIterMut + 'n + Send, T: VectorListIterMut+ Send,
{ {
let Some(row) = gradient.into_iter().next() else { return content }; let Some(row) = gradient.into_iter().next() else { return content };
@@ -156,7 +157,7 @@ where
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry. /// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("fill_properties"))] #[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("fill_properties"))]
async fn fill<V: VectorListIterMut + 'n + Send, F: IntoGraphicList + 'n + Send + 'static>( fn fill<V: VectorListIterMut+ Send, F: IntoGraphicList+ Send + 'static>(
_: impl Ctx, _: impl Ctx,
/// The content with vector paths to apply the fill style to. /// The content with vector paths to apply the fill style to.
#[implementations( #[implementations(
@@ -251,7 +252,7 @@ impl IntoF64Vec for String {
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry. /// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("stroke_properties"))] #[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("stroke_properties"))]
async fn stroke<V, L: IntoF64Vec, P: IntoGraphicList + 'n + Send + 'static>( fn stroke<V, L: IntoF64Vec, P: IntoGraphicList+ Send + 'static>(
_: impl Ctx, _: impl Ctx,
/// The content with vector paths to apply the stroke style to. /// The content with vector paths to apply the stroke style to.
#[implementations( #[implementations(
@@ -323,7 +324,7 @@ async fn stroke<V, L: IntoF64Vec, P: IntoGraphicList + 'n + Send + 'static>(
dash_offset: f64, dash_offset: f64,
) -> List<V> ) -> List<V>
where where
List<V>: VectorListIterMut + 'n + Send, List<V>: VectorListIterMut+ Send,
{ {
let dash_lengths = dash_lengths.into_vec().into_iter().map(|length| length.max(0.)).collect(); let dash_lengths = dash_lengths.into_vec().into_iter().map(|length| length.max(0.)).collect();
@@ -356,7 +357,7 @@ where
} }
#[node_macro::node(name("Copy to Points"), category("Repeat"), path(core_types::vector))] #[node_macro::node(name("Copy to Points"), category("Repeat"), path(core_types::vector))]
async fn copy_to_points<I: 'n + Send + Clone>( fn copy_to_points<I: Send + Clone>(
_: impl Ctx, _: impl Ctx,
points: List<Vector>, points: List<Vector>,
/// Artwork to be copied and placed at each point. /// Artwork to be copied and placed at each point.
@@ -440,7 +441,7 @@ async fn copy_to_points<I: 'n + Send + Clone>(
} }
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn round_corners( fn round_corners(
_: impl Ctx, _: impl Ctx,
source: List<Vector>, source: List<Vector>,
#[hard(0..)] #[hard(0..)]
@@ -777,7 +778,7 @@ pub mod extrude_algorithms {
} }
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn extrude(_: impl Ctx, mut source: List<Vector>, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) -> List<Vector> { fn extrude(_: impl Ctx, mut source: List<Vector>, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) -> List<Vector> {
for vector in source.iter_element_values_mut() { for vector in source.iter_element_values_mut() {
extrude_algorithms::extrude(vector, direction, joining_algorithm); extrude_algorithms::extrude(vector, direction, joining_algorithm);
} }
@@ -785,7 +786,7 @@ async fn extrude(_: impl Ctx, mut source: List<Vector>, direction: DVec2, joinin
} }
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn box_warp(_: impl Ctx, content: List<Vector>, #[expose] rectangle: List<Vector>) -> List<Vector> { fn box_warp(_: impl Ctx, content: List<Vector>, #[expose] rectangle: List<Vector>) -> List<Vector> {
let Some(target) = rectangle.element(0).cloned() else { return content }; let Some(target) = rectangle.element(0).cloned() else { return content };
let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM, 0); let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
@@ -870,7 +871,7 @@ fn bilinear_interpolate(t: DVec2, quad: &[DVec2; 4]) -> DVec2 {
} }
#[node_macro::node(category("Vector"), path(graphene_core::vector))] #[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn pack_strips<T: 'n + Send + Clone>( fn pack_strips<T: Send + Clone>(
_: impl Ctx, _: impl Ctx,
#[implementations( #[implementations(
List<Graphic>, List<Graphic>,
@@ -991,7 +992,7 @@ where
/// Automatically constructs tangents (Bézier handles) for anchor points in a vector path. /// Automatically constructs tangents (Bézier handles) for anchor points in a vector path.
#[node_macro::node(category("Vector: Modifier"), name("Auto-Tangents"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), name("Auto-Tangents"), path(core_types::vector))]
async fn auto_tangents( fn auto_tangents(
_: impl Ctx, _: impl Ctx,
source: List<Vector>, source: List<Vector>,
/// The amount of spread for the auto-tangents, from 0 (sharp corner) to 1 (full spread). /// The amount of spread for the auto-tangents, from 0 (sharp corner) to 1 (full spread).
@@ -1145,7 +1146,7 @@ async fn auto_tangents(
} }
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn bounding_box(_: impl Ctx, content: List<Vector>) -> List<Vector> { fn bounding_box(_: impl Ctx, content: List<Vector>) -> List<Vector> {
content content
.into_iter() .into_iter()
.map(|mut row| { .map(|mut row| {
@@ -1170,7 +1171,7 @@ async fn bounding_box(_: impl Ctx, content: List<Vector>) -> List<Vector> {
} }
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
async fn dimensions(_: impl Ctx, content: List<Vector>) -> DVec2 { fn dimensions(_: impl Ctx, content: List<Vector>) -> DVec2 {
(0..content.len()) (0..content.len())
.filter_map(|index| content.element(index).unwrap().bounding_box_with_transform(content.attribute_cloned_or_default(ATTR_TRANSFORM, index))) .filter_map(|index| content.element(index).unwrap().bounding_box_with_transform(content.attribute_cloned_or_default(ATTR_TRANSFORM, index)))
.reduce(|[acc_top_left, acc_bottom_right], [top_left, bottom_right]| [acc_top_left.min(top_left), acc_bottom_right.max(bottom_right)]) .reduce(|[acc_top_left, acc_bottom_right], [top_left, bottom_right]| [acc_top_left.min(top_left), acc_bottom_right.max(bottom_right)])
@@ -1186,7 +1187,7 @@ fn as_vector(_: impl Ctx, value: List<Vector>) -> List<Vector> {
/// Creates a polyline from a series of vector points, replacing any existing segments and regions that may already exist. /// Creates a polyline from a series of vector points, replacing any existing segments and regions that may already exist.
#[node_macro::node(category("Vector"), name("Points to Polyline"), path(core_types::vector))] #[node_macro::node(category("Vector"), name("Points to Polyline"), path(core_types::vector))]
async fn points_to_polyline(_: impl Ctx, mut points: List<Vector>, #[default(true)] closed: bool) -> List<Vector> { fn points_to_polyline(_: impl Ctx, mut points: List<Vector>, #[default(true)] closed: bool) -> List<Vector> {
for vector in points.iter_element_values_mut() { for vector in points.iter_element_values_mut() {
let mut segment_domain = SegmentDomain::new(); let mut segment_domain = SegmentDomain::new();
let mut next_id = SegmentId::ZERO; let mut next_id = SegmentId::ZERO;
@@ -1214,7 +1215,7 @@ async fn points_to_polyline(_: impl Ctx, mut points: List<Vector>, #[default(tru
} }
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector), properties("offset_path_properties"))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector), properties("offset_path_properties"))]
async fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: StrokeJoin, #[default(4.)] miter_limit: f64) -> List<Vector> { fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: StrokeJoin, #[default(4.)] miter_limit: f64) -> List<Vector> {
content content
.into_iter() .into_iter()
.map(|mut row| { .map(|mut row| {
@@ -1258,7 +1259,7 @@ async fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: St
} }
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn solidify_stroke<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> { fn solidify_stroke<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
// TODO: Make this node support stroke align, which it currently ignores // TODO: Make this node support stroke align, which it currently ignores
let graphic_list = content.into_graphic_list(); let graphic_list = content.into_graphic_list();
@@ -1366,7 +1367,7 @@ async fn solidify_stroke<T: IntoGraphicList>(_: impl Ctx, #[implementations(List
} }
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> { fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> {
content content
.into_iter() .into_iter()
.flat_map(|row| { .flat_map(|row| {
@@ -1397,7 +1398,7 @@ async fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> {
/// Determines if the subpath at the given index (across all vector element subpaths) is closed, meaning its ends are connected together forming a loop. /// Determines if the subpath at the given index (across all vector element subpaths) is closed, meaning its ends are connected together forming a loop.
#[node_macro::node(name("Path is Closed"), category("Vector: Measure"), path(core_types::vector))] #[node_macro::node(name("Path is Closed"), category("Vector: Measure"), path(core_types::vector))]
async fn path_is_closed( fn path_is_closed(
_: impl Ctx, _: impl Ctx,
/// The vector content whose subpaths are inspected. /// The vector content whose subpaths are inspected.
content: List<Vector>, content: List<Vector>,
@@ -1412,25 +1413,25 @@ async fn path_is_closed(
} }
#[node_macro::node(category("Vector"), path(graphene_core::vector))] #[node_macro::node(category("Vector"), path(graphene_core::vector))]
async fn map_points(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: List<Vector>, mapped: impl Node<Context<'static>, Output = DVec2>) -> List<Vector> { fn map_points(ctx: impl Ctx + DeriveCtx, content: List<Vector>, mapped: impl Node<Context<'_>, Output = DVec2>) -> Result<List<Vector>, Interrupt> {
let spilled = ctx.index_head();
let mut content = content; let mut content = content;
let mut index = 0; let mut index = 0;
for vector in content.iter_element_values_mut() { for vector in content.iter_element_values_mut() {
for (_, position) in vector.point_domain.positions_mut() { for (_, position) in vector.point_domain.positions_mut() {
let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(*position); let scoped = ctx.push_position(*position);
*position = mapped.eval(&scoped.ctx().promoted(&spilled, index))?;
index += 1; index += 1;
*position = mapped.eval(owned_ctx.into_context()).await;
} }
} }
content Ok(content)
} }
// TODO: Rename to "Combine Paths" and make this happen per-element instead of flattening every element into a single path. The migration for this should then become a Flatten Vector -> Combine Paths pair of nodes. // TODO: Rename to "Combine Paths" and make this happen per-element instead of flattening every element into a single path. The migration for this should then become a Flatten Vector -> Combine Paths pair of nodes.
#[node_macro::node(category("Vector"), path(graphene_core::vector))] #[node_macro::node(category("Vector"), path(graphene_core::vector))]
pub async fn flatten_path<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> { pub fn flatten_path<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 flattened = graphic_list.clone().into_flattened_list::<Vector>(); let flattened = graphic_list.clone().into_flattened_list::<Vector>();
@@ -1486,7 +1487,7 @@ pub async fn flatten_path<T: IntoGraphicList>(_: impl Ctx, #[implementations(Lis
/// Convert vector geometry into a polyline composed of evenly spaced points. /// Convert vector geometry into a polyline composed of evenly spaced points.
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector), properties("sample_polyline_properties"), memoize)] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector), properties("sample_polyline_properties"), memoize)]
async fn sample_polyline( fn sample_polyline(
_: impl Ctx, _: impl Ctx,
content: List<Vector>, content: List<Vector>,
spacing: PointSpacingType, spacing: PointSpacingType,
@@ -1572,7 +1573,7 @@ async fn sample_polyline(
/// Simplifies vector paths by reducing the number of curve segments while preserving the overall shape within the given tolerance. /// Simplifies vector paths by reducing the number of curve segments while preserving the overall shape within the given tolerance.
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn simplify( fn simplify(
_: impl Ctx, _: impl Ctx,
/// The vector paths to simplify. /// The vector paths to simplify.
content: List<Vector>, content: List<Vector>,
@@ -1616,7 +1617,7 @@ async fn simplify(
/// Decimates vector paths into polylines by sampling any curves into line segments, then removing points that don't significantly contribute to the shape using the Ramer-Douglas-Peucker algorithm. /// Decimates vector paths into polylines by sampling any curves into line segments, then removing points that don't significantly contribute to the shape using the Ramer-Douglas-Peucker algorithm.
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn decimate( fn decimate(
_: impl Ctx, _: impl Ctx,
/// The vector paths to decimate. /// The vector paths to decimate.
content: List<Vector>, content: List<Vector>,
@@ -1744,7 +1745,7 @@ async fn decimate(
/// ///
/// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it. /// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it.
#[node_macro::node(category("Vector: Modifier"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Modifier"), path(graphene_core::vector))]
async fn cut_path( fn cut_path(
_: impl Ctx, _: impl Ctx,
/// The path to insert a cut into. /// The path to insert a cut into.
mut content: List<Vector>, mut content: List<Vector>,
@@ -1795,7 +1796,7 @@ async fn cut_path(
/// Cuts path segments into separate disconnected pieces where each is a distinct subpath. /// Cuts path segments into separate disconnected pieces where each is a distinct subpath.
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn cut_segments(_: impl Ctx, mut content: List<Vector>) -> List<Vector> { fn cut_segments(_: impl Ctx, mut content: List<Vector>) -> List<Vector> {
// Iterate through every segment and make a copy of each of its endpoints, then reassign each segment's endpoints to its own unique point copy // Iterate through every segment and make a copy of each of its endpoints, then reassign each segment's endpoints to its own unique point copy
for vector in content.iter_element_values_mut() { for vector in content.iter_element_values_mut() {
let points_count = vector.point_domain.ids().len(); let points_count = vector.point_domain.ids().len();
@@ -1854,7 +1855,7 @@ async fn cut_segments(_: impl Ctx, mut content: List<Vector>) -> List<Vector> {
/// ///
/// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it. /// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it.
#[node_macro::node(name("Position on Path"), category("Vector: Measure"), path(graphene_core::vector))] #[node_macro::node(name("Position on Path"), category("Vector: Measure"), path(graphene_core::vector))]
async fn position_on_path( fn position_on_path(
_: impl Ctx, _: impl Ctx,
/// The path to traverse. /// The path to traverse.
content: List<Vector>, content: List<Vector>,
@@ -1892,7 +1893,7 @@ async fn position_on_path(
/// ///
/// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it. /// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it.
#[node_macro::node(name("Tangent on Path"), category("Vector: Measure"), path(graphene_core::vector))] #[node_macro::node(name("Tangent on Path"), category("Vector: Measure"), path(graphene_core::vector))]
async fn tangent_on_path( fn tangent_on_path(
_: impl Ctx, _: impl Ctx,
/// The path to traverse. /// The path to traverse.
content: List<Vector>, content: List<Vector>,
@@ -1940,7 +1941,7 @@ async fn tangent_on_path(
} }
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector), memoize)] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector), memoize)]
async fn scatter_points( fn scatter_points(
_: impl Ctx, _: impl Ctx,
content: List<Vector>, content: List<Vector>,
#[unit(" px")] #[unit(" px")]
@@ -1990,7 +1991,7 @@ async fn scatter_points(
} }
#[node_macro::node(name("Spline"), category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(name("Spline"), category("Vector: Modifier"), path(core_types::vector))]
async fn spline(_: impl Ctx, content: List<Vector>) -> List<Vector> { fn spline(_: impl Ctx, content: List<Vector>) -> List<Vector> {
content content
.into_iter() .into_iter()
.filter_map(|mut row| { .filter_map(|mut row| {
@@ -2090,7 +2091,7 @@ fn apply_point_deltas(element: &mut Vector, deltas: &[DVec2], transform: DAffine
/// Perturbs the positions of anchor points in vector geometry by random amounts and directions. /// Perturbs the positions of anchor points in vector geometry by random amounts and directions.
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn jitter_points( fn jitter_points(
_: impl Ctx, _: impl Ctx,
/// The vector geometry with points to be jittered. /// The vector geometry with points to be jittered.
content: List<Vector>, content: List<Vector>,
@@ -2140,7 +2141,7 @@ async fn jitter_points(
/// Displaces anchor points along their normal direction (perpendicular to the path) by a set distance. /// Displaces anchor points along their normal direction (perpendicular to the path) by a set distance.
/// Points with 0 or 3+ segment connections have no well-defined normal and are left in place. /// Points with 0 or 3+ segment connections have no well-defined normal and are left in place.
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn offset_points( fn offset_points(
_: impl Ctx, _: impl Ctx,
/// The vector geometry with points to be offset. /// The vector geometry with points to be offset.
content: List<Vector>, content: List<Vector>,
@@ -2177,7 +2178,7 @@ async fn offset_points(
/// ///
/// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments. /// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments.
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))] #[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
async fn morph<I: IntoGraphicList>( fn morph<I: IntoGraphicList>(
_: impl Ctx, _: impl Ctx,
/// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements. /// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements.
#[implementations(List<Graphic>, List<Vector>)] #[implementations(List<Graphic>, List<Vector>)]
@@ -3124,19 +3125,19 @@ fn point_inside(_: impl Ctx, source: List<Vector>, point: DVec2) -> bool {
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs. // TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.) // TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
#[node_macro::node(category("General"), path(graphene_core::vector))] #[node_macro::node(category("General"), path(graphene_core::vector))]
async fn count_elements(_: impl Ctx, content: ListDyn) -> f64 { fn count_elements(_: impl Ctx, content: ListDyn) -> f64 {
content.len() as f64 content.len() as f64
} }
#[node_macro::node(category("Vector: Measure"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Measure"), path(graphene_core::vector))]
async fn count_points(_: impl Ctx, content: List<Vector>) -> f64 { fn count_points(_: impl Ctx, content: List<Vector>) -> f64 {
content.iter_element_values().map(|vector| vector.point_domain.positions().len() as f64).sum() content.iter_element_values().map(|vector| vector.point_domain.positions().len() as f64).sum()
} }
/// Retrieves the vec2 position (in local space) of the anchor point at the specified index in a `List` of vector elements. /// Retrieves the vec2 position (in local space) of the anchor point at the specified index in a `List` of vector elements.
/// If no value exists at that index, the position (0, 0) is returned. /// If no value exists at that index, the position (0, 0) is returned.
#[node_macro::node(category("Vector: Measure"), path(graphene_core::vector))] #[node_macro::node(category("Vector: Measure"), path(graphene_core::vector))]
async fn index_points( fn index_points(
_: impl Ctx, _: impl Ctx,
/// The vector element or elements containing the anchor points to be retrieved. /// The vector element or elements containing the anchor points to be retrieved.
content: List<Vector>, content: List<Vector>,
@@ -3170,7 +3171,7 @@ async fn index_points(
} }
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
async fn path_length(_: impl Ctx, source: List<Vector>) -> f64 { fn path_length(_: impl Ctx, source: List<Vector>) -> f64 {
(0..source.len()) (0..source.len())
.map(|index| { .map(|index| {
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM, index); let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM, index);
@@ -3189,26 +3190,24 @@ async fn path_length(_: impl Ctx, source: List<Vector>) -> f64 {
} }
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
async fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Context<'static>, Output = List<Vector>>) -> f64 { fn area(ctx: impl Ctx + DeriveCtx, content: impl Node<Context<'_>, Output = List<Vector>>) -> Result<f64, Interrupt> {
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context(); let vector = content.eval(&ctx.with_footprint(&Footprint::DEFAULT))?;
let vector = content.eval(new_ctx).await;
(0..vector.len()) Ok((0..vector.len())
.map(|index| { .map(|index| {
let transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM, index); let transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM, index);
let area_scale = transform.matrix2.determinant().abs(); let area_scale = transform.matrix2.determinant().abs();
vector.element(index).unwrap().stroke_bezpath_iter().map(|subpath| subpath.area() * area_scale).sum::<f64>() vector.element(index).unwrap().stroke_bezpath_iter().map(|subpath| subpath.area() * area_scale).sum::<f64>()
}) })
.sum() .sum())
} }
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))] #[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
async fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Context<'static>, Output = List<Vector>>, centroid_type: CentroidType) -> DVec2 { fn centroid(ctx: impl Ctx + DeriveCtx, content: impl Node<Context<'_>, Output = List<Vector>>, centroid_type: CentroidType) -> Result<DVec2, Interrupt> {
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context(); let vector = content.eval(&ctx.with_footprint(&Footprint::DEFAULT))?;
let vector = content.eval(new_ctx).await;
if vector.is_empty() { if vector.is_empty() {
return DVec2::ZERO; return Ok(DVec2::ZERO);
} }
// All subpath centroid positions added together as if they were vectors from the origin. // All subpath centroid positions added together as if they were vectors from the origin.
@@ -3234,7 +3233,7 @@ async fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<
} }
if sum > 0. { if sum > 0. {
centroid / sum Ok(centroid / sum)
} }
// Without a summed denominator, return the average of all positions instead // Without a summed denominator, return the average of all positions instead
else { else {
@@ -3255,7 +3254,7 @@ async fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<
.inspect(|_| count += 1) .inspect(|_| count += 1)
.sum::<DVec2>(); .sum::<DVec2>();
if count != 0 { summed_positions / (count as f64) } else { DVec2::ZERO } if count != 0 { Ok(summed_positions / (count as f64)) } else { Ok(DVec2::ZERO) }
} }
} }
+1
View File
@@ -23,6 +23,7 @@ serde-discriminant = []
proc-macro2 = { workspace = true } proc-macro2 = { workspace = true }
syn = { workspace = true } syn = { workspace = true }
quote = { workspace = true } quote = { workspace = true }
convert_case = { workspace = true }
[dev-dependencies] [dev-dependencies]
# Local dependencies # Local dependencies
+128
View File
@@ -0,0 +1,128 @@
use convert_case::{Case, Casing};
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{Error, FnArg, Ident, Item, ItemFn, ItemMod, ItemUse, Pat, Visibility};
pub fn editor_commands_impl(attr: TokenStream, module: ItemMod) -> syn::Result<TokenStream> {
if !attr.is_empty() {
return Err(Error::new(attr.span(), "#[editor_commands] takes no arguments"));
}
for attr in &module.attrs {
if !attr.path().is_ident("doc") {
return Err(Error::new(attr.span(), "the #[editor_commands] module may not have other attributes"));
}
}
let Some((_, items)) = module.content else {
return Err(Error::new(module.mod_token.span, "#[editor_commands] requires a module with an inline body"));
};
let mut imports: Vec<ItemUse> = Vec::new();
let mut functions: Vec<ItemFn> = Vec::new();
for item in items {
match item {
Item::Use(import) => imports.push(import),
Item::Fn(function) => functions.push(function),
other => return Err(Error::new(other.span(), "only `use` imports and command functions may appear in an #[editor_commands] module")),
}
}
let mut variants = TokenStream::new();
let mut stubs = TokenStream::new();
let mut arms = TokenStream::new();
for function in &functions {
for attr in &function.attrs {
if !attr.path().is_ident("doc") {
return Err(Error::new(
attr.span(),
"command functions may not have attributes; anything that doesn't fit the `fn name(args…) -> Message` contract belongs in a plain impl block",
));
}
}
if !matches!(function.vis, Visibility::Inherited) {
return Err(Error::new(
function.span(),
"command functions have no visibility modifier; the macro generates the public JS-facing stub",
));
}
let signature = &function.sig;
if let Some(receiver) = signature.receiver() {
return Err(Error::new(receiver.span(), "command functions take no `self`; they are pure `args… -> Message` translations"));
}
if !signature.generics.params.is_empty() || signature.asyncness.is_some() || signature.unsafety.is_some() {
return Err(Error::new(signature.span(), "command functions must be plain non-generic, non-async, safe functions"));
}
let docs = &function.attrs;
let fn_name = &signature.ident;
let variant = Ident::new(&fn_name.to_string().to_case(Case::Pascal), fn_name.span());
let js_name = Ident::new(&fn_name.to_string().to_case(Case::Camel), fn_name.span());
let mut param_names = Vec::new();
let mut param_types = Vec::new();
for parameter in &signature.inputs {
let FnArg::Typed(pat_type) = parameter else { unreachable!("receiver is rejected above") };
let Pat::Ident(pat_ident) = &*pat_type.pat else {
return Err(Error::new(pat_type.span(), "command parameters must be plain identifiers"));
};
param_names.push(&pat_ident.ident);
param_types.push(&*pat_type.ty);
}
let return_type = &signature.output;
let body = &function.block;
let span = fn_name.span();
variants.extend(quote_spanned! {span=>
#(#docs)*
#variant { #(#param_names: #param_types,)* },
});
stubs.extend(quote_spanned! {span=>
#(#docs)*
#[cfg(not(feature = "native"))]
#[wasm_bindgen(js_name = #js_name)]
pub fn #fn_name(&self, #(#param_names: #param_types,)*) {
self.dispatch((move || #return_type #body)())
}
#(#docs)*
#[cfg(feature = "native")]
#[wasm_bindgen(js_name = #js_name)]
pub fn #fn_name(&self, #(#param_names: #param_types,)*) {
self.send(EditorCommand::#variant { #(#param_names,)* })
}
});
arms.extend(quote_spanned! {span=>
EditorCommand::#variant { #(#param_names,)* } => #body,
});
}
Ok(quote! {
#(
#[cfg(feature = "editor")]
#imports
)*
#[cfg(any(feature = "native", not(target_family = "wasm")))]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum EditorCommand {
#variants
}
#[cfg(all(feature = "editor", any(feature = "native", not(target_family = "wasm"))))]
impl From<EditorCommand> for Message {
fn from(command: EditorCommand) -> Self {
match command {
#arms
}
}
}
#[cfg(target_family = "wasm")]
#[wasm_bindgen]
impl EditorWrapper {
#stubs
}
})
}
+8
View File
@@ -3,6 +3,7 @@
mod as_message; mod as_message;
mod combined_message_attrs; mod combined_message_attrs;
mod discriminant; mod discriminant;
mod editor_commands;
mod extract_fields; mod extract_fields;
mod helper_structs; mod helper_structs;
mod helpers; mod helpers;
@@ -15,6 +16,7 @@ mod widget_builder;
use crate::as_message::derive_as_message_impl; use crate::as_message::derive_as_message_impl;
use crate::combined_message_attrs::combined_message_attrs_impl; use crate::combined_message_attrs::combined_message_attrs_impl;
use crate::discriminant::derive_discriminant_impl; use crate::discriminant::derive_discriminant_impl;
use crate::editor_commands::editor_commands_impl;
use crate::extract_fields::derive_extract_field_impl; use crate::extract_fields::derive_extract_field_impl;
use crate::helper_structs::AttrInnerSingleString; use crate::helper_structs::AttrInnerSingleString;
use crate::hierarchical_tree::generate_hierarchical_tree; use crate::hierarchical_tree::generate_hierarchical_tree;
@@ -302,6 +304,12 @@ pub fn message_handler_data(attr: TokenStream, input_item: TokenStream) -> Token
TokenStream::from(message_handler_data_attr_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error())) TokenStream::from(message_handler_data_attr_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
} }
#[proc_macro_attribute]
pub fn editor_commands(attr: TokenStream, input_item: TokenStream) -> TokenStream {
let module = syn::parse_macro_input!(input_item as syn::ItemMod);
TokenStream::from(editor_commands_impl(attr.into(), module).unwrap_or_else(|err| err.to_compile_error()))
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
+9 -1
View File
@@ -8,7 +8,15 @@ use std::path::Path;
use std::process::ExitCode; use std::process::ExitCode;
use std::time::Duration; use std::time::Duration;
const EXCLUDED_DIRECTORIES: &[&str] = &["target", ".git", "frontend/node_modules", "frontend/dist", "frontend/wrapper/pkg", "tools"]; const EXCLUDED_DIRECTORIES: &[&str] = &[
"target",
".git",
"frontend/node_modules",
"frontend/dist",
"frontend/wrapper/pkg",
"frontend/wrapper/pkg-native",
"tools",
];
const INCLUDED_EXTENSIONS: &[&str] = &["rs"]; const INCLUDED_EXTENSIONS: &[&str] = &["rs"];
const DEBOUNCE: Duration = Duration::from_millis(500); const DEBOUNCE: Duration = Duration::from_millis(500);
+11 -7
View File
@@ -10,8 +10,12 @@ pub fn frontend_dir() -> PathBuf {
workspace_dir().join("frontend") workspace_dir().join("frontend")
} }
fn wasm_glue_path() -> PathBuf { fn pkg_dir(native: bool) -> PathBuf {
frontend_dir().join("wrapper").join("pkg").join(format!("{OUT_NAME}.js")) frontend_dir().join("wrapper").join(if native { "pkg-native" } else { "pkg" })
}
fn wasm_glue_path(native: bool) -> PathBuf {
pkg_dir(native).join(format!("{OUT_NAME}.js"))
} }
pub fn setup() -> Result<(), Error> { pub fn setup() -> Result<(), Error> {
@@ -50,15 +54,15 @@ pub fn build_wasm(release: bool, native: bool) -> Result<(), Error> {
pub fn build_wasm_steps(release: bool, native: bool) -> Vec<Expression> { pub fn build_wasm_steps(release: bool, native: bool) -> Vec<Expression> {
let wasm_artifact = target_dir().join(WASM_TARGET).join(if release { "release" } else { "debug" }).join(format!("{OUT_NAME}.wasm")); let wasm_artifact = target_dir().join(WASM_TARGET).join(if release { "release" } else { "debug" }).join(format!("{OUT_NAME}.wasm"));
let pkg_dir = frontend_dir().join("wrapper").join("pkg"); let pkg_dir = pkg_dir(native);
let mut steps = vec![ let mut steps = vec![
cmd!("cargo", "build", "--lib", "--package", WRAPPER_CRATE, "--target", WASM_TARGET) cmd!("cargo", "build", "--lib", "--package", WRAPPER_CRATE, "--target", WASM_TARGET)
.arg_if(release, "--release") .arg_if(release, "--release")
.args_if(native, ["--no-default-features", "--features", "native"]) .args_if(native, ["--no-default-features", "--features", "native"])
.dir(workspace_dir()) .dir(workspace_dir())
.before_spawn(|_| { .before_spawn(move |_| {
if is_build_corrupted() { if is_build_corrupted(wasm_glue_path(native)) {
clean_wasm(); clean_wasm();
} }
Ok(()) Ok(())
@@ -90,8 +94,8 @@ pub fn clean_wasm() -> bool {
true true
} }
pub fn is_build_corrupted() -> bool { pub fn is_build_corrupted(path: PathBuf) -> bool {
let Ok(js) = std::fs::read_to_string(wasm_glue_path()) else { let Ok(js) = std::fs::read_to_string(&path) else {
return false; return false;
}; };
js.contains("from \"env\"") || js.contains("from 'env'") js.contains("from \"env\"") || js.contains("from 'env'")