mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a08514812 | ||
|
|
b58d2ab470 | ||
|
|
2e1d9c04f7 | ||
|
|
5d967a6a17 | ||
|
|
c93395bb8f | ||
|
|
d0dae48575 | ||
|
|
658f37874c | ||
|
|
c01fb080bf | ||
|
|
d1779e8feb | ||
|
|
fa762379e3 | ||
|
|
18225d0c12 | ||
|
|
f01429ff0b | ||
|
|
32068fc8f5 | ||
|
|
00e40b4f53 | ||
|
|
7623b68318 | ||
|
|
837a374554 |
No files matched your search
Generated
+4
-1
@@ -2038,7 +2038,6 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"log",
|
||||
"raster-types",
|
||||
@@ -4880,11 +4879,15 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-core",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"tokio",
|
||||
"vector-nodes",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
|
||||
@@ -97,11 +97,6 @@ impl App {
|
||||
});
|
||||
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
|
||||
|
||||
let completion_render_sender = start_render_sender.clone();
|
||||
DesktopWrapper::set_completion_notifier(move || {
|
||||
let _ = completion_render_sender.try_send(());
|
||||
});
|
||||
|
||||
Self {
|
||||
render_state: None,
|
||||
wgpu_context,
|
||||
|
||||
@@ -228,7 +228,7 @@ impl RenderState {
|
||||
return;
|
||||
};
|
||||
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
|
||||
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
|
||||
let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None));
|
||||
match result {
|
||||
Ok(texture) => {
|
||||
self.overlays_texture = Some(texture.into());
|
||||
|
||||
@@ -52,10 +52,6 @@ impl DesktopWrapper {
|
||||
executor.execute()
|
||||
}
|
||||
|
||||
pub fn set_completion_notifier(notifier: impl Fn() + Send + Sync + 'static) {
|
||||
graphite_editor::node_graph_executor::set_completion_notifier(Arc::new(notifier));
|
||||
}
|
||||
|
||||
pub async fn execute_node_graph() -> NodeGraphExecutionResult {
|
||||
let result = graphite_editor::node_graph_executor::run_node_graph().await;
|
||||
match result {
|
||||
|
||||
@@ -246,10 +246,10 @@ fn test_nested_network_flattening() {
|
||||
#[test]
|
||||
fn test_metadata_preservation() {
|
||||
// Create a network with nodes that have non-default metadata
|
||||
let context_features = ContextDependencies::new(
|
||||
core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
|
||||
core_types::context::ContextFeatures::empty(),
|
||||
);
|
||||
let context_features = ContextDependencies {
|
||||
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
|
||||
@@ -10,10 +10,11 @@ use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::gradient::GradientStops;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
|
||||
use graphene_std::{Artboard, Color, Graphic};
|
||||
use graphene_std::{Artboard, Color, Context, Graphic};
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -166,8 +167,8 @@ macro_rules! generate_layout_downcast {
|
||||
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
|
||||
if false { None }
|
||||
$(
|
||||
else if let Some(element) = $introspected_data.downcast_ref::<$ty>() {
|
||||
Some(element.layout_with_breadcrumb($data))
|
||||
else if let Some(io) = $introspected_data.downcast_ref::<IORecord<Context, $ty>>() {
|
||||
Some(io.output.layout_with_breadcrumb($data))
|
||||
}
|
||||
)*
|
||||
else { None }
|
||||
@@ -177,8 +178,8 @@ macro_rules! generate_layout_downcast {
|
||||
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
|
||||
// `List<NodeId>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
|
||||
// `List` where each item's NodeId resolves against the prefix made up of the items above it.
|
||||
if let Some(list) = introspected_data.downcast_ref::<List<NodeId>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(list, data));
|
||||
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<NodeId>>>() {
|
||||
return Some(table_node_id_path_layout_with_breadcrumb(&io.output, data));
|
||||
}
|
||||
generate_layout_downcast!(introspected_data, data, [
|
||||
List<Artboard>,
|
||||
|
||||
@@ -919,12 +919,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
NodeInput::import(concrete!(String), 1),
|
||||
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
|
||||
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
],
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(concrete!(String), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -999,13 +994,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::import(concrete!(Footprint), 1),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
NodeInput::scope("graphene_std::runtime::RuntimeNode"),
|
||||
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
],
|
||||
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(concrete!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
+4
-4
@@ -29,7 +29,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
|
||||
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
let node_registry = NODE_REGISTRY.lock().unwrap();
|
||||
let empty_implementations: Vec<RegistryEntry> = Vec::new();
|
||||
let empty_implementations: Vec<(NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
let context_type = concrete!(Context);
|
||||
for (id, metadata) in NODE_METADATA.lock().unwrap().iter() {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(id.clone());
|
||||
@@ -48,12 +48,12 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
|
||||
let implementations = node_registry.get(id).unwrap_or(&empty_implementations);
|
||||
|
||||
let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
|
||||
let first_node_io = implementations.first().map(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() });
|
||||
|
||||
let call_arguments: Vec<&Type> = if !implementations.is_empty() {
|
||||
implementations.iter().map(|entry| &entry.io.call_argument).collect()
|
||||
implementations.iter().map(|(_, io)| &io.call_argument).collect()
|
||||
} else if let Some(impls) = extended_node_registry.get(id) {
|
||||
impls.iter().map(|entry| &entry.io.call_argument).collect()
|
||||
impls.keys().map(|io| &io.call_argument).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
@@ -323,7 +323,7 @@ pub(crate) fn property_from_type(
|
||||
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::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||
Type::Record(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
|
||||
Type::Ref(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
|
||||
};
|
||||
|
||||
extra_widgets.push(widgets);
|
||||
@@ -2360,7 +2360,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut input_types = implementations.iter().filter_map(|entry| entry.io.inputs.get(input_index)).collect::<Vec<_>>();
|
||||
let mut input_types = implementations.keys().filter_map(|item| item.inputs.get(input_index)).collect::<Vec<_>>();
|
||||
input_types.sort_by_key(|ty| ty.type_name());
|
||||
let input_type = input_types.first().cloned();
|
||||
|
||||
|
||||
+5
-7
@@ -253,9 +253,8 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
||||
implementations
|
||||
.iter()
|
||||
.filter_map(|entry| {
|
||||
let node_io = &entry.io;
|
||||
.keys()
|
||||
.filter_map(|node_io| {
|
||||
// Check if this NodeIOTypes implementation is valid for the other inputs
|
||||
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
|
||||
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
|
||||
@@ -294,9 +293,8 @@ impl NodeNetworkInterface {
|
||||
let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path);
|
||||
|
||||
implementations
|
||||
.iter()
|
||||
.filter_map(|entry| {
|
||||
let node_io = &entry.io;
|
||||
.keys()
|
||||
.filter_map(|node_io| {
|
||||
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
|
||||
return None;
|
||||
}
|
||||
@@ -325,7 +323,7 @@ impl NodeNetworkInterface {
|
||||
log::error!("Protonode {render_node:?} not found in registry");
|
||||
return Vec::new();
|
||||
};
|
||||
implementations.iter().map(|entry| entry.io.inputs[1].clone()).collect()
|
||||
implementations.keys().map(|types| types.inputs[1].clone()).collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,11 +10,12 @@ use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderC
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{Vector, graphic_types};
|
||||
use graphene_std::{ATTR_TRANSFORM, Graphic, NodeInputDecleration};
|
||||
use graphene_std::{ATTR_TRANSFORM, Context, Graphic, NodeInputDecleration};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
@@ -25,7 +26,7 @@ pub use runtime_io::NodeRuntimeIO;
|
||||
mod runtime;
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ExecutionRequest {
|
||||
execution_id: u64,
|
||||
render_config: RenderConfig,
|
||||
@@ -58,9 +59,6 @@ pub struct NodeGraphExecutor {
|
||||
runtime_io: NodeRuntimeIO,
|
||||
current_execution_id: u64,
|
||||
futures: VecDeque<(u64, ExecutionContext)>,
|
||||
/// The most recently consumed plain render execution, kept so a runtime-replayed response with the same id
|
||||
/// (sent after an async source completion) finds its context again.
|
||||
last_execution_context: Option<(u64, ExecutionContext)>,
|
||||
node_graph_hash: u64,
|
||||
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
|
||||
/// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in,
|
||||
@@ -110,7 +108,6 @@ impl NodeGraphExecutor {
|
||||
let node_executor = Self {
|
||||
futures: Default::default(),
|
||||
runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver),
|
||||
last_execution_context: None,
|
||||
node_graph_hash: 0,
|
||||
current_execution_id: 0,
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
@@ -378,22 +375,10 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
|
||||
let (_, execution_context) = self.futures.pop_front().expect("front was just matched");
|
||||
self.last_execution_context = Some((execution_id, execution_context.clone()));
|
||||
execution_context
|
||||
} else {
|
||||
// A runtime-replayed response re-uses an already consumed id; only plain renders may re-apply.
|
||||
match &self.last_execution_context {
|
||||
Some((last_execution_id, execution_context)) if *last_execution_id == execution_id => {
|
||||
if execution_context.export_config.is_some() || execution_context.measure_fill.is_some() {
|
||||
continue;
|
||||
}
|
||||
execution_context.clone()
|
||||
}
|
||||
_ => panic!("InvalidGenerationId"),
|
||||
}
|
||||
let Some((queued_execution_id, execution_context)) = self.futures.pop_front() else {
|
||||
panic!("InvalidGenerationId")
|
||||
};
|
||||
assert_eq!(queued_execution_id, execution_id, "Missmatch in execution id");
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
// Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork.
|
||||
@@ -899,9 +884,18 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Extract a monitor node's captured output element.
|
||||
/// Extract a monitor node's recorded output, trying each context type the runtime may have evaluated it under.
|
||||
fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> {
|
||||
data.downcast_ref::<T>().cloned()
|
||||
if let Some(io) = data.downcast_ref::<IORecord<(), T>>() {
|
||||
return Some(io.output.clone());
|
||||
}
|
||||
if let Some(io) = data.downcast_ref::<IORecord<Footprint, T>>() {
|
||||
return Some(io.output.clone());
|
||||
}
|
||||
if let Some(io) = data.downcast_ref::<IORecord<Context, T>>() {
|
||||
return Some(io.output.clone());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// Re-export for usage by tests in other modules
|
||||
@@ -917,7 +911,9 @@ mod test {
|
||||
use crate::test_utils::test_prelude::{self, NodeGraphLayer};
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graphene_std::Context;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::memo::IORecord;
|
||||
use test_prelude::LayerNodeIdentifier;
|
||||
|
||||
/// Stores all of the monitor nodes that have been attached to a graph
|
||||
@@ -978,11 +974,17 @@ mod test {
|
||||
where
|
||||
Input::Result: Send + Sync + Clone + 'static,
|
||||
{
|
||||
let element = dynamic.downcast_ref::<Input::Result>().cloned();
|
||||
if element.is_none() {
|
||||
// This is quite inflexible since it only allows the footprint as inputs.
|
||||
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Input::Result>>() {
|
||||
Some(x.output.clone())
|
||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Input::Result>>() {
|
||||
Some(x.output.clone())
|
||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Context, Input::Result>>() {
|
||||
Some(x.output.clone())
|
||||
} else {
|
||||
warn!("cannot downcast type for introspection");
|
||||
None
|
||||
}
|
||||
element
|
||||
}
|
||||
|
||||
/// Grab all of the values of the input every time it occurs in the graph.
|
||||
|
||||
@@ -3,25 +3,25 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::resource::ResourceRegistry;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::core_types::gpoll::GPoll;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::ops::Convert;
|
||||
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
|
||||
use graphene_std::raster_types::Raster;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
|
||||
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
|
||||
use graphene_std::transform::RenderQuality;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Artboard, Graphic};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
|
||||
use graphene_std::{Artboard, Context, Graphic};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use spin::Mutex;
|
||||
use std::sync::Arc;
|
||||
@@ -40,9 +40,6 @@ pub struct NodeRuntime {
|
||||
editor_preferences: EditorPreferences,
|
||||
old_graph: Option<NodeNetwork>,
|
||||
update_thumbnails: bool,
|
||||
graph_runtime: Arc<DynGraphRuntime>,
|
||||
/// The last plain render request, replayed when an async source completion marks the graph dirty.
|
||||
last_render: Option<ExecutionRequest>,
|
||||
|
||||
editor_api: Arc<PlatformEditorApi>,
|
||||
resources: ResourceRegistry,
|
||||
@@ -122,86 +119,20 @@ impl NodeGraphUpdateSender for InternalNodeGraphUpdateSender {
|
||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||
pub static NODE_RUNTIME: once_cell::sync::Lazy<Mutex<Option<NodeRuntime>>> = once_cell::sync::Lazy::new(|| Mutex::new(None));
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub struct TokioSpawner(Option<tokio::runtime::Runtime>);
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl TokioSpawner {
|
||||
pub fn new() -> Self {
|
||||
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Default for TokioSpawner {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Spawner for TokioSpawner {
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
let runtime = self.0.as_ref().expect("runtime lives until drop");
|
||||
let _guard = runtime.enter();
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
runtime.spawn(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Dropping a tokio runtime blocks on its tasks, which panics inside an async context; the tests drop
|
||||
/// [`NodeRuntime`] from one, so shut down in the background instead.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Drop for TokioSpawner {
|
||||
fn drop(&mut self) {
|
||||
if let Some(runtime) = self.0.take() {
|
||||
runtime.shutdown_background();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub struct WasmSpawner;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
impl Spawner for WasmSpawner {
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeRuntime {
|
||||
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
|
||||
#[cfg(target_family = "wasm")]
|
||||
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
|
||||
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(spawner));
|
||||
let mut executor = DynamicExecutor::default();
|
||||
executor.set_runtime(Arc::clone(&graph_runtime));
|
||||
|
||||
Self {
|
||||
executor,
|
||||
executor: DynamicExecutor::default(),
|
||||
receiver,
|
||||
sender: InternalNodeGraphUpdateSender(sender.clone()),
|
||||
editor_preferences: EditorPreferences::default(),
|
||||
old_graph: None,
|
||||
resources: ResourceRegistry::default(),
|
||||
update_thumbnails: true,
|
||||
graph_runtime: Arc::clone(&graph_runtime),
|
||||
last_render: None,
|
||||
|
||||
editor_api: PlatformEditorApi {
|
||||
editor_preferences: Box::new(EditorPreferences::default()),
|
||||
node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)),
|
||||
runtime: RuntimeHandle(graph_runtime),
|
||||
|
||||
#[cfg(not(test))]
|
||||
application_io: None,
|
||||
@@ -226,11 +157,6 @@ impl NodeRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn take_dirty(&self) -> bool {
|
||||
self.executor.take_dirty()
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) -> Option<Texture> {
|
||||
let mut preferences = None;
|
||||
let mut graph = None;
|
||||
@@ -247,9 +173,6 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
let for_export = execution_request.render_config.for_export;
|
||||
if !for_export {
|
||||
self.last_render = Some(execution_request.clone());
|
||||
}
|
||||
|
||||
execution = Some(request);
|
||||
|
||||
@@ -270,10 +193,6 @@ impl NodeRuntime {
|
||||
eyedropper.render_config.pointer = execution.render_config.pointer;
|
||||
}
|
||||
|
||||
if self.executor.take_dirty() && execution.is_none() {
|
||||
execution = self.last_render.clone().map(GraphRuntimeRequest::ExecutionRequest);
|
||||
}
|
||||
|
||||
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
|
||||
|
||||
for request in requests {
|
||||
@@ -284,12 +203,11 @@ impl NodeRuntime {
|
||||
application_io: self.editor_api.application_io.clone(),
|
||||
node_graph_message_sender: Box::new(self.sender.clone()),
|
||||
editor_preferences: Box::new(preferences),
|
||||
runtime: self.editor_api.runtime.clone(),
|
||||
}
|
||||
.into();
|
||||
if let Some(graph) = self.old_graph.clone() {
|
||||
// We ignore this result as compilation errors should have been reported in an earlier iteration
|
||||
let _ = self.update_network(graph);
|
||||
let _ = self.update_network(graph).await;
|
||||
}
|
||||
}
|
||||
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
@@ -304,7 +222,7 @@ impl NodeRuntime {
|
||||
self.resources = resources;
|
||||
|
||||
self.node_graph_errors.clear();
|
||||
let result = self.update_network(network);
|
||||
let result = self.update_network(network).await;
|
||||
let node_graph_errors = self.node_graph_errors.clone();
|
||||
|
||||
self.update_thumbnails = true;
|
||||
@@ -319,7 +237,7 @@ impl NodeRuntime {
|
||||
render_config.export_format = ExportFormat::Svg;
|
||||
}
|
||||
|
||||
let result = self.execute_network(render_config);
|
||||
let result = self.execute_network(render_config).await;
|
||||
let mut responses = VecDeque::new();
|
||||
// TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes
|
||||
if !render_config.for_eyedropper {
|
||||
@@ -340,10 +258,10 @@ impl NodeRuntime {
|
||||
.application_io
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.gpu_executor_arc()
|
||||
.gpu_executor()
|
||||
.expect("GPU executor should be available when we receive a texture");
|
||||
|
||||
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
|
||||
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await;
|
||||
|
||||
let (data, width, height) = raster_cpu.to_flat_u8();
|
||||
|
||||
@@ -364,10 +282,10 @@ impl NodeRuntime {
|
||||
.application_io
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.gpu_executor_arc()
|
||||
.gpu_executor()
|
||||
.expect("GPU executor should be available when we receive a texture");
|
||||
|
||||
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, wgpu_executor::WgpuExecutorHandle(executor)).await;
|
||||
let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await;
|
||||
|
||||
self.sender.send_eyedropper_preview(raster_cpu);
|
||||
continue;
|
||||
@@ -427,7 +345,7 @@ impl NodeRuntime {
|
||||
None
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
async fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone());
|
||||
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||
@@ -450,24 +368,20 @@ impl NodeRuntime {
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||
self.executor.update(proto_network).map_err(|(types, e)| {
|
||||
self.executor.update(proto_network).await.map_err(|(types, e)| {
|
||||
self.node_graph_errors.clone_from(&e);
|
||||
(types, format!("{e:?}"))
|
||||
})
|
||||
}
|
||||
|
||||
fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
|
||||
async fn execute_network(&mut self, render_config: RenderConfig) -> Result<TaggedValue, String> {
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
|
||||
match (&self.executor).execute(render_config).map_err(|e| e.to_string())? {
|
||||
GPoll::Final(value) | GPoll::Partial(value) => Ok(value),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||
Ok(value)
|
||||
}
|
||||
GPoll::Pending => Err("Node graph evaluation is pending".to_string()),
|
||||
GPoll::Error(error) => Err(format!("Node graph evaluation failed: {error:?}")),
|
||||
match self.executor.input_type() {
|
||||
Some(t) if t == concrete!(RenderConfig) => (&self.executor).execute(render_config).await.map_err(|e| e.to_string()),
|
||||
Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()),
|
||||
Some(t) => Err(format!("Invalid input type {t:?}")),
|
||||
_ => Err(format!("No input type:\n{:?}", self.node_graph_errors)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -501,30 +415,30 @@ impl NodeRuntime {
|
||||
};
|
||||
|
||||
// Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
|
||||
if let Some(list) = introspected_data.downcast_ref::<List<Graphic>>() {
|
||||
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Graphic>>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(list, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
|
||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(&io.output, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
|
||||
// clips content to those rectangles so anything outside isn't visible
|
||||
else if let Some(list) = introspected_data.downcast_ref::<List<Artboard>>() {
|
||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Artboard>>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = artboard_clip_bounds(list);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
|
||||
let bounds = artboard_clip_bounds(&io.output);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Vector list: vector modifications
|
||||
else if let Some(list) = introspected_data.downcast_ref::<List<Vector>>() {
|
||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Vector>>>() {
|
||||
// Insert the vector modify
|
||||
self.vector_modify.insert(parent_network_node_id, list.element(0).cloned().unwrap_or_default());
|
||||
self.vector_modify.insert(parent_network_node_id, io.output.element(0).cloned().unwrap_or_default());
|
||||
}
|
||||
// String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
|
||||
else if let Some(list) = introspected_data.downcast_ref::<List<String>>() {
|
||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<String>>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = graphene_std::renderer::text_list_bounding_box(list, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
|
||||
let bounds = graphene_std::renderer::text_list_bounding_box(&io.output, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Other
|
||||
@@ -630,6 +544,14 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
[center - half, center + half]
|
||||
}
|
||||
|
||||
pub async fn introspect_node(path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let runtime = NODE_RUNTIME.lock();
|
||||
if let Some(ref mut runtime) = runtime.as_ref() {
|
||||
return runtime.executor.introspect(path);
|
||||
}
|
||||
Err(IntrospectError::RuntimeNotReady)
|
||||
}
|
||||
|
||||
pub async fn run_node_graph() -> (bool, Option<Texture>) {
|
||||
let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) };
|
||||
if let Some(ref mut runtime) = runtime.as_mut() {
|
||||
@@ -649,20 +571,12 @@ pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_completion_notifier(notifier: Arc<DynNotifier>) {
|
||||
let node_runtime = NODE_RUNTIME.lock();
|
||||
if let Some(node_runtime) = &*node_runtime {
|
||||
node_runtime.graph_runtime.set_notifier(notifier);
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeRuntime {
|
||||
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
|
||||
self.editor_api = PlatformEditorApi {
|
||||
application_io: Some(application_io.into()),
|
||||
node_graph_message_sender: Box::new(self.sender.clone()),
|
||||
editor_preferences: Box::new(self.editor_preferences.clone()),
|
||||
runtime: self.editor_api.runtime.clone(),
|
||||
}
|
||||
.into();
|
||||
}
|
||||
|
||||
@@ -53,27 +53,6 @@ impl EditorTestUtils {
|
||||
}
|
||||
runtime.run().await;
|
||||
|
||||
// An async source reports `Pending` on the evaluation that starts it and marks the runtime dirty once
|
||||
// it completes, so the value only reaches the render on a follow-up evaluation. The superseded response's
|
||||
// `Pending` error is ignored, but its messages carry the incremental resolved-types delta and must be
|
||||
// dispatched, or the editor's type map desyncs permanently.
|
||||
while runtime.take_dirty() {
|
||||
let mut superseded_messages = VecDeque::new();
|
||||
let _ = editor.poll_node_graph_evaluation(&mut superseded_messages);
|
||||
for message in superseded_messages {
|
||||
editor.handle_message(message);
|
||||
}
|
||||
|
||||
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).unwrap();
|
||||
|
||||
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
|
||||
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
|
||||
}
|
||||
runtime.run().await;
|
||||
}
|
||||
|
||||
let mut messages = VecDeque::new();
|
||||
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
|
||||
return Err(format!("Graph should render\n\n{e}"));
|
||||
|
||||
@@ -9,7 +9,7 @@ pub use graphene_application_io::ApplicationIo;
|
||||
#[derive(Default)]
|
||||
pub struct PlatformApplicationIo {
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu_executor: Option<std::sync::Arc<WgpuExecutor>>,
|
||||
gpu_executor: Option<WgpuExecutor>,
|
||||
resources: Option<Box<dyn resource::LoadResource>>,
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ impl PlatformApplicationIo {
|
||||
|
||||
Self {
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu_executor: executor.map(std::sync::Arc::new),
|
||||
gpu_executor: executor,
|
||||
resources: None,
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ impl PlatformApplicationIo {
|
||||
set_wgpu_available(wgpu_available);
|
||||
|
||||
Self {
|
||||
gpu_executor: executor.map(std::sync::Arc::new),
|
||||
gpu_executor: executor,
|
||||
resources: None,
|
||||
}
|
||||
}
|
||||
@@ -57,12 +57,7 @@ impl ApplicationIo for PlatformApplicationIo {
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
||||
self.gpu_executor.as_deref()
|
||||
}
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
fn gpu_executor_arc(&self) -> Option<std::sync::Arc<Self::Executor>> {
|
||||
self.gpu_executor.clone()
|
||||
self.gpu_executor.as_ref()
|
||||
}
|
||||
|
||||
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
|
||||
|
||||
@@ -8,6 +8,7 @@ pub use core_types::uuid::generate_uuid;
|
||||
use core_types::{Context, ContextDependencies, Cow, MemoHash, ProtoNodeIdentifier, Type};
|
||||
use dyn_any::DynAny;
|
||||
use glam::IVec2;
|
||||
use log::Metadata;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
@@ -214,14 +215,12 @@ impl InlineRust {
|
||||
#[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DocumentNodeMetadata {
|
||||
DocumentNodePath,
|
||||
SourceId,
|
||||
}
|
||||
|
||||
impl DocumentNodeMetadata {
|
||||
pub fn ty(&self) -> Type {
|
||||
match self {
|
||||
DocumentNodeMetadata::DocumentNodePath => concrete!(core_types::list::List<NodeId>),
|
||||
DocumentNodeMetadata::SourceId => concrete!(u64),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -274,7 +273,7 @@ impl NodeInput {
|
||||
NodeInput::Import { import_type, .. } => import_type.clone(),
|
||||
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
|
||||
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
|
||||
NodeInput::Reflection(metadata) => metadata.ty(),
|
||||
NodeInput::Reflection(_) => concrete!(Metadata),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -880,7 +879,7 @@ impl NodeNetwork {
|
||||
|
||||
// Replace value inputs with dedicated value nodes
|
||||
if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) {
|
||||
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id, Some(&mut node.context_features));
|
||||
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id);
|
||||
}
|
||||
|
||||
let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else {
|
||||
@@ -899,7 +898,6 @@ impl NodeNetwork {
|
||||
gen_id,
|
||||
map_ids,
|
||||
id,
|
||||
None,
|
||||
);
|
||||
|
||||
// Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node.
|
||||
@@ -980,12 +978,6 @@ impl NodeNetwork {
|
||||
}
|
||||
}
|
||||
|
||||
fn source_id_for_path(path: &[NodeId]) -> u64 {
|
||||
let mut hasher = graphene_hash::FxHasher64::new();
|
||||
path.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
fn replace_value_inputs_with_nodes(
|
||||
inputs: &mut [NodeInput],
|
||||
@@ -994,7 +986,6 @@ impl NodeNetwork {
|
||||
gen_id: impl Fn() -> NodeId + Copy,
|
||||
map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy,
|
||||
id: NodeId,
|
||||
mut context_features: Option<&mut ContextDependencies>,
|
||||
) {
|
||||
// Replace value exports and imports with value nodes, added inside the nested network
|
||||
for export in inputs {
|
||||
@@ -1005,13 +996,6 @@ impl NodeNetwork {
|
||||
NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed),
|
||||
NodeInput::Reflection(reflect) => match reflect {
|
||||
DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(path.to_vec()).into(), false),
|
||||
DocumentNodeMetadata::SourceId => {
|
||||
let source_id = Self::source_id_for_path(path);
|
||||
if let Some(context_features) = context_features.as_deref_mut() {
|
||||
context_features.add_sources(&[source_id]);
|
||||
}
|
||||
(TaggedValue::U64(source_id).into(), false)
|
||||
}
|
||||
},
|
||||
previous_export => {
|
||||
*export = previous_export;
|
||||
@@ -1224,9 +1208,7 @@ fn migrate_call_argument<'de, D: serde::Deserializer<'de>>(deserializer: D) -> R
|
||||
Old(Option<Type>),
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this migration document upgrade code
|
||||
Ok(match CallArg::deserialize(deserializer)? {
|
||||
CallArg::New(Type::Concrete(descriptor)) if descriptor.name.ends_with("OwnedContextImpl>>") => concrete!(Context),
|
||||
CallArg::New(ty) => ty,
|
||||
CallArg::Old(ty) => ty.unwrap_or_default(),
|
||||
})
|
||||
|
||||
@@ -1,18 +1,13 @@
|
||||
use super::DocumentNode;
|
||||
use crate::application_io::PlatformEditorApi;
|
||||
use crate::application_io::resource::Resource;
|
||||
use crate::proto::Any as DAny;
|
||||
use crate::proto::{Any as DAny, FutureAny};
|
||||
use brush_nodes::brush_stroke::BrushStroke;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::context::Context;
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::List;
|
||||
use core_types::node::Node;
|
||||
use core_types::registry::{EdgeHandle, edge_type};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::value::record_value_edge;
|
||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
|
||||
use core_types::{CacheHash, Color, ContextFeatures, MemoHash, Node, Type, TypeDescriptor};
|
||||
use dyn_any::DynAny;
|
||||
pub use dyn_any::StaticType;
|
||||
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
@@ -24,6 +19,7 @@ use graphic_types::{Artboard, Graphic, Vector};
|
||||
use rendering::RenderMetadata;
|
||||
use std::fmt::Display;
|
||||
use std::hash::Hash;
|
||||
use std::marker::PhantomData;
|
||||
use std::str::FromStr;
|
||||
pub use std::sync::Arc;
|
||||
use text_nodes::Font;
|
||||
@@ -94,7 +90,7 @@ macro_rules! tagged_value {
|
||||
DocumentNode(DocumentNode),
|
||||
/// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`.
|
||||
#[serde(skip)]
|
||||
ContextModification(ContextModification),
|
||||
ContextFeatures(ContextFeatures),
|
||||
#[serde(skip)]
|
||||
EditorApi(Arc<PlatformEditorApi>),
|
||||
/// Only used by the `resource` node, should never be serialized
|
||||
@@ -124,7 +120,7 @@ macro_rules! tagged_value {
|
||||
// =======================
|
||||
Self::NodeIdPath(path) => path.hash(state),
|
||||
Self::DocumentNode(node) => node.cache_hash(state),
|
||||
Self::ContextModification(modification) => modification.cache_hash(state),
|
||||
Self::ContextFeatures(features) => features.cache_hash(state),
|
||||
Self::RenderOutput(x) => x.cache_hash(state),
|
||||
Self::EditorApi(x) => x.cache_hash(state),
|
||||
Self::ResourceHash(x) => x.cache_hash(state),
|
||||
@@ -179,7 +175,7 @@ macro_rules! tagged_value {
|
||||
Box::new(list)
|
||||
}
|
||||
Self::DocumentNode(node) => Box::new(node),
|
||||
Self::ContextModification(modification) => Box::new(modification),
|
||||
Self::ContextFeatures(features) => Box::new(features),
|
||||
Self::EditorApi(x) => Box::new(x),
|
||||
Self::ResourceHash(x) => Box::new(x),
|
||||
}
|
||||
@@ -229,7 +225,7 @@ macro_rules! tagged_value {
|
||||
Arc::new(list)
|
||||
}
|
||||
Self::DocumentNode(node) => Arc::new(node),
|
||||
Self::ContextModification(modification) => Arc::new(modification),
|
||||
Self::ContextFeatures(features) => Arc::new(features),
|
||||
Self::EditorApi(x) => Arc::new(x),
|
||||
Self::ResourceHash(x) => Arc::new(x),
|
||||
}
|
||||
@@ -257,112 +253,12 @@ macro_rules! tagged_value {
|
||||
Self::RenderOutput(_) => concrete!(RenderOutput),
|
||||
Self::NodeIdPath(_) => concrete!(List<NodeId>),
|
||||
Self::DocumentNode(_) => concrete!(DocumentNode),
|
||||
Self::ContextModification(_) => concrete!(ContextModification),
|
||||
Self::EditorApi(_) => concrete!(Arc<PlatformEditorApi>),
|
||||
Self::ContextFeatures(_) => concrete!(ContextFeatures),
|
||||
Self::EditorApi(_) => concrete!(&PlatformEditorApi),
|
||||
Self::ResourceHash(_) => concrete!(ResourceHash),
|
||||
}
|
||||
}
|
||||
|
||||
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a `ClonedNode` edge typed by [`Self::ty`].
|
||||
pub fn to_edge(self) -> Result<EdgeHandle, String> {
|
||||
match self {
|
||||
// ===============
|
||||
// MANUAL VARIANTS
|
||||
// ===============
|
||||
Self::None => Ok(record_value_edge(())),
|
||||
Self::TypeDefault(td) => {
|
||||
// Same direct-construction path as `to_dynany` for the same reason as in `to_dynany`.
|
||||
let name = td.name.as_ref();
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if name == std::any::type_name::<$type_default>() { return Ok(record_value_edge(<$type_default>::default())); }
|
||||
};
|
||||
}
|
||||
for_each_type_default!(check);
|
||||
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
|
||||
}
|
||||
Self::F64Array(values) => {
|
||||
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Ok(record_value_edge(list))
|
||||
}
|
||||
Self::Color(color) => {
|
||||
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Ok(record_value_edge(list))
|
||||
}
|
||||
Self::Gradient(stops) => Ok(record_value_edge(List::<GradientStops>::new_from_element(stops))),
|
||||
Self::BrushStrokes(strokes) => {
|
||||
let list: List<BrushStroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Ok(record_value_edge(list))
|
||||
}
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$( Self::$identifier(x) => Ok(record_value_edge(x)), )*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(x) => Ok(record_value_edge(x)),
|
||||
Self::NodeIdPath(path) => {
|
||||
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Ok(record_value_edge(list))
|
||||
}
|
||||
Self::DocumentNode(node) => Ok(record_value_edge(node)),
|
||||
Self::ContextModification(modification) => Ok(record_value_edge(modification)),
|
||||
Self::EditorApi(x) => Ok(record_value_edge(x)),
|
||||
Self::ResourceHash(x) => Ok(record_value_edge(x)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates a typed edge and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
|
||||
pub fn from_edge(handle: EdgeHandle, ctx: &Context) -> Result<GPoll<Self>, String> {
|
||||
let ty = handle.ty().clone();
|
||||
// ===============
|
||||
// MANUAL VARIANTS
|
||||
// ===============
|
||||
if ty == edge_type::<()>() {
|
||||
return Ok(handle.downcast::<()>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(|_| TaggedValue::None));
|
||||
}
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$(
|
||||
if ty == edge_type::<$ty>() {
|
||||
return Ok(handle.downcast::<$ty>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(TaggedValue::$identifier));
|
||||
}
|
||||
)*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
if ty == edge_type::<RenderOutput>() {
|
||||
return Ok(handle.downcast::<RenderOutput>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(TaggedValue::RenderOutput));
|
||||
}
|
||||
// =======================
|
||||
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
|
||||
// =======================
|
||||
if ty == core_types::registry::record_edge_type::<()>() {
|
||||
return Ok(handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(|_| TaggedValue::None));
|
||||
}
|
||||
$(
|
||||
if ty == core_types::registry::record_edge_type::<$ty>() {
|
||||
let layout = handle.layout().ok_or_else(|| "a record edge must carry its layout".to_string())?.clone();
|
||||
return Ok(handle
|
||||
.downcast_record::<$ty>()
|
||||
.map_err(|e| format!("{e:?}"))?
|
||||
.eval(ctx)
|
||||
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
|
||||
}
|
||||
)*
|
||||
if ty == core_types::registry::record_edge_type::<RenderOutput>() {
|
||||
let layout = handle.layout().ok_or_else(|| "a record edge must carry its layout".to_string())?.clone();
|
||||
return Ok(handle
|
||||
.downcast_record::<RenderOutput>()
|
||||
.map_err(|e| format!("{e:?}"))?
|
||||
.eval(ctx)
|
||||
.map(|value| TaggedValue::RenderOutput(unsafe { core_types::record::read_element::<RenderOutput>(layout.rec(&value)) })));
|
||||
}
|
||||
Err(format!("Cannot convert edge of type {ty} to TaggedValue"))
|
||||
}
|
||||
|
||||
/// Attempts to downcast the dynamic type to a tagged value
|
||||
pub fn try_from_any(input: Box<dyn DynAny<'a> + 'a>) -> Result<Self, String> {
|
||||
use dyn_any::downcast;
|
||||
@@ -413,7 +309,7 @@ macro_rules! tagged_value {
|
||||
pub fn from_type(input: &Type) -> Option<Self> {
|
||||
match input {
|
||||
Type::Generic(_) => None,
|
||||
Type::Record(inner) => Self::from_type(inner),
|
||||
Type::Ref(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
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
|
||||
@@ -464,7 +360,7 @@ macro_rules! tagged_value {
|
||||
Self::RenderOutput(_) => "RenderOutput".to_string(),
|
||||
Self::NodeIdPath(path) => format!("NodeIdPath({path:?})"),
|
||||
Self::DocumentNode(node) => format!("DocumentNode({node:?})"),
|
||||
Self::ContextModification(modification) => format!("ContextModification({modification:?})"),
|
||||
Self::ContextFeatures(features) => format!("ContextFeatures({features:?})"),
|
||||
Self::EditorApi(_) => "PlatformEditorApi".to_string(),
|
||||
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
|
||||
}
|
||||
@@ -674,7 +570,7 @@ impl TaggedValue {
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
Type::Record(_) => None,
|
||||
Type::Ref(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
let ty = concrete_type.id?;
|
||||
use std::any::TypeId;
|
||||
@@ -790,6 +686,39 @@ impl Display for TaggedValue {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UpcastNode {
|
||||
value: MemoHash<TaggedValue>,
|
||||
}
|
||||
impl<'input> Node<'input, DAny<'input>> for UpcastNode {
|
||||
type Output = FutureAny<'input>;
|
||||
|
||||
fn eval(&'input self, _: DAny<'input>) -> Self::Output {
|
||||
let memo_clone = MemoHash::clone(&self.value);
|
||||
Box::pin(async move { memo_clone.into_inner().as_ref().clone().to_dynany() })
|
||||
}
|
||||
}
|
||||
impl UpcastNode {
|
||||
pub fn new(value: MemoHash<TaggedValue>) -> Self {
|
||||
Self { value }
|
||||
}
|
||||
}
|
||||
#[derive(Default, Debug, Clone, Copy)]
|
||||
pub struct UpcastAsRefNode<T: AsRef<U> + Sync + Send, U: Sync + Send>(pub T, PhantomData<U>);
|
||||
|
||||
impl<'i, T: 'i + AsRef<U> + Sync + Send, U: 'i + StaticType + Sync + Send> Node<'i, DAny<'i>> for UpcastAsRefNode<T, U> {
|
||||
type Output = FutureAny<'i>;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _: DAny<'i>) -> Self::Output {
|
||||
Box::pin(async move { Box::new(self.0.as_ref()) as DAny<'i> })
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<U> + Sync + Send, U: Sync + Send> UpcastAsRefNode<T, U> {
|
||||
pub const fn new(value: T) -> UpcastAsRefNode<T, U> {
|
||||
UpcastAsRefNode(value, PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RenderOutput {
|
||||
pub data: RenderOutputType,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::document::NodeNetwork;
|
||||
use crate::proto::ProtoNetwork;
|
||||
use crate::proto::{LocalFuture, ProtoNetwork};
|
||||
use std::error::Error;
|
||||
|
||||
pub struct Compiler {}
|
||||
@@ -33,5 +33,5 @@ impl Compiler {
|
||||
}
|
||||
|
||||
pub trait Executor<I, O> {
|
||||
fn execute(&self, input: I) -> Result<O, Box<dyn Error>>;
|
||||
fn execute(&self, input: I) -> LocalFuture<'_, Result<O, Box<dyn Error>>>;
|
||||
}
|
||||
@@ -258,11 +258,6 @@ impl ProtoNetwork {
|
||||
self.replace_node_id(&outwards_edges, NodeId(index as u64), sni);
|
||||
self.nodes[index].0 = sni;
|
||||
}
|
||||
|
||||
// Equal nodes hash to one id; the copies must go, or a pass that
|
||||
// rewrites one of them (like adapter splicing) leaves the others stale.
|
||||
let mut seen = HashSet::new();
|
||||
self.nodes.retain(|(id, _)| seen.insert(*id));
|
||||
}
|
||||
|
||||
// TODO: Remove
|
||||
@@ -299,10 +294,6 @@ impl ProtoNetwork {
|
||||
(inwards_edges, id_map)
|
||||
}
|
||||
|
||||
pub fn source_ids(&self) -> Vec<SourceId> {
|
||||
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources().iter().copied()).collect()
|
||||
}
|
||||
|
||||
/// Inserts context nullification nodes to optimize caching.
|
||||
/// This analysis is performed after topological sorting to ensure proper dependency tracking.
|
||||
pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> {
|
||||
@@ -317,7 +308,7 @@ impl ProtoNetwork {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextModification) -> NodeId {
|
||||
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextFeatures) -> NodeId {
|
||||
let (_, node) = &self.nodes[node_id.0 as usize];
|
||||
let mut path = node.original_location.path.clone();
|
||||
|
||||
@@ -347,7 +338,7 @@ impl ProtoNetwork {
|
||||
self.nodes.push((
|
||||
nullification_value_node_id,
|
||||
ProtoNode {
|
||||
construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextModification(context_deps))),
|
||||
construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextFeatures(context_deps))),
|
||||
call_argument: concrete!(Context),
|
||||
identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"),
|
||||
original_location: OriginalLocation {
|
||||
@@ -374,43 +365,42 @@ impl ProtoNetwork {
|
||||
nullification_node_id
|
||||
}
|
||||
|
||||
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextModification, Option<NodeId>) {
|
||||
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextFeatures, Option<NodeId>) {
|
||||
let mut branch_dependencies = Vec::new();
|
||||
let mut combined_deps = ContextModification::default();
|
||||
let mut combined_deps = ContextFeatures::default();
|
||||
let node_index = id.0 as usize;
|
||||
|
||||
let (extract, inject, own_deps) = {
|
||||
let (extract, inject) = {
|
||||
let dependencies = &self.nodes[node_index].1.context_features;
|
||||
let own_deps = ContextModification::from_sources(dependencies.extract, dependencies.sources());
|
||||
(dependencies.extract, dependencies.inject, own_deps)
|
||||
(dependencies.extract, dependencies.inject)
|
||||
};
|
||||
|
||||
let mut inputs = match &self.nodes[node_index].1.construction_args {
|
||||
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
|
||||
ConstructionArgs::Value(_) => return (own_deps, Some(id)),
|
||||
ConstructionArgs::Value(_) => return (extract, Some(id)),
|
||||
ConstructionArgs::Nodes(items) => items.clone(),
|
||||
ConstructionArgs::Inline(_) => return (own_deps, Some(id)),
|
||||
ConstructionArgs::Inline(_) => return (extract, Some(id)),
|
||||
};
|
||||
|
||||
// Compute the dependencies for each branch and combine all of them
|
||||
for &node in &inputs {
|
||||
let branch = self.find_context_dependencies(node);
|
||||
|
||||
combined_deps |= &branch.0;
|
||||
branch_dependencies.push(branch);
|
||||
combined_deps |= branch.0;
|
||||
}
|
||||
let mut new_deps = combined_deps.clone();
|
||||
let mut new_deps = combined_deps;
|
||||
|
||||
// Remove requirements which this node provides
|
||||
new_deps &= !inject;
|
||||
// Add requirements we have
|
||||
new_deps |= own_deps;
|
||||
new_deps |= extract;
|
||||
|
||||
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency
|
||||
let we_introduce_new_deps = !combined_deps.contains(&new_deps);
|
||||
let we_introduce_new_deps = !combined_deps.contains(new_deps);
|
||||
|
||||
// For diverging branches, we can add a cache node for all branches which don't reqire all dependencies
|
||||
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies) {
|
||||
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies.into_iter()) {
|
||||
if let Some(new_id) = new_id {
|
||||
*child_node = new_id;
|
||||
} else if we_introduce_new_deps || deps != combined_deps {
|
||||
@@ -423,15 +413,15 @@ impl ProtoNetwork {
|
||||
let net_injections = inject.difference(extract);
|
||||
|
||||
// Which dependencies still need to be met after this node?
|
||||
let remaining_deps_from_children = combined_deps.features.difference(net_injections);
|
||||
let remaining_deps_from_children = combined_deps.difference(net_injections);
|
||||
|
||||
// Do we satisfy any existing dependencies?
|
||||
let we_supply_existing_deps = !combined_deps.features.difference(remaining_deps_from_children).is_empty();
|
||||
let we_supply_existing_deps = !combined_deps.difference(remaining_deps_from_children).is_empty();
|
||||
|
||||
let mut new_id = None;
|
||||
if we_supply_existing_deps {
|
||||
// Our set of context dependencies has shrunk so we can add a cache node after the current node
|
||||
new_id = Some(self.insert_context_nullification_node(id, new_deps.clone()));
|
||||
new_id = Some(self.insert_context_nullification_node(id, new_deps));
|
||||
}
|
||||
|
||||
(new_deps, new_id)
|
||||
@@ -558,7 +548,6 @@ pub enum GraphErrorType {
|
||||
},
|
||||
NoImplementations,
|
||||
NoConstructor,
|
||||
ConstructionFailed(String),
|
||||
/// The `inputs` represents a formatted list of input indices corresponding to their types.
|
||||
/// Each element in `error_inputs` represents a valid `NodeIOTypes` implementation.
|
||||
/// The inner Vec stores the inputs which need to be changed and what type each needs to be changed to.
|
||||
@@ -579,7 +568,6 @@ impl Debug for GraphErrorType {
|
||||
GraphErrorType::UnexpectedGenerics { index, inputs } => write!(f, "Generic inputs should not exist but found at {index}: {inputs:?}"),
|
||||
GraphErrorType::NoImplementations => write!(f, "No implementations found"),
|
||||
GraphErrorType::NoConstructor => write!(f, "No construct found for node"),
|
||||
GraphErrorType::ConstructionFailed(error) => write!(f, "Construction failed: {error}"),
|
||||
GraphErrorType::InvalidImplementations { inputs, error_inputs } => {
|
||||
let format_error = |(index, (found, expected)): &(usize, (Type, Type))| {
|
||||
let index = index + 1;
|
||||
@@ -646,14 +634,14 @@ pub type GraphErrors = Vec<GraphError>;
|
||||
/// The `TypingContext` is used to store the types of the nodes indexed by their stable node id.
|
||||
#[derive(Default, Clone, dyn_any::DynAny)]
|
||||
pub struct TypingContext {
|
||||
lookup: Cow<'static, HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>>,
|
||||
lookup: Cow<'static, HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>>,
|
||||
inferred: HashMap<NodeId, NodeIOTypes>,
|
||||
constructor: HashMap<NodeId, NodeConstructor>,
|
||||
}
|
||||
|
||||
impl TypingContext {
|
||||
/// Creates a new `TypingContext` with the given lookup table.
|
||||
pub fn new(lookup: &'static HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>) -> Self {
|
||||
pub fn new(lookup: &'static HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>) -> Self {
|
||||
Self {
|
||||
lookup: Cow::Borrowed(lookup),
|
||||
..Default::default()
|
||||
@@ -663,8 +651,8 @@ impl TypingContext {
|
||||
/// Updates the `TypingContext` with a given proto network. This will infer the types of the nodes
|
||||
/// and store them in the `inferred` field. The proto network has to be topologically sorted
|
||||
/// and contain fully resolved stable node ids.
|
||||
pub fn update(&mut self, network: &mut ProtoNetwork) -> Result<(), GraphErrors> {
|
||||
for (id, node) in &network.nodes {
|
||||
pub fn update(&mut self, network: &ProtoNetwork) -> Result<(), GraphErrors> {
|
||||
for (id, node) in network.nodes.iter() {
|
||||
self.infer(*id, node)?;
|
||||
}
|
||||
|
||||
@@ -694,10 +682,10 @@ impl TypingContext {
|
||||
}
|
||||
|
||||
let inputs = match node.construction_args {
|
||||
// A value node is a native record source, so it types as a record
|
||||
// of its value.
|
||||
// If the node has a value input we can infer the return type from it
|
||||
ConstructionArgs::Value(ref v) => {
|
||||
let types = NodeIOTypes::new(concrete!(Context), Type::Record(Box::new(v.ty())), vec![]);
|
||||
// TODO: This should return a reference to the value
|
||||
let types = NodeIOTypes::new(concrete!(Context), Type::Future(Box::new(v.ty())), vec![]);
|
||||
self.inferred.insert(node_id, types.clone());
|
||||
return Ok(types);
|
||||
}
|
||||
@@ -717,7 +705,6 @@ impl TypingContext {
|
||||
// Get the node input type from the proto node declaration
|
||||
let call_argument = &node.call_argument;
|
||||
let impls = self.lookup.get(&node.identifier).ok_or_else(|| vec![GraphError::new(node, GraphErrorType::NoImplementations)])?;
|
||||
let candidates: Vec<(NodeIOTypes, NodeConstructor)> = impls.iter().map(|entry| (entry.io.clone(), entry.constructor)).collect();
|
||||
|
||||
if let Some(index) = inputs.iter().position(|p| {
|
||||
matches!(p,
|
||||
@@ -726,25 +713,55 @@ impl TypingContext {
|
||||
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs })]);
|
||||
}
|
||||
|
||||
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
|
||||
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
|
||||
fn valid_type(from: &Type, to: &Type) -> bool {
|
||||
match (from, to) {
|
||||
// Direct comparison of two concrete types.
|
||||
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
|
||||
// Check inner type for futures
|
||||
(Type::Future(type1), Type::Future(type2)) => valid_type(type1, type2),
|
||||
// Direct comparison of two function types.
|
||||
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
|
||||
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
|
||||
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
|
||||
// This allows us to supply anything to a function that is satisfied with `()`.
|
||||
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
|
||||
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
|
||||
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
|
||||
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
|
||||
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
|
||||
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
||||
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
||||
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
||||
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
||||
// TODO: Add proper generic counting which is not based on the name
|
||||
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
|
||||
// Reject unknown type relationships.
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
// List of all implementations that match the input types
|
||||
let valid_output_types = candidates
|
||||
.iter()
|
||||
.filter(|(node_io, _)| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
|
||||
let valid_output_types = impls
|
||||
.keys()
|
||||
.filter(|node_io| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Attempt to substitute generic types with concrete types and save the list of results
|
||||
let substitution_results = valid_output_types
|
||||
.iter()
|
||||
.map(|(node_io, constructor)| {
|
||||
.map(|node_io| {
|
||||
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
|
||||
.iter()
|
||||
.map(|generic| check_generic(node_io, call_argument, &inputs, generic).map(|x| (generic.to_string(), x)))
|
||||
.collect();
|
||||
|
||||
generics_lookup.map(|generics_lookup| {
|
||||
let mut new_node_io = node_io.clone();
|
||||
let orig_node_io = (*node_io).clone();
|
||||
let mut new_node_io = orig_node_io.clone();
|
||||
replace_generics(&mut new_node_io, &generics_lookup);
|
||||
(new_node_io, *constructor)
|
||||
(new_node_io, orig_node_io)
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -757,7 +774,7 @@ impl TypingContext {
|
||||
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
|
||||
let mut best_errors = usize::MAX;
|
||||
let mut error_inputs = Vec::new();
|
||||
for (node_io, _) in &candidates {
|
||||
for node_io in impls.keys() {
|
||||
// For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to.
|
||||
let current_errors = [call_argument]
|
||||
.into_iter()
|
||||
@@ -792,72 +809,42 @@ impl TypingContext {
|
||||
.join("\n");
|
||||
Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })])
|
||||
}
|
||||
[(node_io, constructor)] => {
|
||||
[(node_io, org_nio)] => {
|
||||
let node_io = node_io.clone();
|
||||
|
||||
// Save the inferred type
|
||||
self.inferred.insert(node_id, node_io.clone());
|
||||
self.constructor.insert(node_id, *constructor);
|
||||
self.constructor.insert(node_id, impls[org_nio]);
|
||||
Ok(node_io)
|
||||
}
|
||||
// If two types are available and one of them accepts () an input, always choose that one
|
||||
[first, second] => {
|
||||
if first.0.call_argument != second.0.call_argument {
|
||||
for (node_io, constructor) in [first, second] {
|
||||
for (node_io, orig_nio) in [first, second] {
|
||||
if node_io.call_argument != concrete!(()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Save the inferred type
|
||||
self.inferred.insert(node_id, node_io.clone());
|
||||
self.constructor.insert(node_id, *constructor);
|
||||
self.constructor.insert(node_id, impls[orig_nio]);
|
||||
return Ok(node_io.clone());
|
||||
}
|
||||
}
|
||||
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
|
||||
let valid = valid_output_types.into_iter().cloned().collect();
|
||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||
}
|
||||
|
||||
_ => {
|
||||
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
|
||||
let valid = valid_output_types.into_iter().cloned().collect();
|
||||
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
|
||||
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
|
||||
fn valid_type(from: &Type, to: &Type) -> bool {
|
||||
match (from, to) {
|
||||
// Direct comparison of two concrete types.
|
||||
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
|
||||
// Direct comparison of two function types.
|
||||
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
|
||||
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
|
||||
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
|
||||
// This allows us to supply anything to a function that is satisfied with `()`.
|
||||
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
|
||||
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
|
||||
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
|
||||
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
|
||||
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
|
||||
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
||||
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
||||
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
||||
// A lend edge is substitutable exactly when the lent values are.
|
||||
// A record edge is substitutable exactly when the elements are.
|
||||
(Type::Record(in1), Type::Record(in2)) => valid_type(in1, in2),
|
||||
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
||||
// TODO: Add proper generic counting which is not based on the name
|
||||
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
|
||||
// Reject unknown type relationships.
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a list of all generic types used in the node
|
||||
fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
|
||||
let inputs = [&types.call_argument].into_iter().chain(types.inputs.iter().map(|x| x.nested_type()));
|
||||
@@ -876,23 +863,10 @@ fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
|
||||
|
||||
/// Checks if a generic type can be substituted with a concrete type and returns the concrete type
|
||||
fn check_generic(types: &NodeIOTypes, input: &Type, parameters: &[Type], generic: &str) -> Result<Type, String> {
|
||||
fn record_element(ty: Option<&Type>) -> Option<&Type> {
|
||||
match ty {
|
||||
Some(Type::Record(inner)) => Some(inner.as_ref()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
let inputs = [(Some(&types.call_argument), Some(input))]
|
||||
.into_iter()
|
||||
.chain(types.inputs.iter().map(|x| x.fn_input()).zip(parameters.iter().map(|x| x.fn_input())))
|
||||
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())))
|
||||
.chain(
|
||||
types
|
||||
.inputs
|
||||
.iter()
|
||||
.map(|x| record_element(x.fn_output()))
|
||||
.zip(parameters.iter().map(|x| record_element(x.fn_output()))),
|
||||
);
|
||||
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())));
|
||||
let concrete_inputs = inputs.filter(|(ni, _)| matches!(ni, Some(Type::Generic(input)) if generic == input));
|
||||
let mut outputs = concrete_inputs.flat_map(|(_, out)| out);
|
||||
let out_ty = outputs
|
||||
@@ -984,81 +958,6 @@ mod test {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retain_filter_placement_on_source_free_branch() {
|
||||
let mut network = source_branch_network(vec![1], vec![]);
|
||||
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
|
||||
|
||||
let filters = nullification_filters(&network);
|
||||
assert_eq!(filters.len(), 1, "only the source-free branch gets a filter");
|
||||
let (filter_id, wrapped, retained) = &filters[0];
|
||||
assert_eq!(wrapped, "source_b");
|
||||
assert!(retained.is_empty(), "the source-free branch retains no sources");
|
||||
|
||||
let (source_a_id, _) = find_node(&network, "source_a");
|
||||
let (_, join) = find_node(&network, "join");
|
||||
let ConstructionArgs::Nodes(join_args) = &join.construction_args else {
|
||||
panic!("join args must be nodes")
|
||||
};
|
||||
assert_eq!(join_args, &vec![source_a_id, *filter_id], "the source branch stays direct, the filter replaces the source-free branch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diverging_source_sets_filter_each_branch() {
|
||||
let mut network = source_branch_network(vec![1], vec![2]);
|
||||
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
|
||||
|
||||
let mut filters = nullification_filters(&network);
|
||||
filters.sort_by(|(_, a, _), (_, b, _)| a.cmp(b));
|
||||
let summary: Vec<_> = filters.iter().map(|(_, wrapped, retained)| (wrapped.as_str(), retained.as_slice())).collect();
|
||||
assert_eq!(
|
||||
summary,
|
||||
vec![("source_a", &[1u64][..]), ("source_b", &[2u64][..])],
|
||||
"each diverging branch is filtered down to its own source set"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_source_sets_insert_no_filter() {
|
||||
let mut network = source_branch_network(vec![1], vec![1]);
|
||||
network.insert_context_nullification_nodes().expect("Error when calling 'insert_context_nullification_nodes'");
|
||||
|
||||
assert!(nullification_filters(&network).is_empty(), "equal branch source sets need no filter");
|
||||
}
|
||||
|
||||
fn find_node<'a>(network: &'a ProtoNetwork, name: &str) -> (NodeId, &'a ProtoNode) {
|
||||
network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.identifier.as_str() == name)
|
||||
.map(|(id, node)| (*id, node))
|
||||
.unwrap_or_else(|| panic!("node {name} not found"))
|
||||
}
|
||||
|
||||
fn nullification_filters(network: &ProtoNetwork) -> Vec<(NodeId, String, Vec<SourceId>)> {
|
||||
let node = |id: NodeId| &network.nodes[id.0 as usize].1;
|
||||
network
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|(_, candidate)| candidate.identifier.as_str() == graphene_core::context_modification::context_modification::IDENTIFIER.as_str())
|
||||
.map(|(id, candidate)| {
|
||||
let ConstructionArgs::Nodes(args) = &candidate.construction_args else {
|
||||
panic!("filter args must be nodes")
|
||||
};
|
||||
let ConstructionArgs::Nodes(memoized) = &node(args[0]).construction_args else {
|
||||
panic!("filter memoize args must be nodes")
|
||||
};
|
||||
let ConstructionArgs::Value(value) = &node(args[1]).construction_args else {
|
||||
panic!("filter payload must be a value")
|
||||
};
|
||||
let value::TaggedValue::ContextModification(modification) = &**value else {
|
||||
panic!("filter payload must be a context modification")
|
||||
};
|
||||
(*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources().to_vec())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn test_network() -> ProtoNetwork {
|
||||
ProtoNetwork {
|
||||
inputs: vec![NodeId(10)],
|
||||
@@ -1115,44 +1014,6 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
fn source_branch_network(branch_a_sources: Vec<SourceId>, branch_b_sources: Vec<SourceId>) -> ProtoNetwork {
|
||||
let branch = |name: &str, sources: Vec<SourceId>| ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::with_owned_string(name.to_string()),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]),
|
||||
context_features: ContextDependencies::from_sources(&sources),
|
||||
..Default::default()
|
||||
};
|
||||
ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(3),
|
||||
nodes: [
|
||||
(
|
||||
NodeId(0),
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new("value"),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::U32(2).into()),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(NodeId(1), branch("source_a", branch_a_sources)),
|
||||
(NodeId(2), branch("source_b", branch_b_sources)),
|
||||
(
|
||||
NodeId(3),
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new("join"),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn test_network_with_cycles() -> ProtoNetwork {
|
||||
ProtoNetwork {
|
||||
inputs: vec![NodeId(1)],
|
||||
|
||||
@@ -1,40 +1,15 @@
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::core_types::gpoll::GPoll;
|
||||
use graphene_std::core_types::ops::ConvertAsync;
|
||||
use graphene_std::core_types::ops::Convert;
|
||||
use graphene_std::core_types::transform::Footprint;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use std::error::Error;
|
||||
use std::io::Cursor;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::time::Duration;
|
||||
|
||||
const SOURCE_COMPLETION_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
fn execute_until_final(executor: &DynamicExecutor, render_config: RenderConfig, completion: &Receiver<()>) -> Result<TaggedValue, Box<dyn Error>> {
|
||||
loop {
|
||||
while completion.try_recv().is_ok() {}
|
||||
match executor.execute(render_config)? {
|
||||
GPoll::Final(value) => return Ok(value),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
log::warn!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||
return Ok(value);
|
||||
}
|
||||
GPoll::Partial(_) | GPoll::Pending => {
|
||||
completion
|
||||
.recv_timeout(SOURCE_COMPLETION_TIMEOUT)
|
||||
.map_err(|_| format!("Timed out after {}s waiting for async sources to complete", SOURCE_COMPLETION_TIMEOUT.as_secs()))?;
|
||||
}
|
||||
GPoll::Error(error) => return Err(format!("Node graph evaluation failed: {error:?}").into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FileType {
|
||||
Svg,
|
||||
@@ -53,16 +28,14 @@ pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn export_document(
|
||||
pub async fn export_document(
|
||||
executor: &DynamicExecutor,
|
||||
wgpu_executor: wgpu_executor::WgpuExecutorHandle,
|
||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
||||
output_path: PathBuf,
|
||||
file_type: FileType,
|
||||
scale: f64,
|
||||
(width, height): (Option<u32>, Option<u32>),
|
||||
transparent: bool,
|
||||
completion: &Receiver<()>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
// Determine export format based on file type
|
||||
let export_format = match file_type {
|
||||
@@ -84,7 +57,7 @@ pub fn export_document(
|
||||
}
|
||||
|
||||
// Execute the graph
|
||||
let result = execute_until_final(executor, render_config, completion)?;
|
||||
let result = executor.execute(render_config).await?;
|
||||
|
||||
// Handle the result based on output type
|
||||
match result {
|
||||
@@ -97,7 +70,7 @@ pub fn export_document(
|
||||
RenderOutputType::Texture(texture) => {
|
||||
// Convert GPU texture to CPU buffer
|
||||
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
||||
let cpu_raster: Raster<CPU> = block_on(gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()));
|
||||
let cpu_raster: Raster<CPU> = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await;
|
||||
let (data, width, height) = cpu_raster.to_flat_u8();
|
||||
|
||||
// Encode and write raster image
|
||||
@@ -176,14 +149,13 @@ impl AnimationParams {
|
||||
}
|
||||
|
||||
/// Export an animated GIF by rendering multiple frames at different animation times
|
||||
pub fn export_gif(
|
||||
pub async fn export_gif(
|
||||
executor: &DynamicExecutor,
|
||||
wgpu_executor: wgpu_executor::WgpuExecutorHandle,
|
||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
||||
output_path: PathBuf,
|
||||
scale: f64,
|
||||
(width, height): (Option<u32>, Option<u32>),
|
||||
animation: AnimationParams,
|
||||
completion: &Receiver<()>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
use image::codecs::gif::{GifEncoder, Repeat};
|
||||
use image::{Frame, RgbaImage};
|
||||
@@ -223,14 +195,14 @@ pub fn export_gif(
|
||||
}
|
||||
|
||||
// Execute the graph for this frame
|
||||
let result = execute_until_final(executor, render_config, completion)?;
|
||||
let result = executor.execute(render_config).await?;
|
||||
|
||||
// Extract RGBA data from result
|
||||
let (data, img_width, img_height) = match result {
|
||||
TaggedValue::RenderOutput(output) => match output.data {
|
||||
RenderOutputType::Texture(texture) => {
|
||||
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
||||
let cpu_raster: Raster<CPU> = block_on(gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()));
|
||||
let cpu_raster: Raster<CPU> = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await;
|
||||
cpu_raster.to_flat_u8()
|
||||
}
|
||||
RenderOutputType::Buffer { data, width, height } => (data, width, height),
|
||||
|
||||
@@ -7,13 +7,13 @@ use document_format::{GddV1, GddV1Layout};
|
||||
use fern::colors::{Color, ColoredLevelConfig};
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::application_io::EditorPreferences;
|
||||
use graph_craft::application_io::resource::ResourceRegistry;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::load_network;
|
||||
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
|
||||
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::error::Error;
|
||||
@@ -28,35 +28,6 @@ impl NodeGraphUpdateSender for UpdateLogger {
|
||||
}
|
||||
}
|
||||
|
||||
struct TokioSpawner(Option<tokio::runtime::Runtime>);
|
||||
|
||||
impl TokioSpawner {
|
||||
fn new() -> Result<Self, std::io::Error> {
|
||||
Ok(Self(Some(tokio::runtime::Runtime::new()?)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Spawner for TokioSpawner {
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
let runtime = self.0.as_ref().expect("runtime lives until drop");
|
||||
let _guard = runtime.enter();
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
runtime.spawn(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Dropping a tokio runtime blocks on its tasks, which panics inside the async main; shut down in the background instead.
|
||||
impl Drop for TokioSpawner {
|
||||
fn drop(&mut self) {
|
||||
if let Some(runtime) = self.0.take() {
|
||||
runtime.shutdown_background();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser)]
|
||||
#[clap(name = "graphene-cli", version)]
|
||||
pub struct App {
|
||||
@@ -130,7 +101,8 @@ struct GlobalOpts {
|
||||
verbose: u8,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let app = App::parse();
|
||||
|
||||
let log_level = app.global_opts.verbose;
|
||||
@@ -158,7 +130,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let gdd = if is_gdd {
|
||||
let archive = std::fs::read(document_path).map_err(|error| format!("Failed to read document {}: {error}", document_path.display()))?;
|
||||
let container = AnyContainer::Memory(MemoryBackend::new());
|
||||
let gdd = block_on(document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)).map_err(|error| format!("Failed to open document: {error}"))?;
|
||||
let gdd = document_format::Gdd::open_from_archive(archive.as_ref(), container, GddV1Layout)
|
||||
.await
|
||||
.map_err(|error| format!("Failed to open document: {error}"))?;
|
||||
Some(gdd)
|
||||
} else {
|
||||
None
|
||||
@@ -166,7 +140,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
|
||||
if let Command::ExtractLegacyDoc { ref document } = app.command {
|
||||
let Some(gdd) = &gdd else { return Err("ExtractLegacyDoc requires a .gdd document".into()) };
|
||||
let Some(legacy_doc) = block_on(gdd.read_legacy_document()) else {
|
||||
let Some(legacy_doc) = gdd.read_legacy_document().await else {
|
||||
return Err("gdd file did not contain a legacy .graphite document".into());
|
||||
};
|
||||
let mut new_path = document.clone();
|
||||
@@ -179,7 +153,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Build the runtime network: from the `.gdd` registry, or by loading a legacy `.graphite` document.
|
||||
let node_network = match &gdd {
|
||||
Some(gdd) => {
|
||||
let declarations = block_on(gdd.declarations(gdd));
|
||||
let declarations = gdd.declarations(gdd).await;
|
||||
let (node_network, _metadata) = gdd.registry().to_runtime_with_metadata(&declarations)?;
|
||||
node_network
|
||||
}
|
||||
@@ -190,7 +164,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
};
|
||||
|
||||
log::info!("Creating GPU context");
|
||||
let mut application_io = block_on(PlatformApplicationIo::new());
|
||||
let mut application_io = PlatformApplicationIo::new().await;
|
||||
if let Some(gdd) = &gdd {
|
||||
application_io.inject_resource_proxy(Box::new(gdd.resource_proxy()));
|
||||
}
|
||||
@@ -202,22 +176,16 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let application_io_for_api = application_io_arc.clone();
|
||||
|
||||
// Get reference to wgpu executor and clone device handle
|
||||
let wgpu_executor_ref = wgpu_executor::WgpuExecutorHandle(application_io_arc.gpu_executor_arc().unwrap());
|
||||
let wgpu_executor_ref = application_io_arc.gpu_executor().unwrap();
|
||||
let device = wgpu_executor_ref.context().device.clone();
|
||||
|
||||
let preferences = EditorPreferences {
|
||||
max_render_region_size: EditorPreferences::default().max_render_region_size,
|
||||
};
|
||||
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()?) as Box<DynSpawner>));
|
||||
let (completion_sender, completion_receiver) = std::sync::mpsc::channel();
|
||||
graph_runtime.set_notifier(Arc::new(move || {
|
||||
let _ = completion_sender.send(());
|
||||
}));
|
||||
let editor_api = Arc::new(PlatformEditorApi {
|
||||
application_io: Some(application_io_for_api),
|
||||
node_graph_message_sender: Box::new(UpdateLogger {}),
|
||||
editor_preferences: Box::new(preferences),
|
||||
runtime: RuntimeHandle(graph_runtime.clone()),
|
||||
});
|
||||
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref())?;
|
||||
|
||||
@@ -250,7 +218,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let file_type = export::detect_file_type(&output)?;
|
||||
|
||||
// Create executor
|
||||
let executor = create_executor(proto_graph, graph_runtime)?;
|
||||
let executor = create_executor(proto_graph)?;
|
||||
|
||||
if fps <= 0. {
|
||||
return Err("Fps number must be positive".into());
|
||||
@@ -259,9 +227,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
// Perform export based on file type
|
||||
if file_type == export::FileType::Gif {
|
||||
let animation = export::AnimationParams::new(fps, frames, duration);
|
||||
export::export_gif(&executor, wgpu_executor_ref.clone(), output, scale, (width, height), animation, &completion_receiver)?;
|
||||
export::export_gif(&executor, wgpu_executor_ref, output, scale, (width, height), animation).await?;
|
||||
} else {
|
||||
export::export_document(&executor, wgpu_executor_ref.clone(), output, file_type, scale, (width, height), transparent, &completion_receiver)?;
|
||||
export::export_document(&executor, wgpu_executor_ref, output, file_type, scale, (width, height), transparent).await?;
|
||||
}
|
||||
}
|
||||
_ => unreachable!("All other commands should be handled before this match statement is run"),
|
||||
@@ -317,8 +285,7 @@ fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd:
|
||||
compiler.compile_single(network).map_err(|x| x.into())
|
||||
}
|
||||
|
||||
fn create_executor(proto_network: ProtoNetwork, runtime: Arc<DynGraphRuntime>) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||
let mut executor = DynamicExecutor::new(proto_network).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?;
|
||||
executor.set_runtime(runtime);
|
||||
fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||
let executor = block_on(DynamicExecutor::new(proto_network)).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?;
|
||||
Ok(executor)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
use criterion::BenchmarkGroup;
|
||||
use criterion::measurement::Measurement;
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::{DEMO_ART, compile, load_from_name};
|
||||
use graphene_std::application_io::EditorApi;
|
||||
@@ -13,12 +14,10 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
|
||||
let executor = block_on(DynamicExecutor::new(proto_network.clone())).unwrap();
|
||||
(executor, proto_network)
|
||||
}
|
||||
|
||||
// Some benches in this module's include set drive the demos themselves.
|
||||
#[allow(dead_code)]
|
||||
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
|
||||
where
|
||||
F: Fn(&str, &mut BenchmarkGroup<M>),
|
||||
|
||||
@@ -2,7 +2,6 @@ mod benchmark_util;
|
||||
|
||||
use benchmark_util::{bench_for_each_demo, setup_network};
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
|
||||
fn subsequent_evaluations(c: &mut Criterion) {
|
||||
@@ -10,7 +9,9 @@ fn subsequent_evaluations(c: &mut Criterion) {
|
||||
let context = RenderConfig::default();
|
||||
bench_for_each_demo(&mut group, |name, g| {
|
||||
let (executor, _) = setup_network(name);
|
||||
g.bench_function(name, |b| b.iter(|| Executor::execute(&&executor, std::hint::black_box(context)).unwrap()));
|
||||
g.bench_function(name, |b| {
|
||||
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap())
|
||||
});
|
||||
});
|
||||
group.finish();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
mod benchmark_util;
|
||||
|
||||
use benchmark_util::setup_network;
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
use gungraun::prelude::*;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -12,7 +11,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
|
||||
|
||||
// Warm up the cache by running once
|
||||
let context = RenderConfig::default();
|
||||
let _ = Executor::execute(&&executor, context);
|
||||
let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context));
|
||||
|
||||
executor
|
||||
}
|
||||
@@ -21,7 +20,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
|
||||
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
|
||||
let context = RenderConfig::default();
|
||||
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
|
||||
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
|
||||
@@ -9,11 +9,14 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
let network = load_from_name(name);
|
||||
let proto_network = compile(network);
|
||||
let empty = ProtoNetwork::default();
|
||||
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
||||
|
||||
c.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
|| (DynamicExecutor::new(ProtoNetwork::default()).unwrap(), proto_network.clone()),
|
||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
||||
|| (executor.clone(), proto_network.clone()),
|
||||
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
@@ -30,10 +33,10 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
let network = load_from_name(name);
|
||||
let proto_network = compile(network);
|
||||
|
||||
let executor = DynamicExecutor::new(proto_network).unwrap();
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(proto_network)).unwrap();
|
||||
let footprint = Footprint::default();
|
||||
|
||||
c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
|
||||
c.bench_function(name, |b| b.iter(|| futures::executor::block_on((&executor).execute(footprint))));
|
||||
}
|
||||
fn run_once_demo(c: &mut Criterion) {
|
||||
let mut g = c.benchmark_group("Run Once no render");
|
||||
|
||||
@@ -2,7 +2,6 @@ mod benchmark_util;
|
||||
|
||||
use benchmark_util::{bench_for_each_demo, setup_network};
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
|
||||
fn run_once(c: &mut Criterion) {
|
||||
@@ -12,7 +11,7 @@ fn run_once(c: &mut Criterion) {
|
||||
g.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
|| setup_network(name),
|
||||
|(executor, _)| Executor::execute(&&executor, std::hint::black_box(context)).unwrap(),
|
||||
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap(),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
mod benchmark_util;
|
||||
|
||||
use benchmark_util::setup_network;
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io;
|
||||
use gungraun::prelude::*;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -16,7 +15,7 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
|
||||
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
|
||||
let context = application_io::RenderConfig::default();
|
||||
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
|
||||
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
|
||||
@@ -13,10 +13,10 @@ fn update_executor(c: &mut Criterion) {
|
||||
|| {
|
||||
let (_, proto_network) = setup_network(name);
|
||||
let empty = ProtoNetwork::default();
|
||||
let executor = DynamicExecutor::new(empty).unwrap();
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
||||
(executor, proto_network)
|
||||
},
|
||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
||||
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::hint::black_box;
|
||||
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let (_, proto_network) = setup_network(name);
|
||||
let empty = ProtoNetwork::default();
|
||||
let executor = DynamicExecutor::new(empty).unwrap();
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
||||
(executor, proto_network)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
|
||||
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
|
||||
let (mut executor, network) = setup;
|
||||
let _ = black_box(executor.update(black_box(network)));
|
||||
let _ = black_box(futures::executor::block_on(executor.update(black_box(network))));
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
|
||||
@@ -1,30 +1,17 @@
|
||||
use crate::node_registry;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, DynSlot, EvalScope, VarArg, VarArgLink, VarArgSlots};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::node::Node;
|
||||
use core_types::registry::{EdgeHandle, ErasedNode};
|
||||
use core_types::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner};
|
||||
use dyn_any::StaticType;
|
||||
use graph_craft::Type;
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::value::{TaggedValue, UpcastAsRefNode, UpcastNode};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graph_craft::proto::{ConstructionArgs, GraphError, ProtoNetwork, ProtoNode, TypingContext};
|
||||
use graph_craft::proto::{ConstructionArgs, GraphError, LocalFuture, NodeContainer, ProtoNetwork, ProtoNode, SharedNodeContainer, TypeErasedBox, TypingContext};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const ARENA_CAPACITY: usize = 1 << 20;
|
||||
|
||||
fn new_arena() -> Arena {
|
||||
Arena::new(ARENA_CAPACITY).unwrap_or_else(|| {
|
||||
log::error!("arena generations exhausted; continuing without frame caching");
|
||||
Arena::parked()
|
||||
})
|
||||
}
|
||||
use std::sync::Arc;
|
||||
|
||||
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
|
||||
#[derive(Clone)]
|
||||
pub struct DynamicExecutor {
|
||||
output: NodeId,
|
||||
/// Stores all of the dynamic node structs.
|
||||
@@ -33,13 +20,6 @@ pub struct DynamicExecutor {
|
||||
typing_context: TypingContext,
|
||||
// This allows us to keep the nodes around for one more frame which is used for introspection
|
||||
orphaned_nodes: HashSet<NodeId>,
|
||||
arena: Mutex<Arena>,
|
||||
runtime: Arc<DynGraphRuntime>,
|
||||
live_sources: Vec<core_types::SourceId>,
|
||||
}
|
||||
|
||||
fn noop_runtime() -> Arc<DynGraphRuntime> {
|
||||
Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>))
|
||||
}
|
||||
|
||||
impl Default for DynamicExecutor {
|
||||
@@ -49,9 +29,6 @@ impl Default for DynamicExecutor {
|
||||
tree: Default::default(),
|
||||
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
||||
orphaned_nodes: HashSet::new(),
|
||||
arena: Mutex::new(new_arena()),
|
||||
runtime: noop_runtime(),
|
||||
live_sources: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,40 +48,25 @@ pub struct ResolvedDocumentNodeTypesDelta {
|
||||
}
|
||||
|
||||
impl DynamicExecutor {
|
||||
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||
pub async fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&mut proto_network)?;
|
||||
typing_context.update(&proto_network)?;
|
||||
let output = proto_network.output;
|
||||
let sources = proto_network.source_ids();
|
||||
let tree = BorrowTree::new(proto_network, &typing_context)?;
|
||||
let runtime = noop_runtime();
|
||||
runtime.retain_sources(&sources);
|
||||
let tree = BorrowTree::new(proto_network, &typing_context).await?;
|
||||
|
||||
Ok(Self {
|
||||
tree,
|
||||
output,
|
||||
typing_context,
|
||||
orphaned_nodes: HashSet::new(),
|
||||
arena: Mutex::new(new_arena()),
|
||||
runtime,
|
||||
live_sources: sources,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_runtime(&mut self, runtime: Arc<DynGraphRuntime>) {
|
||||
runtime.retain_sources(&self.live_sources);
|
||||
self.runtime = runtime;
|
||||
}
|
||||
|
||||
pub fn take_dirty(&self) -> bool {
|
||||
self.runtime.take_dirty()
|
||||
}
|
||||
|
||||
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
|
||||
#[cfg_attr(debug_assertions, inline(never))]
|
||||
pub fn update(&mut self, mut proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
pub async fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
self.output = proto_network.output;
|
||||
self.typing_context.update(&mut proto_network).map_err(|e| {
|
||||
self.typing_context.update(&proto_network).map_err(|e| {
|
||||
// If there is an error then get types that have been resolved before the error
|
||||
let add = proto_network
|
||||
.nodes
|
||||
@@ -125,10 +87,11 @@ impl DynamicExecutor {
|
||||
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
|
||||
})?;
|
||||
|
||||
let sources = proto_network.source_ids();
|
||||
let (add, orphaned) = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||
self.runtime.retain_sources(&sources);
|
||||
self.live_sources = sources;
|
||||
let (add, orphaned) = self
|
||||
.tree
|
||||
.update(proto_network, &self.typing_context)
|
||||
.await
|
||||
.map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
|
||||
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
|
||||
for node_id in old_to_remove {
|
||||
@@ -145,17 +108,8 @@ impl DynamicExecutor {
|
||||
}
|
||||
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
|
||||
/// A monitor's record capture materializes its element here against the
|
||||
/// arena, inside the introspection window, so consumers downcast the
|
||||
/// element type directly. The captured input context stays on the
|
||||
/// serialized io record for consumers that need it.
|
||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let result = self.tree.introspect(node_path)?;
|
||||
if let Some(io) = result.downcast_ref::<core_types::memo::IORecord<core_types::context::CtxSnapshot, core_types::record::RecordCapture>>() {
|
||||
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
return io.output.materialize_element(&arena).map(Arc::from).ok_or(IntrospectError::NoData);
|
||||
}
|
||||
Ok(result)
|
||||
self.tree.introspect(node_path)
|
||||
}
|
||||
|
||||
pub fn input_type(&self) -> Option<Type> {
|
||||
@@ -181,51 +135,27 @@ impl DynamicExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
impl<I> Executor<I, GPoll<TaggedValue>> for &DynamicExecutor
|
||||
impl<I> Executor<I, TaggedValue> for &DynamicExecutor
|
||||
where
|
||||
I: VarArg + Send + Sync + std::panic::RefUnwindSafe,
|
||||
I: StaticType + 'static + Send + Sync + std::panic::UnwindSafe,
|
||||
{
|
||||
fn execute(&self, input: I) -> Result<GPoll<TaggedValue>, Box<dyn Error>> {
|
||||
let Some(handle) = self.tree.get(self.output) else {
|
||||
return Err("Output node not found in executor".into());
|
||||
};
|
||||
let mut arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
core_types::record::stack::reserve(self.tree.stack_need());
|
||||
let result = eval_root(&mut arena, &self.runtime, &input, |ctx| match TaggedValue::from_edge(handle.duplicate(), ctx) {
|
||||
Ok(poll) => poll.map(Ok),
|
||||
Err(error) => GPoll::Final(Err(error)),
|
||||
});
|
||||
match result {
|
||||
GPoll::Final(value) => Ok(GPoll::Final(value?)),
|
||||
GPoll::Partial(value) => Ok(GPoll::Partial(value?)),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
Ok(GPoll::Fallback(Box::new((value?, error))))
|
||||
}
|
||||
GPoll::Pending => Ok(GPoll::Pending),
|
||||
GPoll::Error(error) => Ok(GPoll::Error(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn eval_root<S, T>(arena: &mut Arena, runtime: &GraphRuntime<S>, call_argument: DynSlot, eval: impl FnOnce(&ContextImpl) -> GPoll<T>) -> GPoll<T> {
|
||||
arena.reset();
|
||||
let generations = runtime.snapshot();
|
||||
let scope = EvalScope::new(None, None, None, &generations, arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
let link = VarArgLink {
|
||||
args: VarArgSlots::Single(call_argument),
|
||||
outer: None,
|
||||
};
|
||||
let ctx = root.with_varargs(&link);
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| eval(&ctx))) {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
arena.reset();
|
||||
GPoll::panicked()
|
||||
}
|
||||
}
|
||||
}
|
||||
fn execute(&self, input: I) -> LocalFuture<'_, Result<TaggedValue, Box<dyn Error>>> {
|
||||
Box::pin(async move {
|
||||
use futures::FutureExt;
|
||||
|
||||
let result = self.tree.eval_tagged_value(self.output, input);
|
||||
let wrapped_result = std::panic::AssertUnwindSafe(result).catch_unwind().await;
|
||||
|
||||
match wrapped_result {
|
||||
Ok(result) => result.map_err(|e| e.into()),
|
||||
Err(e) => {
|
||||
Box::leak(e);
|
||||
Err("Node graph execution panicked".into())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
pub struct InputMapping {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -258,88 +188,85 @@ impl std::fmt::Display for IntrospectError {
|
||||
///
|
||||
/// # Fields
|
||||
///
|
||||
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`EdgeHandle`] and [`Path`].
|
||||
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SharedNodeContainer`] and [`Path`].
|
||||
/// This stores the actual node instances and their associated paths.
|
||||
///
|
||||
/// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`].
|
||||
/// This maps document paths to node IDs and their associated type information.
|
||||
///
|
||||
/// A store of the dynamically typed nodes and also the source map.
|
||||
#[derive(Default)]
|
||||
#[derive(Default, Clone)]
|
||||
pub struct BorrowTree {
|
||||
/// A hashmap of node IDs and dynamically typed nodes.
|
||||
nodes: HashMap<NodeId, (EdgeHandle, Path)>,
|
||||
nodes: HashMap<NodeId, (SharedNodeContainer, Path)>,
|
||||
/// A hashmap from the document path to the proto node ID.
|
||||
source_map: HashMap<Path, (NodeId, NodeTypes)>,
|
||||
/// The record-stack reserve, folded from the graph at construction.
|
||||
stack_need: usize,
|
||||
}
|
||||
|
||||
impl BorrowTree {
|
||||
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
||||
pub async fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
||||
let mut nodes = BorrowTree::default();
|
||||
let output = proto_network.output;
|
||||
let mut deps = HashMap::new();
|
||||
for (id, node) in proto_network.nodes {
|
||||
if let ConstructionArgs::Nodes(ids) = &node.construction_args {
|
||||
deps.insert(id, ids.clone());
|
||||
}
|
||||
nodes.push_node(id, node, typing_context)?
|
||||
nodes.push_node(id, node, typing_context).await?
|
||||
}
|
||||
nodes.stack_need = stack_peak(output, &deps, &|id| nodes.frame_bytes(id));
|
||||
Ok(nodes)
|
||||
}
|
||||
|
||||
/// Pushes new nodes into the tree and return orphaned nodes
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
|
||||
let output = proto_network.output;
|
||||
pub async fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
|
||||
let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect();
|
||||
let mut new_nodes: Vec<_> = Vec::new();
|
||||
let mut deps = HashMap::new();
|
||||
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
|
||||
for (id, node) in proto_network.nodes {
|
||||
if let ConstructionArgs::Nodes(ids) = &node.construction_args {
|
||||
deps.insert(id, ids.clone());
|
||||
}
|
||||
if !self.nodes.contains_key(&id) {
|
||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||
self.push_node(id, node, typing_context)?;
|
||||
self.push_node(id, node, typing_context).await?;
|
||||
} else if self.update_source_map(id, typing_context, &node) {
|
||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||
}
|
||||
old_nodes.remove(&id);
|
||||
}
|
||||
self.stack_need = stack_peak(output, &deps, &|id| self.frame_bytes(id));
|
||||
Ok((new_nodes, old_nodes))
|
||||
}
|
||||
|
||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<EdgeHandle> {
|
||||
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.duplicate()).collect()
|
||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SharedNodeContainer> {
|
||||
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.clone()).collect()
|
||||
}
|
||||
|
||||
fn store_node(&mut self, node: EdgeHandle, id: NodeId, path: Path) {
|
||||
fn store_node(&mut self, node: SharedNodeContainer, id: NodeId, path: Path) {
|
||||
self.nodes.insert(id, (node, path));
|
||||
}
|
||||
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the captured io record for a monitor node. The node path must match the document node path.
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
|
||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||
let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
|
||||
node.serialize().ok_or(IntrospectError::NoData)
|
||||
}
|
||||
|
||||
pub fn get(&self, id: NodeId) -> Option<EdgeHandle> {
|
||||
self.nodes.get(&id).map(|(node, _)| node.duplicate())
|
||||
pub fn get(&self, id: NodeId) -> Option<SharedNodeContainer> {
|
||||
self.nodes.get(&id).map(|(node, _)| node.clone())
|
||||
}
|
||||
|
||||
/// Evaluate a node of the [`BorrowTree`], downcasting its edge to the expected output type.
|
||||
pub fn eval<I, T: 'static>(&self, id: NodeId, input: &I) -> Option<GPoll<T>>
|
||||
/// Evaluate the output node of the [`BorrowTree`].
|
||||
pub async fn eval<'i, I, O>(&'i self, id: NodeId, input: I) -> Option<O>
|
||||
where
|
||||
ErasedNode<T>: Node<I, Output = T>,
|
||||
I: StaticType + 'i + Send + Sync,
|
||||
O: StaticType + 'i,
|
||||
{
|
||||
let (node, _path) = self.nodes.get(&id)?;
|
||||
let edge = node.duplicate().downcast::<T>().ok()?;
|
||||
Some(edge.eval(input))
|
||||
let (node, _path) = self.nodes.get(&id).cloned()?;
|
||||
let output = node.eval(Box::new(input));
|
||||
dyn_any::downcast::<O>(output.await).ok().map(|o| *o)
|
||||
}
|
||||
/// Evaluate the output node of the [`BorrowTree`] and cast it to a tagged value.
|
||||
/// This ensures that no borrowed data can escape the node graph.
|
||||
pub async fn eval_tagged_value<I>(&self, id: NodeId, input: I) -> Result<TaggedValue, String>
|
||||
where
|
||||
I: StaticType + 'static + Send + Sync + std::panic::UnwindSafe,
|
||||
{
|
||||
let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?;
|
||||
let output = node.eval(Box::new(input));
|
||||
TaggedValue::try_from_any(output.await)
|
||||
}
|
||||
|
||||
/// Removes a node from the [`BorrowTree`] and returns its associated path.
|
||||
@@ -366,10 +293,10 @@ impl BorrowTree {
|
||||
/// use interpreted_executor::node_registry;
|
||||
///
|
||||
///
|
||||
/// fn example() -> Result<(), GraphErrors> {
|
||||
/// async fn example() -> Result<(), GraphErrors> {
|
||||
/// let (proto_network, node_id, proto_node) = ProtoNetwork::example();
|
||||
/// let typing_context = TypingContext::default();
|
||||
/// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context)?;
|
||||
/// let typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
||||
/// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context).await?;
|
||||
///
|
||||
/// // Assert that the node exists in the BorrowTree
|
||||
/// assert!(borrow_tree.get(node_id).is_some(), "Node should exist before removal");
|
||||
@@ -466,23 +393,30 @@ impl BorrowTree {
|
||||
/// - `Nodes`: Constructs a node using other nodes as dependencies.
|
||||
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
|
||||
/// - Returns an error if no constructor is found for the given node ID.
|
||||
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
|
||||
async fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
|
||||
self.update_source_map(id, typing_context, &proto_node);
|
||||
let path = proto_node.original_location.path.clone().unwrap_or_default();
|
||||
|
||||
match &proto_node.construction_args {
|
||||
ConstructionArgs::Value(value) => {
|
||||
let node = (**value)
|
||||
.clone()
|
||||
.to_edge()
|
||||
.map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(error))])?;
|
||||
let node = if let TaggedValue::EditorApi(api) = &**value {
|
||||
let editor_api = UpcastAsRefNode::new(api.clone());
|
||||
let node = Box::new(editor_api) as TypeErasedBox<'_>;
|
||||
NodeContainer::new(node)
|
||||
} else {
|
||||
let upcasted = UpcastNode::new(value.to_owned());
|
||||
let node = Box::new(upcasted) as TypeErasedBox<'_>;
|
||||
NodeContainer::new(node)
|
||||
};
|
||||
self.store_node(node, id, path.into());
|
||||
}
|
||||
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
|
||||
ConstructionArgs::Nodes(ids) => {
|
||||
let construction_nodes = self.node_deps(ids);
|
||||
let ids = ids.to_vec();
|
||||
let construction_nodes = self.node_deps(&ids);
|
||||
let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
|
||||
let node = constructor(construction_nodes).map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(format!("{error:?}")))])?;
|
||||
let node = constructor(construction_nodes).await;
|
||||
let node = NodeContainer::new(node);
|
||||
self.store_node(node, id, path.into());
|
||||
}
|
||||
};
|
||||
@@ -493,309 +427,22 @@ impl BorrowTree {
|
||||
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
|
||||
&self.source_map
|
||||
}
|
||||
|
||||
/// The record-stack reserve of an evaluation, folded from the graph at
|
||||
/// construction (see [`stack_peak`]).
|
||||
pub fn stack_need(&self) -> usize {
|
||||
self.stack_need
|
||||
}
|
||||
|
||||
fn frame_bytes(&self, id: NodeId) -> usize {
|
||||
self.nodes.get(&id).and_then(|(handle, _)| handle.layout()).map_or(0, |layout| layout.frame_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
/// Peak record-stack bytes for evaluating `output`'s cone. A node holds its
|
||||
/// inputs' frames until it returns, so its need is its own frame plus every
|
||||
/// input's frame plus the deepest input's peak. Memoized over shared cones.
|
||||
fn stack_peak(output: NodeId, deps: &HashMap<NodeId, Vec<NodeId>>, frame_bytes: &dyn Fn(NodeId) -> usize) -> usize {
|
||||
fn peak(id: NodeId, deps: &HashMap<NodeId, Vec<NodeId>>, frame_bytes: &dyn Fn(NodeId) -> usize, memo: &mut HashMap<NodeId, usize>) -> usize {
|
||||
if let Some(&cached) = memo.get(&id) {
|
||||
return cached;
|
||||
}
|
||||
let mut held = 0;
|
||||
let mut deepest = 0;
|
||||
for &child in deps.get(&id).map_or(&[][..], Vec::as_slice) {
|
||||
let child_frame = frame_bytes(child);
|
||||
held += child_frame;
|
||||
deepest = deepest.max(peak(child, deps, frame_bytes, memo).saturating_sub(child_frame));
|
||||
}
|
||||
let need = frame_bytes(id) + held + deepest;
|
||||
memo.insert(id, need);
|
||||
need
|
||||
}
|
||||
peak(output, deps, frame_bytes, &mut HashMap::new())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use core_types::arena::ArenaCell;
|
||||
use core_types::context::{ExtractFootprint, ExtractVarArgs};
|
||||
use core_types::runtime::{SourceFuture, Spawner};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
|
||||
struct InertSpawner;
|
||||
|
||||
impl Spawner for InertSpawner {
|
||||
fn spawn(&self, _task: SourceFuture) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_peak_folds_a_diamond_chain() {
|
||||
// S3 <- S2 <- S1 <- S0, each consuming the node below on both inputs.
|
||||
let deps = HashMap::from([
|
||||
(NodeId(1), vec![NodeId(0), NodeId(0)]),
|
||||
(NodeId(2), vec![NodeId(1), NodeId(1)]),
|
||||
(NodeId(3), vec![NodeId(2), NodeId(2)]),
|
||||
]);
|
||||
let frame = |_: NodeId| 1;
|
||||
assert_eq!(stack_peak(NodeId(0), &deps, &frame), 1);
|
||||
assert_eq!(stack_peak(NodeId(3), &deps, &frame), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_root_builds_the_bare_root_with_the_call_argument_as_vararg_0() {
|
||||
let mut arena = Arena::new(64).unwrap();
|
||||
let runtime = GraphRuntime::new(InertSpawner);
|
||||
let argument = 21.5f64;
|
||||
let result = eval_root(&mut arena, &runtime, &argument, |ctx| {
|
||||
assert!(ctx.try_footprint().is_none(), "the bare root carries no axes");
|
||||
GPoll::Final(ctx.vararg(0).ok().and_then(|slot| slot.downcast_ref::<f64>()).copied().unwrap_or(0.))
|
||||
});
|
||||
assert_eq!(result, GPoll::Final(21.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_root_resets_the_arena_at_eval_start() {
|
||||
let mut arena = Arena::new(64).unwrap();
|
||||
let runtime = GraphRuntime::new(InertSpawner);
|
||||
let cell = ArenaCell::new();
|
||||
eval_root(&mut arena, &runtime, &(), |ctx| {
|
||||
let (_, weak) = ctx.scope().arena().alloc(5u32).unwrap();
|
||||
cell.store(weak);
|
||||
GPoll::Final(())
|
||||
});
|
||||
assert!(cell.load(&arena).is_some(), "the introspection window spans until the next eval");
|
||||
eval_root(&mut arena, &runtime, &(), |ctx| {
|
||||
assert!(cell.load(ctx.scope().arena()).is_none(), "the reset at eval start reclaims the previous frame");
|
||||
GPoll::Final(())
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panicking_eval_reports_the_error_and_resets_the_arena() {
|
||||
let mut arena = Arena::new(64).unwrap();
|
||||
let runtime = GraphRuntime::new(InertSpawner);
|
||||
let cell = ArenaCell::new();
|
||||
let result: GPoll<()> = eval_root(&mut arena, &runtime, &(), |ctx| {
|
||||
let (_, weak) = ctx.scope().arena().alloc(5u32).unwrap();
|
||||
cell.store(weak);
|
||||
panic!("mid-eval");
|
||||
});
|
||||
assert_eq!(result, GPoll::panicked());
|
||||
assert!(cell.load(&arena).is_none(), "reset-on-panic leaves no stale records");
|
||||
assert_eq!(eval_root(&mut arena, &runtime, &(), |_| GPoll::Final(7u32)), GPoll::Final(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn push_node_sync() {
|
||||
let mut tree = BorrowTree::default();
|
||||
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
|
||||
let context = TypingContext::default();
|
||||
tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
|
||||
let handle = tree.get(NodeId(0)).unwrap();
|
||||
let layout = handle.layout().unwrap().clone();
|
||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let GPoll::Final(value) = edge.eval(&ctx) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(unsafe { core_types::record::read_element::<u32>(layout.rec(&value)) }, 2);
|
||||
}
|
||||
|
||||
fn proto_node(identifier: &'static str, args: Vec<NodeId>) -> ProtoNode {
|
||||
let mut node = ProtoNode::default();
|
||||
node.identifier = graph_craft::ProtoNodeIdentifier::new(identifier);
|
||||
node.call_argument = core_types::concrete!(core_types::context::Context);
|
||||
node.construction_args = ConstructionArgs::Nodes(args);
|
||||
node
|
||||
}
|
||||
|
||||
fn string_value(value: &str) -> ProtoNode {
|
||||
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(value.to_string()).into()), vec![])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clone_node_clones_the_element_out_of_its_record_wire() {
|
||||
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), vec![])),
|
||||
(NodeId(1), proto_node("graphene_core::debug::CloneNode", vec![NodeId(0)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
let arena = Arena::new(1 << 20).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let edge = executor
|
||||
.tree()
|
||||
.get(NodeId(1))
|
||||
.unwrap()
|
||||
.downcast_record::<graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>>()
|
||||
.unwrap();
|
||||
let result = edge.eval(&ctx);
|
||||
assert!(matches!(result, GPoll::Final(_)), "the flipped clone must evaluate over record wires, got a non-final poll");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flipped_ref_parameter_reads_the_borrow_from_its_record_wire() {
|
||||
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(2),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), vec![])),
|
||||
(NodeId(1), ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(4).into()), vec![])),
|
||||
(NodeId(2), proto_node("raster_nodes::image_color_palette::ImageColorPaletteNode", vec![NodeId(0), NodeId(1)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
let arena = Arena::new(1 << 12).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let edge = executor
|
||||
.tree()
|
||||
.get(NodeId(2))
|
||||
.unwrap()
|
||||
.downcast_record::<graphene_std::list::List<graphene_std::raster::color::Color>>()
|
||||
.unwrap();
|
||||
let result = edge.eval(&ctx);
|
||||
assert!(matches!(result, GPoll::Final(_)), "the palette must evaluate through its record wires, got a non-final poll");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_edge_is_a_record_wire_end_to_end() {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(0),
|
||||
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![]))],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
let value = executor.tree().get(NodeId(0)).unwrap();
|
||||
assert_eq!(value.ty(), &core_types::registry::record_edge_type::<f64>());
|
||||
assert!(value.layout().is_some());
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_monitor_row_forwards_and_introspects_through_the_executor() {
|
||||
let mut monitor = proto_node("graphene_core::memo::MonitorNode", vec![NodeId(0)]);
|
||||
monitor.original_location.path = Some(vec![NodeId(9)]);
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])), (NodeId(1), monitor)],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
let element = executor.introspect(&[NodeId(9)]).unwrap();
|
||||
let element = element.downcast_ref::<f64>().expect("a record capture materializes to its element");
|
||||
assert_eq!(*element, 7.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_memoize_row_wires_generically_and_replays_over_record_wires() {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(String::from("cached")).into()), vec![])),
|
||||
(NodeId(1), proto_node("graphene_core::memo::MemoizeNode", vec![NodeId(0)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String(String::from("cached"))));
|
||||
assert_eq!(
|
||||
(&executor).execute(()).unwrap(),
|
||||
GPoll::Final(TaggedValue::String(String::from("cached"))),
|
||||
"the second execution replays the deep copy against a reset arena"
|
||||
);
|
||||
}
|
||||
|
||||
fn modification_value() -> ProtoNode {
|
||||
let modification = core_types::ContextModification::from_sources(core_types::context::ContextFeatures::all(), &[]);
|
||||
ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextModification(modification).into()), vec![])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_context_modification_row_wires_over_a_value_wire() {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(2),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
|
||||
(NodeId(1), modification_value()),
|
||||
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_context_modifications_forward_the_layout() {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(4),
|
||||
nodes: vec![
|
||||
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
|
||||
(NodeId(1), modification_value()),
|
||||
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
|
||||
(NodeId(3), modification_value()),
|
||||
(NodeId(4), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(2), NodeId(3)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stacked_frame_memos_replay_over_record_wires() {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(2),
|
||||
nodes: vec![
|
||||
(NodeId(0), string_value("memoized")),
|
||||
(NodeId(1), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(0)])),
|
||||
(NodeId(2), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(1)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String("memoized".to_string())));
|
||||
assert_eq!(
|
||||
(&executor).execute(()).unwrap(),
|
||||
GPoll::Final(TaggedValue::String("memoized".to_string())),
|
||||
"the frame memo must replay across evaluations"
|
||||
);
|
||||
let future = tree.push_node(NodeId(0), val_1_protonode, &context);
|
||||
futures::executor::block_on(future).unwrap();
|
||||
let _node = tree.get(NodeId(0)).unwrap();
|
||||
let result = futures::executor::block_on(tree.eval(NodeId(0), ()));
|
||||
assert_eq!(result, Some(2u32));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ pub mod util;
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use core_types::*;
|
||||
use futures::executor::block_on;
|
||||
use graphene_core::ops::passthrough;
|
||||
|
||||
#[test]
|
||||
@@ -46,6 +47,6 @@ mod tests {
|
||||
let compiler = Compiler {};
|
||||
let protograph = compiler.compile_single(network).expect("Graph should be generated");
|
||||
|
||||
let _exec = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
let _exec = block_on(DynamicExecutor::new(protograph)).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,12 @@
|
||||
use dyn_any::StaticType;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graph_craft::document::value::RenderOutput;
|
||||
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::application_io::Texture;
|
||||
use graphene_std::brush::brush_stroke::BrushStroke;
|
||||
use graphene_std::gradient::GradientStops;
|
||||
use graphene_std::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
|
||||
#[cfg(target_family = "wasm")]
|
||||
@@ -10,20 +16,19 @@ use graphene_std::raster::GPU;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::raster::*;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::registry::{ConstructionError, EdgeHandle, ErasedNode, NodeIOTypes, RegistryEntry};
|
||||
use graphene_std::render_node::RenderIntermediate;
|
||||
use graphene_std::runtime::RuntimeHandle;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Context, Graphic, ProtoNodeIdentifier, SourceId, concrete, fn_type};
|
||||
use node_registry_macros::{convert_node, into_node};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type_fut, future};
|
||||
use node_registry_macros::{async_node, convert_node, into_node};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "gpu")]
|
||||
use wgpu_executor::WgpuExecutorHandle;
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
let mut node_types: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
|
||||
// TODO: turn into hashmap
|
||||
fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> {
|
||||
let mut node_types: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
// ==========
|
||||
// INTO NODES
|
||||
// ==========
|
||||
@@ -87,6 +92,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
convert_node!(from: List<Raster<GPU>>, to: AttributeValueDyn),
|
||||
convert_node!(from: List<Graphic>, to: AttributeValueDyn),
|
||||
// into_node!(from: List<Raster<CPU>>, to: List<Raster<SRGBA8>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
into_node!(from: &PlatformEditorApi, to: &WgpuExecutor),
|
||||
convert_node!(from: DVec2, to: DVec2),
|
||||
convert_node!(from: List<Vector>, to: List<Vector>),
|
||||
convert_node!(from: DVec2, to: List<Vector>),
|
||||
@@ -96,19 +103,193 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
convert_node!(from: IVec2, to: String),
|
||||
convert_node!(from: DAffine2, to: String),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>, converter: WgpuExecutorHandle),
|
||||
convert_node!(from: List<Raster<CPU>>, to: List<Raster<CPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<CPU>>, to: List<Raster<GPU>>, converter: WgpuExecutorHandle),
|
||||
convert_node!(from: List<Raster<CPU>>, to: List<Raster<GPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>, converter: WgpuExecutorHandle),
|
||||
convert_node!(from: List<Raster<GPU>>, to: List<Raster<GPU>>, converter: &WgpuExecutor),
|
||||
#[cfg(feature = "gpu")]
|
||||
convert_node!(from: List<Raster<GPU>>, to: List<Raster<CPU>>, converter: WgpuExecutorHandle, async),
|
||||
convert_node!(from: List<Raster<GPU>>, to: List<Raster<CPU>>, converter: &WgpuExecutor),
|
||||
// =============
|
||||
// MONITOR NODES
|
||||
// =============
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ()]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Artboard>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Graphic>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Vector>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientStops>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Image<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => String]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => IVec2]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DVec2]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DAffine2]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => bool]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => f64]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u32]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => u64]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => BlendMode]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Texture]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::application_io::resource::Resource]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Option<f64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<NodeId>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<u8>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<bool>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientType>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => AttributeDyn]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ListDyn]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Graphic]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => DocumentNode]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::LuminanceCalculation]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlue]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlueAlpha]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::NoiseType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::FractalType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularDistanceFunction]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularReturnType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::DomainWarpType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RelativeAbsolute]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::SelectiveColorChoice]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
|
||||
// Context nullification
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderOutput, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeDyn, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => graphene_std::ContextFeatures]),
|
||||
#[cfg(target_family = "wasm")]
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => CanvasHandle, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache, Context => graphene_std::ContextFeatures]),
|
||||
// ==========
|
||||
// MEMO NODES
|
||||
// ==========
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ()]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => bool]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Artboard>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Graphic>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Vector>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Image<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientStops>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<NodeId>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<u8>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientType>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeDyn]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ListDyn]),
|
||||
#[cfg(target_family = "wasm")]
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => CanvasHandle]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f64]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f32]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u32]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u64]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DVec2]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => String]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DAffine2]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Footprint]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderOutput]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi]),
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<f64>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Graphic]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Vec2]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Affine2]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DocumentNode]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::LuminanceCalculation]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::QRCodeErrorCorrectionLevel]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlue]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlueAlpha]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::NoiseType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::FractalType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularDistanceFunction]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularReturnType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::DomainWarpType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RelativeAbsolute]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::SelectiveColorChoice]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache]),
|
||||
];
|
||||
// =============
|
||||
// CONVERT NODES
|
||||
@@ -136,22 +317,15 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
.flatten(),
|
||||
);
|
||||
|
||||
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
|
||||
|
||||
let mut map: HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> = HashMap::new();
|
||||
let insert = |map: &mut HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>, id: ProtoNodeIdentifier, entry: RegistryEntry| {
|
||||
let rows = map.entry(id).or_default();
|
||||
if !rows.iter().any(|row| row.io == entry.io) {
|
||||
rows.push(entry);
|
||||
}
|
||||
};
|
||||
|
||||
for (id, entries) in graphene_std::registry::NODE_REGISTRY.lock().unwrap().iter() {
|
||||
for entry in entries {
|
||||
insert(&mut map, id.clone(), entry.clone());
|
||||
for (id, entry) in graphene_std::registry::NODE_REGISTRY.lock().unwrap().iter() {
|
||||
for (constructor, types) in entry.iter() {
|
||||
map.entry(id.clone()).or_default().insert(types.clone(), *constructor);
|
||||
}
|
||||
}
|
||||
|
||||
for (id, entry) in node_types.into_iter() {
|
||||
for (id, node_constructor, types) in node_types.into_iter() {
|
||||
// TODO: this is a hack to remove the newline from the node new_name
|
||||
// This occurs for the ChannelMixerNode presumably because of the long name.
|
||||
// This might be caused by the stringify! macro
|
||||
@@ -164,45 +338,77 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
new_name = path.to_string();
|
||||
}
|
||||
|
||||
insert(&mut map, ProtoNodeIdentifier::with_owned_string(new_name), entry);
|
||||
map.entry(ProtoNodeIdentifier::with_owned_string(new_name)).or_default().insert(types.clone(), node_constructor);
|
||||
}
|
||||
|
||||
map
|
||||
}
|
||||
|
||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||
pub static NODE_REGISTRY: once_cell::sync::Lazy<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>> = once_cell::sync::Lazy::new(node_registry);
|
||||
pub static NODE_REGISTRY: once_cell::sync::Lazy<HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>>> = once_cell::sync::Lazy::new(|| node_registry());
|
||||
|
||||
mod node_registry_macros {
|
||||
macro_rules! async_node {
|
||||
// TODO: we currently need to annotate the type here because the compiler would otherwise (correctly)
|
||||
// TODO: assign a Pin<Box<dyn Future<Output=T>>> type to the node, which is not what we want for now.
|
||||
//
|
||||
// This `params` variant of the macro wraps the normal `fn_params` variant and is used as a shorthand for writing `T` instead of `() => T`
|
||||
($path:ty, input: $input:ty, params: [$($type:ty),*]) => {
|
||||
async_node!($path, input: $input, fn_params: [ $(() => $type),*])
|
||||
};
|
||||
($path:ty, input: $input:ty, fn_params: [$($arg:ty => $type:ty),*]) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(stringify!($path)),
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
args.reverse();
|
||||
let node = <$path>::new($(graphene_std::any::downcast_node::<$arg, $type>(args.pop().expect("Not enough arguments provided to construct node"))),*);
|
||||
let any: DynAnyNode<$input, _, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
{
|
||||
let node = <$path>::new($(
|
||||
graphene_std::any::PanicNode::<$arg, core::pin::Pin<Box<dyn core::future::Future<Output = $type> + Send>>>::new()
|
||||
),*);
|
||||
let params = vec![$(fn_type_fut!($arg, $type)),*];
|
||||
let mut node_io = NodeIO::<'_, $input>::to_async_node_io(&node, params);
|
||||
node_io.call_argument = concrete!(<$input as StaticType>::Static);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! into_node {
|
||||
(from: $from:ty, to: $to:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
|
||||
RegistryEntry {
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![core_types::registry::record_edge_type::<$from>()],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 1 {
|
||||
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let handle = inputs.next().unwrap();
|
||||
let Some(layout) = handle.layout().cloned() else {
|
||||
return Err(ConstructionError::MissingLayout);
|
||||
};
|
||||
let node = graphene_std::ops::IntoNode::<$to, _, $from>::new(handle.downcast_record::<$from>()?, &layout);
|
||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
},
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let node = graphene_std::ops::IntoNode::new(
|
||||
graphene_std::any::downcast_node::<Context, $from>(args.pop().unwrap()),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)),
|
||||
);
|
||||
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
{
|
||||
let node = graphene_std::ops::IntoNode::new(
|
||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)),
|
||||
);
|
||||
let params = vec![fn_type_fut!(Context, $from)];
|
||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
macro_rules! convert_node {
|
||||
(from: $from:ty, to: numbers) => {{
|
||||
let x: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
|
||||
let x: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
convert_node!(from: $from, to: f32),
|
||||
convert_node!(from: $from, to: f64),
|
||||
convert_node!(from: $from, to: i8),
|
||||
@@ -221,7 +427,7 @@ mod node_registry_macros {
|
||||
x
|
||||
}};
|
||||
(from: numbers, to: $to:ty) => {{
|
||||
let x: Vec<(ProtoNodeIdentifier, RegistryEntry)> = vec![
|
||||
let x: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
convert_node!(from: f32, to: $to),
|
||||
convert_node!(from: f64, to: $to),
|
||||
convert_node!(from: i8, to: $to),
|
||||
@@ -242,118 +448,37 @@ mod node_registry_macros {
|
||||
(from: $from:ty, to: $to:ty) => {
|
||||
convert_node!(from: $from, to: $to, converter: ())
|
||||
};
|
||||
(from: $from:ty, to: $to:ty, converter: $convert:ty, async) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
||||
RegistryEntry {
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![
|
||||
core_types::registry::record_edge_type::<$from>(),
|
||||
core_types::registry::record_edge_type::<$convert>(),
|
||||
core_types::registry::record_edge_type::<RuntimeHandle>(),
|
||||
core_types::registry::record_edge_type::<SourceId>(),
|
||||
],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 4 {
|
||||
return Err(ConstructionError::Arity { expected: 4, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let mut claim = || {
|
||||
let handle = inputs.next().unwrap();
|
||||
let Some(layout) = handle.layout().cloned() else {
|
||||
return Err(ConstructionError::MissingLayout);
|
||||
};
|
||||
Ok((handle, layout))
|
||||
};
|
||||
let (value, value_layout) = claim()?;
|
||||
let (converter, converter_layout) = claim()?;
|
||||
let (runtime, runtime_layout) = claim()?;
|
||||
let (source, source_layout) = claim()?;
|
||||
let node = graphene_std::ops::ConvertAsyncNode::<$to, _, _, _, _, $from, $convert>::new(
|
||||
value.downcast_record::<$from>()?,
|
||||
converter.downcast_record::<$convert>()?,
|
||||
runtime.downcast_record::<RuntimeHandle>()?,
|
||||
source.downcast_record::<SourceId>()?,
|
||||
&value_layout,
|
||||
&converter_layout,
|
||||
&runtime_layout,
|
||||
&source_layout,
|
||||
);
|
||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
},
|
||||
},
|
||||
)
|
||||
};
|
||||
(from: $from:ty, to: $to:ty, converter: $convert:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
|
||||
RegistryEntry {
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![core_types::registry::record_edge_type::<$from>(), core_types::registry::record_edge_type::<$convert>()],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 2 {
|
||||
return Err(ConstructionError::Arity { expected: 2, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let value = inputs.next().unwrap();
|
||||
let Some(value_layout) = value.layout().cloned() else {
|
||||
return Err(ConstructionError::MissingLayout);
|
||||
};
|
||||
let converter = inputs.next().unwrap();
|
||||
let Some(converter_layout) = converter.layout().cloned() else {
|
||||
return Err(ConstructionError::MissingLayout);
|
||||
};
|
||||
let node = graphene_std::ops::ConvertNode::<$to, _, _, $from, $convert>::new(
|
||||
value.downcast_record::<$from>()?,
|
||||
converter.downcast_record::<$convert>()?,
|
||||
&value_layout,
|
||||
&converter_layout,
|
||||
|mut args| {
|
||||
Box::pin(async move {
|
||||
let mut args = args.drain(..);
|
||||
let node = graphene_std::ops::ConvertNode::new(
|
||||
graphene_std::any::downcast_node::<Context, $from>(args.next().expect("Convert node did not get first argument")),
|
||||
graphene_std::any::downcast_node::<Context, $convert>(args.next().expect("Convert node did not get converter argument")),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>))
|
||||
);
|
||||
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
|
||||
},
|
||||
let any: DynAnyNode<Context, $to, _> = graphene_std::any::DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox
|
||||
})
|
||||
},
|
||||
{
|
||||
let node = graphene_std::ops::ConvertNode::new(
|
||||
|
||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $from> + Send>>>::new(),
|
||||
graphene_std::any::PanicNode::<Context, core::pin::Pin<Box<dyn core::future::Future<Output = $convert> + Send>>>::new(),
|
||||
graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>))
|
||||
);
|
||||
let params = vec![fn_type_fut!(Context, $from), fn_type_fut!(Context, $convert)];
|
||||
let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
pub(crate) use async_node;
|
||||
pub(crate) use convert_node;
|
||||
pub(crate) use into_node;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graphene_std::Type;
|
||||
|
||||
fn is_record_edge(ty: &Type) -> bool {
|
||||
match ty {
|
||||
Type::Fn(_, output) => matches!(&**output, Type::Record(_)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One wire kind: every row consumes and produces record wires. A plain
|
||||
/// io type here would need a bridge adapter, and those are gone.
|
||||
#[test]
|
||||
fn every_registry_row_is_record_typed() {
|
||||
let mut plain: Vec<String> = Vec::new();
|
||||
for (id, entries) in NODE_REGISTRY.iter() {
|
||||
for entry in entries {
|
||||
let plain_output = !matches!(entry.io.return_value, Type::Record(_));
|
||||
let plain_inputs: Vec<usize> = entry.io.inputs.iter().enumerate().filter(|(_, ty)| !is_record_edge(ty)).map(|(index, _)| index).collect();
|
||||
if plain_output || !plain_inputs.is_empty() {
|
||||
plain.push(format!("{} plain_output={plain_output} plain_inputs={plain_inputs:?}", id.as_str()));
|
||||
}
|
||||
}
|
||||
}
|
||||
plain.sort();
|
||||
assert!(plain.is_empty(), "plain io remains in the registry:\n{}", plain.join("\n"));
|
||||
}
|
||||
}
|
||||
@@ -69,12 +69,12 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
call_argument: concrete!(graphene_std::application_io::RenderConfig),
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
|
||||
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
|
||||
context_features: graphene_std::ContextDependencies::new(
|
||||
ContextFeatures::INDEX | ContextFeatures::VARARGS,
|
||||
ContextFeatures::INDEX,
|
||||
ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
),
|
||||
..Default::default()
|
||||
@@ -99,7 +99,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), concrete!(std::sync::Arc<PlatformEditorApi>)))];
|
||||
let scope_injections = vec![("editor-api".to_string(), (NodeId(2), concrete!(&PlatformEditorApi)))];
|
||||
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
|
||||
@@ -16,7 +16,6 @@ wgpu = ["dep:raster-types", "raster-types/wgpu"]
|
||||
# Local dependencies
|
||||
dyn-any = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
|
||||
@@ -21,9 +21,6 @@ pub trait ApplicationIo {
|
||||
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
||||
None
|
||||
}
|
||||
fn gpu_executor_arc(&self) -> Option<Arc<Self::Executor>> {
|
||||
None
|
||||
}
|
||||
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_>;
|
||||
}
|
||||
|
||||
@@ -34,10 +31,6 @@ impl<T: ApplicationIo> ApplicationIo for &T {
|
||||
(**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<'_> {
|
||||
(**self).load_resource(hash)
|
||||
}
|
||||
@@ -61,7 +54,7 @@ pub trait GetEditorPreferences {
|
||||
fn max_render_region_area(&self) -> u32;
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum ExportFormat {
|
||||
#[default]
|
||||
@@ -69,14 +62,14 @@ pub enum ExportFormat {
|
||||
Raster,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct TimingInformation {
|
||||
pub time: f64,
|
||||
pub animation_time: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct RenderConfig {
|
||||
pub viewport: Footprint,
|
||||
@@ -112,7 +105,6 @@ pub struct EditorApi<Io> {
|
||||
pub node_graph_message_sender: Box<dyn NodeGraphUpdateSender + Send + Sync>,
|
||||
/// Editor preferences made available to the graph through the `PlatformEditorApi`.
|
||||
pub editor_preferences: Box<dyn GetEditorPreferences + Send + Sync>,
|
||||
pub runtime: core_types::runtime::RuntimeHandle,
|
||||
}
|
||||
|
||||
impl<Io> Eq for EditorApi<Io> {}
|
||||
@@ -123,7 +115,6 @@ impl<Io: Default> Default for EditorApi<Io> {
|
||||
application_io: None,
|
||||
node_graph_message_sender: Box::new(Logger),
|
||||
editor_preferences: Box::new(DummyPreferences),
|
||||
runtime: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,18 +84,6 @@ impl Arena {
|
||||
})
|
||||
}
|
||||
|
||||
/// An arena that refuses every allocation and resolves no handle, so a caller that
|
||||
/// cannot fail can degrade instead of propagating exhaustion.
|
||||
pub fn parked() -> Self {
|
||||
LIVE_ARENAS.fetch_add(1, Ordering::Release);
|
||||
Self {
|
||||
generation: AtomicU64::new(PARKED_GENERATION),
|
||||
offset: AtomicUsize::new(0),
|
||||
buf: Box::new([]),
|
||||
drops: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation.load(Ordering::Acquire)
|
||||
}
|
||||
@@ -187,7 +175,7 @@ impl Drop for Arena {
|
||||
|
||||
pub struct ArenaWeak<T> {
|
||||
word: u64,
|
||||
_marker: PhantomData<fn() -> T>,
|
||||
_marker: PhantomData<*const T>,
|
||||
}
|
||||
|
||||
impl<T> Clone for ArenaWeak<T> {
|
||||
|
||||
@@ -1,310 +0,0 @@
|
||||
//! Attribute markers and their census. A marker declares an attribute name
|
||||
//! once, fixing its value type and its name-specific default; the census
|
||||
//! collects every declaration so name resolution, defaults, and diagnostics
|
||||
//! run at graph compile time. One name belongs to one marker, so a name can
|
||||
//! never mean two different types.
|
||||
//!
|
||||
//! Values are `Copy` and pack directly into record fields. Data with drop
|
||||
//! glue rides the arena instead: the marker declares a reference value
|
||||
//! (`&str`), the writing kernel parks the payload in the arena, and the
|
||||
//! record field carries the eval-lifetime reference.
|
||||
|
||||
use crate::list::AnyAttributeValue;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use std::any::TypeId;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::Deref;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
/// Declares an attribute name: one marker per name, fixing the value type and
|
||||
/// the name-specific default. Declare markers through the [`attribute!`]
|
||||
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`].
|
||||
pub trait Attribute: 'static {
|
||||
/// The name as it appears in documents and diagnostics.
|
||||
const NAME: &'static str;
|
||||
/// The value type every read and write of this name shares. The lifetime
|
||||
/// is the evaluation the value flows in; non-reference values ignore it.
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug;
|
||||
/// The name-specific default, filled where an item lacks the attribute.
|
||||
/// Producing a value for any `'e` from no inputs, reference defaults can
|
||||
/// only point at `'static` data, which is what lets the census fill them
|
||||
/// as plain bytes.
|
||||
fn default<'e>() -> Self::Value<'e> {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `ptr` must point at a live field of this marker's value type.
|
||||
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue>;
|
||||
|
||||
/// Re-parks the owned clone [`Self::read_erased`] produced into fresh
|
||||
/// field storage; `None` for plain values, which ride the byte copy.
|
||||
const REPARK: Option<unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>> = None;
|
||||
}
|
||||
|
||||
/// A kernel-facing attribute value. A parameter `Attr<A>` is a read of `A`
|
||||
/// (yielding the declared default where the attribute is absent upstream), an
|
||||
/// `Attr<A>` in the return tuple is a write, and the same marker on both
|
||||
/// sides is a modify.
|
||||
pub struct Attr<'e, A: Attribute>(pub A::Value<'e>);
|
||||
|
||||
impl<'e, A: Attribute> Deref for Attr<'e, A> {
|
||||
type Target = A::Value<'e>;
|
||||
|
||||
fn deref(&self) -> &A::Value<'e> {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e, A: Attribute> Clone for Attr<'e, A> {
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e, A: Attribute> Copy for Attr<'e, A> {}
|
||||
|
||||
impl<'e, A: Attribute> std::fmt::Debug for Attr<'e, A> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple(A::NAME).field(&self.0).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A deletion of `A` in a node's return tuple: the name leaves the output
|
||||
/// layout, so downstream reads yield the declared default again. Functionally
|
||||
/// a write of the default; the value carries nothing.
|
||||
pub struct RemoveAttr<A: Attribute>(PhantomData<A>);
|
||||
|
||||
impl<A: Attribute> RemoveAttr<A> {
|
||||
pub const fn new() -> Self {
|
||||
RemoveAttr(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Attribute> Default for RemoveAttr<A> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// A census row: what is known about one declared attribute name.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AttributeInfo {
|
||||
pub name: &'static str,
|
||||
pub value_type: TypeId,
|
||||
pub value_type_name: &'static str,
|
||||
pub default: fn() -> Box<dyn AnyAttributeValue>,
|
||||
pub size: usize,
|
||||
pub align: usize,
|
||||
/// Writes the declared default's bytes into a `size`-long slice.
|
||||
pub write_default_bytes: fn(&mut [u8]),
|
||||
}
|
||||
|
||||
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
|
||||
assert_eq!(out.len(), size_of::<A::Value<'static>>());
|
||||
let value: A::Value<'static> = A::default();
|
||||
unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
|
||||
}
|
||||
|
||||
/// All declared attribute names, keyed by name.
|
||||
pub static ATTRIBUTE_REGISTRY: LazyLock<Mutex<HashMap<&'static str, AttributeInfo>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// Registers `A` into the census. Called by the [`attribute!`] expansion at
|
||||
/// startup (ctor natively, a `__node_registry_attribute_*` export on wasm).
|
||||
/// Re-registration at the same value type is idempotent; a second marker
|
||||
/// claiming the name at a different value type panics.
|
||||
pub fn register<A: Attribute>()
|
||||
where
|
||||
A::Value<'static>: AnyAttributeValue,
|
||||
{
|
||||
let info = AttributeInfo {
|
||||
name: A::NAME,
|
||||
value_type: TypeId::of::<A::Value<'static>>(),
|
||||
value_type_name: std::any::type_name::<A::Value<'static>>(),
|
||||
default: || Box::new(A::default()),
|
||||
size: size_of::<A::Value<'static>>(),
|
||||
align: align_of::<A::Value<'static>>(),
|
||||
write_default_bytes: write_default_bytes::<A>,
|
||||
};
|
||||
let conflict = match ATTRIBUTE_REGISTRY.lock().unwrap().entry(A::NAME) {
|
||||
Entry::Vacant(vacant) => {
|
||||
vacant.insert(info);
|
||||
None
|
||||
}
|
||||
Entry::Occupied(occupied) => (occupied.get().value_type != info.value_type).then(|| occupied.get().value_type_name),
|
||||
};
|
||||
if let Some(existing) = conflict {
|
||||
panic!("attribute `{}` is declared at two value types: {existing} and {}", A::NAME, info.value_type_name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Looks up a declared name.
|
||||
pub fn info(name: &str) -> Option<AttributeInfo> {
|
||||
ATTRIBUTE_REGISTRY.lock().unwrap().get(name).copied()
|
||||
}
|
||||
|
||||
/// The name-specific default for `name`, if the name is declared.
|
||||
pub fn default_value(name: &str) -> Option<Box<dyn AnyAttributeValue>> {
|
||||
info(name).map(|info| (info.default)())
|
||||
}
|
||||
|
||||
/// Declares attribute markers: for each entry, the marker struct, its
|
||||
/// [`Attribute`] impl, and the census registration.
|
||||
///
|
||||
/// ```
|
||||
/// core_types::attribute! {
|
||||
/// /// How visible the content is.
|
||||
/// pub Opacity("opacity"): f64 = 1.;
|
||||
/// /// The item's label, parked in the arena by the writer.
|
||||
/// pub Label("label"): &str;
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The trailing `= expr` is the name-specific default; without it the value
|
||||
/// type's `Default` applies. A `&T` value carries the eval lifetime, so its
|
||||
/// default must be `'static` data.
|
||||
#[macro_export]
|
||||
macro_rules! attribute {
|
||||
() => {};
|
||||
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): &$value:ty $(= $default:expr)?; $($rest:tt)*) => {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = &'e $value;
|
||||
$(
|
||||
fn default<'e>() -> Self::Value<'e> {
|
||||
$default
|
||||
}
|
||||
)?
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<&$value>().read() }.to_owned())
|
||||
}
|
||||
|
||||
const REPARK: ::core::option::Option<unsafe fn(&dyn $crate::list::AnyAttributeValue, *mut u8, &$crate::arena::Arena) -> ::core::option::Option<()>> = {
|
||||
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
|
||||
let owned: &<$value as ::std::borrow::ToOwned>::Owned = value.as_any().downcast_ref().expect("a reference attribute replays its owned clone");
|
||||
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
|
||||
unsafe { dst.cast::<&$value>().write(::std::borrow::Borrow::borrow(parked)) };
|
||||
::core::option::Option::Some(())
|
||||
}
|
||||
::core::option::Option::Some(repark)
|
||||
};
|
||||
}
|
||||
|
||||
$crate::attribute!(@register $marker);
|
||||
$crate::attribute!($($rest)*);
|
||||
};
|
||||
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): $value:ty $(= $default:expr)?; $($rest:tt)*) => {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = $value;
|
||||
$(
|
||||
fn default<'e>() -> Self::Value<'e> {
|
||||
$default
|
||||
}
|
||||
)?
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<$value>().read() })
|
||||
}
|
||||
}
|
||||
|
||||
$crate::attribute!(@register $marker);
|
||||
$crate::attribute!($($rest)*);
|
||||
};
|
||||
(@register $marker:ident) => {
|
||||
const _: () = {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[$crate::ctor::ctor]
|
||||
fn register() {
|
||||
$crate::attribute::register::<$marker>();
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[unsafe(export_name = concat!("__node_registry_attribute_", stringify!($marker)))]
|
||||
extern "C" fn register() {
|
||||
$crate::attribute::register::<$marker>();
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
attribute! {
|
||||
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
|
||||
pub Transform("transform"): DAffine2;
|
||||
/// Item's `BlendMode`, controlling how it composites with content beneath it.
|
||||
pub BlendMode("blend_mode"): crate::blending::BlendMode;
|
||||
/// Item's opacity multiplier, composed multiplicatively through nested groups.
|
||||
/// Affects content clipped to the item.
|
||||
pub Opacity("opacity"): f64 = 1.;
|
||||
/// Item's fill opacity multiplier. Like opacity but does not affect content clipped to the item.
|
||||
pub OpacityFill("opacity_fill"): f64 = 1.;
|
||||
/// Whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||
pub ClippingMask("clipping_mask"): bool;
|
||||
/// Artboard's top-left corner in document coordinates.
|
||||
pub Location("location"): DVec2;
|
||||
/// A regex named-capture-group's name, or empty for unnamed groups.
|
||||
pub Name("name"): &str;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn census_carries_declared_names() {
|
||||
let row = info("opacity").unwrap();
|
||||
assert_eq!(row.value_type, TypeId::of::<f64>());
|
||||
assert_eq!(info("transform").unwrap().value_type, TypeId::of::<DAffine2>());
|
||||
assert!(info("never_declared").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn name_specific_default_overrides_the_type_default() {
|
||||
assert_eq!(<Opacity as Attribute>::default(), 1.);
|
||||
assert_eq!(<Name as Attribute>::default(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erased_default_downcasts_to_the_declared_type() {
|
||||
let value = default_value("opacity_fill").unwrap();
|
||||
assert_eq!(*value.as_any().downcast_ref::<f64>().unwrap(), 1.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_values_register_at_the_static_instantiation() {
|
||||
let row = info("name").unwrap();
|
||||
assert_eq!(row.value_type, TypeId::of::<&'static str>());
|
||||
assert_eq!(row.size, size_of::<&str>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reregistration_at_the_same_type_is_idempotent() {
|
||||
register::<Opacity>();
|
||||
register::<Opacity>();
|
||||
assert_eq!(info("opacity").unwrap().value_type, TypeId::of::<f64>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "two value types")]
|
||||
fn a_second_marker_at_a_different_type_panics() {
|
||||
struct Conflict;
|
||||
impl Attribute for Conflict {
|
||||
const NAME: &'static str = "opacity";
|
||||
type Value<'e> = bool;
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue> {
|
||||
Box::new(unsafe { ptr.cast::<bool>().read() })
|
||||
}
|
||||
}
|
||||
register::<Conflict>();
|
||||
}
|
||||
}
|
||||
@@ -496,12 +496,185 @@ impl ExtractFootprint for () {
|
||||
}
|
||||
}
|
||||
|
||||
// ==============
|
||||
// TYPE `Context`
|
||||
// ==============
|
||||
// ==========================================
|
||||
// EXTRACT TRAIT IMPLS FOR `OwnedContextImpl`
|
||||
// ==========================================
|
||||
|
||||
pub type Context<'a> = ContextImpl<'a>;
|
||||
impl ArcCtx for OwnedContextImpl {}
|
||||
|
||||
impl ExtractFootprint for OwnedContextImpl {
|
||||
fn try_footprint(&self) -> Option<&Footprint> {
|
||||
self.footprint.as_ref()
|
||||
}
|
||||
}
|
||||
impl ExtractRealTime for OwnedContextImpl {
|
||||
fn try_real_time(&self) -> Option<f64> {
|
||||
self.real_time
|
||||
}
|
||||
}
|
||||
impl ExtractAnimationTime for OwnedContextImpl {
|
||||
fn try_animation_time(&self) -> Option<f64> {
|
||||
self.animation_time
|
||||
}
|
||||
}
|
||||
impl ExtractPointerPosition for OwnedContextImpl {
|
||||
fn try_pointer_position(&self) -> Option<DVec2> {
|
||||
self.pointer_position
|
||||
}
|
||||
}
|
||||
impl ExtractPosition for OwnedContextImpl {
|
||||
fn try_position(&self) -> Option<impl Iterator<Item = DVec2>> {
|
||||
self.position.clone().map(|x| x.into_iter())
|
||||
}
|
||||
}
|
||||
impl ExtractIndex for OwnedContextImpl {
|
||||
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
|
||||
self.index.clone().map(|x| x.into_iter())
|
||||
}
|
||||
}
|
||||
impl ExtractVarArgs for OwnedContextImpl {
|
||||
fn vararg(&self, index: usize) -> Result<DynRef<'_>, VarArgsResult> {
|
||||
let Some(ref inner) = self.varargs else {
|
||||
let Some(ref parent) = self.parent else {
|
||||
return Err(VarArgsResult::NoVarArgs);
|
||||
};
|
||||
return parent.vararg(index);
|
||||
};
|
||||
inner.get(index).map(|x| x.as_ref() as DynRef<'_>).ok_or(VarArgsResult::IndexOutOfBounds)
|
||||
}
|
||||
|
||||
fn varargs_len(&self) -> Result<usize, VarArgsResult> {
|
||||
let Some(ref inner) = self.varargs else {
|
||||
let Some(ref parent) = self.parent else {
|
||||
return Err(VarArgsResult::NoVarArgs);
|
||||
};
|
||||
return parent.varargs_len();
|
||||
};
|
||||
Ok(inner.len())
|
||||
}
|
||||
|
||||
fn hash_varargs(&self, mut hasher: &mut dyn Hasher) {
|
||||
match (&self.varargs, &self.parent) {
|
||||
(Some(inner), _) => {
|
||||
for arg in inner.iter() {
|
||||
arg.hash(&mut hasher);
|
||||
}
|
||||
}
|
||||
(None, Some(parent)) => {
|
||||
parent.hash_varargs(hasher);
|
||||
}
|
||||
_ => (),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl CloneVarArgs for Arc<OwnedContextImpl> {
|
||||
fn arc_clone(&self) -> Option<Arc<dyn ExtractVarArgs + Send + Sync>> {
|
||||
Some(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
// ======================================
|
||||
// TYPES `Context` AND `OwnedContextImpl`
|
||||
// ======================================
|
||||
|
||||
pub type Context<'a> = Option<Arc<OwnedContextImpl>>;
|
||||
type DynRef<'a> = &'a (dyn Any + Send + Sync);
|
||||
type DynBox = Box<dyn AnyHash + Send + Sync>;
|
||||
|
||||
#[derive(dyn_any::DynAny)]
|
||||
pub struct OwnedContextImpl {
|
||||
parent: Option<Arc<dyn ExtractVarArgs + Sync + Send>>,
|
||||
footprint: Option<Footprint>,
|
||||
real_time: Option<f64>,
|
||||
animation_time: Option<f64>,
|
||||
pointer_position: Option<DVec2>,
|
||||
position: Option<Vec<DVec2>>,
|
||||
// This could be converted into a single enum to save extra bytes
|
||||
index: Option<Vec<usize>>,
|
||||
varargs: Option<Arc<[DynBox]>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for OwnedContextImpl {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("OwnedContextImpl")
|
||||
.field("parent", &self.parent.as_ref().map(|_| "<Parent>"))
|
||||
.field("footprint", &self.footprint)
|
||||
.field("real_time", &self.real_time)
|
||||
.field("animation_time", &self.animation_time)
|
||||
.field("pointer_position", &self.pointer_position)
|
||||
.field("index", &self.index)
|
||||
.field("varargs_len", &self.varargs.as_ref().map(|x| x.len()))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for OwnedContextImpl {
|
||||
#[track_caller]
|
||||
fn default() -> Self {
|
||||
Self::empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl graphene_hash::CacheHash for OwnedContextImpl {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.footprint.cache_hash(state);
|
||||
self.real_time.cache_hash(state);
|
||||
self.animation_time.cache_hash(state);
|
||||
self.pointer_position.cache_hash(state);
|
||||
self.position.cache_hash(state);
|
||||
self.index.cache_hash(state);
|
||||
self.hash_varargs(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl OwnedContextImpl {
|
||||
#[track_caller]
|
||||
pub fn from<T: ExtractAll + CloneVarArgs>(value: T) -> Self {
|
||||
OwnedContextImpl::from_flags(value, ContextFeatures::all())
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
pub fn from_flags<T: ExtractAll + CloneVarArgs>(value: T, bitflags: ContextFeatures) -> Self {
|
||||
let parent = bitflags
|
||||
.contains(ContextFeatures::VARARGS)
|
||||
.then(|| match value.varargs_len() {
|
||||
Ok(x) if x > 0 => value.arc_clone(),
|
||||
_ => None,
|
||||
})
|
||||
.flatten();
|
||||
let footprint = bitflags.contains(ContextFeatures::FOOTPRINT).then(|| value.try_footprint().copied()).flatten();
|
||||
let real_time = bitflags.contains(ContextFeatures::REAL_TIME).then(|| value.try_real_time()).flatten();
|
||||
let animation_time = bitflags.contains(ContextFeatures::ANIMATION_TIME).then(|| value.try_animation_time()).flatten();
|
||||
let pointer_position = bitflags.contains(ContextFeatures::POINTER_POSITION).then(|| value.try_pointer_position()).flatten();
|
||||
let position = bitflags.contains(ContextFeatures::POSITION).then(|| value.try_position()).flatten().map(|x| x.collect());
|
||||
let index = bitflags.contains(ContextFeatures::INDEX).then(|| value.try_index()).flatten().map(|x| x.collect());
|
||||
|
||||
OwnedContextImpl {
|
||||
parent,
|
||||
footprint,
|
||||
real_time,
|
||||
animation_time,
|
||||
pointer_position,
|
||||
position,
|
||||
index,
|
||||
varargs: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn empty() -> Self {
|
||||
OwnedContextImpl {
|
||||
parent: None,
|
||||
footprint: None,
|
||||
real_time: None,
|
||||
animation_time: None,
|
||||
pointer_position: None,
|
||||
position: None,
|
||||
index: None,
|
||||
varargs: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait DynHash {
|
||||
fn dyn_hash(&self, state: &mut dyn Hasher);
|
||||
@@ -559,6 +732,57 @@ impl std::fmt::Debug for OwnedSlot {
|
||||
}
|
||||
}
|
||||
|
||||
impl OwnedContextImpl {
|
||||
pub fn set_footprint(&mut self, footprint: Footprint) {
|
||||
self.footprint = Some(footprint);
|
||||
}
|
||||
|
||||
pub fn with_footprint(mut self, footprint: Footprint) -> Self {
|
||||
self.footprint = Some(footprint);
|
||||
self
|
||||
}
|
||||
pub fn with_real_time(mut self, real_time: f64) -> Self {
|
||||
self.real_time = Some(real_time);
|
||||
self
|
||||
}
|
||||
pub fn with_animation_time(mut self, animation_time: f64) -> Self {
|
||||
self.animation_time = Some(animation_time);
|
||||
self
|
||||
}
|
||||
pub fn with_pointer_position(mut self, pointer_position: DVec2) -> Self {
|
||||
self.pointer_position = Some(pointer_position);
|
||||
self
|
||||
}
|
||||
pub fn with_position(mut self, position: DVec2) -> Self {
|
||||
if let Some(current_position) = &mut self.position {
|
||||
current_position.insert(0, position);
|
||||
} else {
|
||||
self.position = Some(vec![position]);
|
||||
}
|
||||
self
|
||||
}
|
||||
pub fn with_index(mut self, index: usize) -> Self {
|
||||
if let Some(current_index) = &mut self.index {
|
||||
current_index.insert(0, index);
|
||||
} else {
|
||||
self.index = Some(vec![index]);
|
||||
}
|
||||
self
|
||||
}
|
||||
pub fn with_vararg(mut self, value: Box<dyn AnyHash + Send + Sync>) -> Self {
|
||||
assert!(self.varargs.is_none_or(|value| value.is_empty()));
|
||||
self.varargs = Some(Arc::new([value]));
|
||||
self
|
||||
}
|
||||
pub fn into_context(self) -> Option<Arc<Self>> {
|
||||
Some(Arc::new(self))
|
||||
}
|
||||
pub fn erase_parent(mut self) -> Self {
|
||||
self.parent = None;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub type SourceId = u64;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
|
||||
@@ -17,13 +17,6 @@ struct FrameSlot<T> {
|
||||
value: UnsafeCell<MaybeUninit<T>>,
|
||||
}
|
||||
|
||||
// SAFETY: the key CAS reserves a slot for one writer, and the Release store of its
|
||||
// state publishes the value to every Acquire load in `lookup`, so concurrent access
|
||||
// is ordered. Sharing the table hands out `&T` and drops `T` on whichever thread
|
||||
// drops the table, which is what the `Send + Sync` bounds cover.
|
||||
unsafe impl<T: Send + Sync, const CAP: usize> Sync for FrameTable<T, CAP> {}
|
||||
unsafe impl<T: Send, const CAP: usize> Send for FrameTable<T, CAP> {}
|
||||
|
||||
pub enum Lookup<'t, T> {
|
||||
Hit(Finality, &'t T),
|
||||
Vacant(VacantSlot<'t, T>),
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
use crate::Node;
|
||||
use std::marker::PhantomData;
|
||||
#[derive(Clone)]
|
||||
pub struct FnNode<T: Fn(I) -> O, I, O>(T, PhantomData<(I, O)>);
|
||||
|
||||
impl<'i, T: Fn(I) -> O + 'i, O: 'i, I: 'i> Node<'i, I> for FnNode<T, I, O> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> Self::Output {
|
||||
self.0(input)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Fn(I) -> O, I, O> FnNode<T, I, O> {
|
||||
pub fn new(f: T) -> Self {
|
||||
FnNode(f, PhantomData)
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
extern crate log;
|
||||
|
||||
pub mod arena;
|
||||
pub mod attribute;
|
||||
pub mod bounds;
|
||||
pub mod consts;
|
||||
pub mod context;
|
||||
pub mod frame_table;
|
||||
pub mod generic;
|
||||
pub mod gpoll;
|
||||
pub mod list;
|
||||
pub mod math;
|
||||
@@ -13,7 +13,6 @@ pub mod memo;
|
||||
pub mod misc;
|
||||
pub mod node;
|
||||
pub mod ops;
|
||||
pub mod record;
|
||||
pub mod registry;
|
||||
pub mod render_complexity;
|
||||
pub mod runtime;
|
||||
@@ -40,15 +39,113 @@ pub use no_std_types::blending;
|
||||
pub use no_std_types::choice_type;
|
||||
pub use no_std_types::color;
|
||||
pub use no_std_types::shaders;
|
||||
pub use node::Node;
|
||||
pub use num_traits;
|
||||
use std::any::TypeId;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
#[cfg(feature = "wasm")]
|
||||
pub use tsify;
|
||||
pub use types::Cow;
|
||||
|
||||
// pub trait Node: for<'n> NodeIO<'n> {
|
||||
/// The node trait allows for defining any node. Nodes can only take one call argument input, however they can store references to other nodes inside the struct.
|
||||
/// See `node-graph/README.md` for information on how to define a new node.
|
||||
pub trait Node<'i, Input> {
|
||||
type Output: 'i;
|
||||
/// Evaluates the node with the single specified input.
|
||||
fn eval(&'i self, input: Input) -> Self::Output;
|
||||
/// Resets the node, e.g. the LetNode's cache is set to None.
|
||||
fn reset(&self) {}
|
||||
/// Returns the name of the node for diagnostic purposes.
|
||||
fn node_name(&self) -> &'static str {
|
||||
std::any::type_name::<Self>()
|
||||
}
|
||||
/// Serialize the node which is used for the `introspect` function which can retrieve values from monitor nodes.
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
log::warn!("Node::serialize not implemented for {}", std::any::type_name::<Self>());
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
mod types;
|
||||
pub use types::*;
|
||||
|
||||
pub trait NodeIO<'i, Input>: Node<'i, Input>
|
||||
where
|
||||
Self::Output: 'i + StaticTypeSized,
|
||||
Input: StaticTypeSized,
|
||||
{
|
||||
fn input_type(&self) -> TypeId {
|
||||
TypeId::of::<Input::Static>()
|
||||
}
|
||||
fn input_type_name(&self) -> &'static str {
|
||||
std::any::type_name::<Input>()
|
||||
}
|
||||
fn output_type(&self) -> TypeId {
|
||||
TypeId::of::<<Self::Output as StaticTypeSized>::Static>()
|
||||
}
|
||||
fn output_type_name(&self) -> &'static str {
|
||||
std::any::type_name::<Self::Output>()
|
||||
}
|
||||
fn to_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes {
|
||||
NodeIOTypes {
|
||||
call_argument: concrete!(<Input as StaticTypeSized>::Static),
|
||||
return_value: concrete!(<Self::Output as StaticTypeSized>::Static),
|
||||
inputs,
|
||||
}
|
||||
}
|
||||
fn to_async_node_io(&self, inputs: Vec<Type>) -> NodeIOTypes
|
||||
where
|
||||
<Self::Output as Future>::Output: StaticTypeSized,
|
||||
Self::Output: Future,
|
||||
{
|
||||
NodeIOTypes {
|
||||
call_argument: concrete!(<Input as StaticTypeSized>::Static),
|
||||
return_value: future!(<<Self::Output as Future>::Output as StaticTypeSized>::Static),
|
||||
inputs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'i, N: Node<'i, I>, I> NodeIO<'i, I> for N
|
||||
where
|
||||
N::Output: 'i + StaticTypeSized,
|
||||
I: StaticTypeSized,
|
||||
{
|
||||
}
|
||||
|
||||
impl<'i, I: 'i, N: Node<'i, I> + ?Sized> Node<'i, I> for &'i N {
|
||||
type Output = N::Output;
|
||||
fn eval(&'i self, input: I) -> N::Output {
|
||||
(*self).eval(input)
|
||||
}
|
||||
}
|
||||
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for Box<N> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> O {
|
||||
(**self).eval(input)
|
||||
}
|
||||
}
|
||||
impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for std::sync::Arc<N> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> O {
|
||||
(**self).eval(input)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'i, I, O: 'i> Node<'i, I> for Pin<Box<dyn Node<'i, I, Output = O> + 'i>> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> O {
|
||||
(**self).eval(input)
|
||||
}
|
||||
}
|
||||
impl<'i, I, O: 'i> Node<'i, I> for Pin<&'i (dyn NodeIO<'i, I, Output = O> + 'i)> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> O {
|
||||
(**self).eval(input)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait InputAccessorSource<'a, T>: InputAccessorSourceIdentifier + std::fmt::Debug {
|
||||
fn get_input(&'a self, index: usize) -> Option<&'a T>;
|
||||
fn set_input(&'a mut self, index: usize, value: T);
|
||||
|
||||
@@ -71,14 +71,6 @@ pub trait Node<Input> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The record layout of this node's output; `None` for element-only
|
||||
/// producers. Consumers read their carrier's layout through this at
|
||||
/// wiring, and the wiring layer derives stack sizing from the same
|
||||
/// layouts, in the dynamic executor and exported source alike.
|
||||
fn layout(&self) -> Option<&crate::record::Layout> {
|
||||
None
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -141,10 +133,6 @@ where
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
fn layout(&self) -> Option<&crate::record::Layout> {
|
||||
(**self).layout()
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -171,10 +159,6 @@ where
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
fn layout(&self) -> Option<&crate::record::Layout> {
|
||||
(**self).layout()
|
||||
}
|
||||
|
||||
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,
|
||||
|
||||
@@ -1,26 +1,56 @@
|
||||
use crate::Node;
|
||||
use crate::list::{Attribute, AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
|
||||
use crate::transform::Footprint;
|
||||
use glam::DVec2;
|
||||
use graphene_hash::CacheHash;
|
||||
use std::future::Future;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
// Type
|
||||
// TODO: Document this
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
|
||||
pub struct TypeNode<N: for<'a> Node<'a, I>, I, O>(pub N, pub PhantomData<(I, O)>);
|
||||
impl<'i, N, I: 'i, O: 'i> Node<'i, I> for TypeNode<N, I, O>
|
||||
where
|
||||
N: for<'n> Node<'n, I, Output = O>,
|
||||
{
|
||||
type Output = O;
|
||||
fn eval(&'i self, input: I) -> Self::Output {
|
||||
self.0.eval(input)
|
||||
}
|
||||
|
||||
fn reset(&self) {
|
||||
self.0.reset();
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
self.0.serialize()
|
||||
}
|
||||
}
|
||||
impl<'i, N: for<'a> Node<'a, I>, I: 'i> TypeNode<N, I, <N as Node<'i, I>>::Output> {
|
||||
pub fn new(node: N) -> Self {
|
||||
Self(node, PhantomData)
|
||||
}
|
||||
}
|
||||
impl<'i, N: for<'a> Node<'a, I> + Clone, I: 'i> Clone for TypeNode<N, I, <N as Node<'i, I>>::Output> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone(), self.1)
|
||||
}
|
||||
}
|
||||
impl<'i, N: for<'a> Node<'a, I> + Copy, I: 'i> Copy for TypeNode<N, I, <N as Node<'i, I>>::Output> {}
|
||||
|
||||
/// The [`Convert`] trait allows for conversion between Rust primitive numeric types.
|
||||
/// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types.
|
||||
pub trait Convert<T, C>: Sized {
|
||||
/// Converts this type into the (usually inferred) output type.
|
||||
#[must_use]
|
||||
fn convert(self, footprint: Footprint, converter: C) -> T;
|
||||
}
|
||||
|
||||
/// The asynchronous counterpart of [`Convert`]; a conversion pair implements exactly one of the two traits.
|
||||
pub trait ConvertAsync<T, C>: Sized {
|
||||
#[must_use]
|
||||
fn convert(self, footprint: Footprint, converter: C) -> crate::runtime::SourceFuture<T>;
|
||||
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send;
|
||||
}
|
||||
|
||||
impl<T: ToString + Send> Convert<String, ()> for T {
|
||||
/// Converts this type into a `String` using its `ToString` implementation.
|
||||
#[inline]
|
||||
fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||
async fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
}
|
||||
@@ -30,7 +60,7 @@ pub trait ListConvert<U> {
|
||||
}
|
||||
|
||||
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
|
||||
fn convert(self, _: Footprint, _: ()) -> List<U> {
|
||||
async fn convert(self, _: Footprint, _: ()) -> List<U> {
|
||||
let list: List<U> = self
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
@@ -46,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
|
||||
/// 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> {
|
||||
fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
|
||||
async fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
|
||||
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
|
||||
AttributeDyn(Box::new(Attribute(values)))
|
||||
}
|
||||
@@ -56,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
|
||||
/// 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 {
|
||||
fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
|
||||
async fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
|
||||
AttributeValueDyn(Box::new(self))
|
||||
}
|
||||
}
|
||||
@@ -65,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
|
||||
/// instead of monomorphizing over every possible carrier list type.
|
||||
impl<T: Send> Convert<ListDyn, ()> for List<T> {
|
||||
fn convert(self, _: Footprint, _: ()) -> ListDyn {
|
||||
async fn convert(self, _: Footprint, _: ()) -> ListDyn {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Convert<DVec2, ()> for DVec2 {
|
||||
fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -85,7 +115,7 @@ pub trait FromAnchorPosition {
|
||||
|
||||
// Converts a position into a vector path composed of a single anchor point
|
||||
impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
|
||||
fn convert(self, _: Footprint, _: ()) -> List<T> {
|
||||
async fn convert(self, _: Footprint, _: ()) -> List<T> {
|
||||
List::new_from_item(Item::new_from_element(T::from_anchor_position(self)))
|
||||
}
|
||||
}
|
||||
@@ -94,7 +124,7 @@ impl<T: FromAnchorPosition + Send> Convert<List<T>, ()> for DVec2 {
|
||||
macro_rules! impl_convert {
|
||||
($from:ty, $to:ty) => {
|
||||
impl Convert<$to, ()> for $from {
|
||||
fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
async fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
self as $to
|
||||
}
|
||||
}
|
||||
@@ -116,7 +146,7 @@ macro_rules! impl_convert {
|
||||
impl_convert!(usize, $to);
|
||||
|
||||
impl Convert<DVec2, ()> for $to {
|
||||
fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
DVec2::splat(self as f64)
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +1,10 @@
|
||||
use crate::concrete;
|
||||
use crate::context::{Context, ContextImpl};
|
||||
use crate::node::Node;
|
||||
use crate::{ContextFeature, ProtoNodeIdentifier, Type, WasmNotSend, WasmNotSync};
|
||||
use dyn_any::DynAny;
|
||||
use graphene_hash::CacheHash;
|
||||
use crate::{ContextFeature, Node, NodeIO, NodeIOTypes, ProtoNodeIdentifier, Type, WasmNotSend};
|
||||
use dyn_any::{DynAny, StaticType};
|
||||
pub use no_std_types::registry::types;
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hasher;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::Deref;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
// Translation struct between macro and definition
|
||||
@@ -20,8 +18,6 @@ pub struct NodeMetadata {
|
||||
pub context_features: Vec<ContextFeature>,
|
||||
pub memoize: bool,
|
||||
pub inject_scope: bool,
|
||||
/// The macro appended its hidden `_runtime` and `_source` fields as the last two entries of `fields`.
|
||||
pub async_source_fields: bool,
|
||||
}
|
||||
|
||||
// Translation struct between macro and definition
|
||||
@@ -59,485 +55,239 @@ pub enum RegistryValueSource {
|
||||
None,
|
||||
Default(&'static str),
|
||||
Scope(&'static str),
|
||||
SourceId,
|
||||
}
|
||||
|
||||
type NodeRegistry = LazyLock<Mutex<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>>>;
|
||||
type NodeRegistry = LazyLock<Mutex<HashMap<ProtoNodeIdentifier, Vec<(NodeConstructor, NodeIOTypes)>>>>;
|
||||
|
||||
pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub use crate::NodeIOTypes;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type ErasedNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = T> + Send + Sync;
|
||||
pub type DynFuture<'n, T> = Pin<Box<dyn Future<Output = T> + 'n + Send>>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type ErasedNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = T>;
|
||||
|
||||
/// Element-independent by erasure; the wire's `Type::Record(El)` keeps element reads proven at wiring.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>, Output = crate::record::RecordValue<'c>> + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>, Output = crate::record::RecordValue<'c>>;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type DynEdge = dyn std::any::Any + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
type DynEdge = dyn std::any::Any;
|
||||
|
||||
pub fn edge_type<T: 'static>() -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(T)))
|
||||
}
|
||||
|
||||
pub fn record_type<T: 'static>() -> Type {
|
||||
Type::Record(Box::new(concrete!(T)))
|
||||
}
|
||||
|
||||
pub fn record_edge_type<T: 'static>() -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(record_type::<T>()))
|
||||
}
|
||||
|
||||
/// The record edge type of a token row, generic over the element.
|
||||
pub fn generic_record_edge_type(name: &'static str) -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Record(Box::new(Type::Generic(std::borrow::Cow::Borrowed(name))))))
|
||||
}
|
||||
|
||||
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
|
||||
let mut hasher = graphene_hash::FxHasher64::new();
|
||||
ctx.cache_hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum ConstructionError {
|
||||
Arity { expected: usize, got: usize },
|
||||
Type { expected: Box<Type>, found: Box<Type> },
|
||||
MissingLayout,
|
||||
}
|
||||
|
||||
pub struct SharedEdge<N: ?Sized> {
|
||||
ptr: std::ptr::NonNull<N>,
|
||||
own: std::sync::Arc<N>,
|
||||
}
|
||||
|
||||
impl<N: ?Sized> SharedEdge<N> {
|
||||
pub fn new(own: std::sync::Arc<N>) -> Self {
|
||||
Self {
|
||||
ptr: std::ptr::NonNull::from(&*own),
|
||||
own,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn share(&self) -> Self {
|
||||
Self { ptr: self.ptr, own: self.own.clone() }
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `ptr` is derived from the owned Arc and never mutated through, so the edge is exactly as
|
||||
// thread safe as the payload it shares.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Send for SharedEdge<N> {}
|
||||
// SAFETY: as in Send.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Sync for SharedEdge<N> {}
|
||||
|
||||
impl<Input, N> Node<Input> for SharedEdge<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> crate::gpoll::GPoll<Self::Output> {
|
||||
// Every node advances the record stack by exactly its own frame: it keeps
|
||||
// its output and reclaims its inputs. A mismatch is a leaked or
|
||||
// over-released frame.
|
||||
#[cfg(debug_assertions)]
|
||||
let sp_before = crate::record::stack::sp();
|
||||
// SAFETY: `own` keeps the payload alive for `self`'s lifetime and Arc
|
||||
// payloads are address stable.
|
||||
let result = unsafe { self.ptr.as_ref() }.eval(input);
|
||||
#[cfg(debug_assertions)]
|
||||
debug_assert_eq!(
|
||||
crate::record::stack::sp(),
|
||||
sp_before + self.layout().map_or(0, |layout| layout.frame_bytes()),
|
||||
"{} left the record stack misaligned",
|
||||
std::any::type_name::<N>(),
|
||||
);
|
||||
result
|
||||
}
|
||||
|
||||
fn extent(&self, input: &Input) -> crate::gpoll::GPoll<crate::gpoll::Extent> {
|
||||
// SAFETY: as in eval.
|
||||
unsafe { self.ptr.as_ref() }.extent(input)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
// SAFETY: as in eval.
|
||||
unsafe { self.ptr.as_ref() }.serialize()
|
||||
}
|
||||
|
||||
fn layout(&self) -> Option<&crate::record::Layout> {
|
||||
// SAFETY: as in eval.
|
||||
unsafe { self.ptr.as_ref() }.layout()
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&self, input: &'a Input, range: std::ops::Range<u64>, scratch: Option<&'a mut [std::mem::MaybeUninit<Self::Output>]>) -> crate::node::BatchStatus<'a, Self::Output>
|
||||
where
|
||||
Input: crate::context::InjectIndex + Copy,
|
||||
{
|
||||
// SAFETY: as in eval.
|
||||
unsafe { self.ptr.as_ref() }.eval_batch(input, range, scratch)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EdgeHandle {
|
||||
node: Box<DynEdge>,
|
||||
share: fn(&DynEdge) -> Box<DynEdge>,
|
||||
serialize: fn(&DynEdge) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
|
||||
layout: fn(&DynEdge) -> Option<&crate::record::Layout>,
|
||||
ty: Type,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EdgeHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EdgeHandle").field("ty", &self.ty).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: wasm is single threaded, so the marker-free payload never actually crosses a thread.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Send for EdgeHandle {}
|
||||
// SAFETY: as in Send.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for EdgeHandle {}
|
||||
|
||||
impl EdgeHandle {
|
||||
pub fn new<T: 'static>(node: std::sync::Arc<ErasedNode<T>>) -> Self {
|
||||
Self::new_erased(node, edge_type::<T>())
|
||||
}
|
||||
|
||||
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
|
||||
Self::new_erased(node, record_edge_type::<T>())
|
||||
}
|
||||
|
||||
pub fn new_erased<N>(node: std::sync::Arc<N>, ty: Type) -> Self
|
||||
where
|
||||
N: ?Sized + 'static + for<'c> Node<ContextImpl<'c>>,
|
||||
SharedEdge<N>: WasmNotSend + WasmNotSync,
|
||||
{
|
||||
Self {
|
||||
node: Box::new(SharedEdge::new(node)),
|
||||
share: |edge| Box::new(edge.downcast_ref::<SharedEdge<N>>().expect("share hook matches the stored edge type").share()),
|
||||
serialize: |edge| Node::<ContextImpl>::serialize(edge.downcast_ref::<SharedEdge<N>>().expect("serialize hook matches the stored edge type")),
|
||||
layout: |edge| Node::<ContextImpl>::layout(edge.downcast_ref::<SharedEdge<N>>().expect("layout hook matches the stored edge type")),
|
||||
ty,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ty(&self) -> &Type {
|
||||
&self.ty
|
||||
}
|
||||
|
||||
pub fn duplicate(&self) -> Self {
|
||||
Self {
|
||||
node: (self.share)(&*self.node),
|
||||
share: self.share,
|
||||
serialize: self.serialize,
|
||||
layout: self.layout,
|
||||
ty: self.ty.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(self.serialize)(&*self.node)
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> Option<&crate::record::Layout> {
|
||||
(self.layout)(&*self.node)
|
||||
}
|
||||
|
||||
pub fn downcast<T: 'static>(self) -> Result<SharedEdge<ErasedNode<T>>, ConstructionError> {
|
||||
self.downcast_erased(edge_type::<T>())
|
||||
}
|
||||
|
||||
pub fn downcast_record<T: 'static>(self) -> Result<SharedEdge<ErasedRecordNode>, ConstructionError> {
|
||||
self.downcast_erased(record_edge_type::<T>())
|
||||
}
|
||||
|
||||
pub fn downcast_erased<N: ?Sized + 'static>(self, expected: Type) -> Result<SharedEdge<N>, ConstructionError> {
|
||||
let found = self.ty;
|
||||
self.node.downcast::<SharedEdge<N>>().map(|edge| *edge).map_err(|_| ConstructionError::Type {
|
||||
expected: Box::new(expected),
|
||||
found: Box::new(found),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub type NodeConstructor = fn(Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RegistryEntry {
|
||||
pub io: NodeIOTypes,
|
||||
pub constructor: NodeConstructor,
|
||||
}
|
||||
|
||||
pub fn construct(entry: &RegistryEntry, inputs: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
||||
if inputs.len() != entry.io.inputs.len() {
|
||||
return Err(ConstructionError::Arity {
|
||||
expected: entry.io.inputs.len(),
|
||||
got: inputs.len(),
|
||||
});
|
||||
}
|
||||
for (handle, expected) in inputs.iter().zip(&entry.io.inputs) {
|
||||
if handle.ty() != expected {
|
||||
return Err(ConstructionError::Type {
|
||||
expected: Box::new(expected.clone()),
|
||||
found: Box::new(handle.ty().clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
(entry.constructor)(inputs)
|
||||
}
|
||||
|
||||
pub type DynFuture<'n, T> = Pin<Box<dyn std::future::Future<Output = T> + 'n>>;
|
||||
pub type LocalFuture<'n, T> = Pin<Box<dyn Future<Output = T> + 'n>>;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type Any<'n> = Box<dyn DynAny<'n> + 'n + Send>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type Any<'n> = Box<dyn DynAny<'n> + 'n>;
|
||||
pub type FutureAny<'n> = DynFuture<'n, Any<'n>>;
|
||||
// TODO: is this safe? This is assumed to be send+sync.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n;
|
||||
pub type TypeErasedPinnedRef<'n> = Pin<&'n TypeErasedNode<'n>>;
|
||||
pub type TypeErasedRef<'n> = &'n TypeErasedNode<'n>;
|
||||
pub type TypeErasedBox<'n> = Box<TypeErasedNode<'n>>;
|
||||
pub type TypeErasedPinned<'n> = Pin<Box<TypeErasedNode<'n>>>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::SourceId;
|
||||
use crate::arena::Arena;
|
||||
use crate::context::{Ctx, EvalScope, ExtractArena};
|
||||
use crate::gpoll::GPoll;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
pub type SharedNodeContainer = std::sync::Arc<NodeContainer>;
|
||||
|
||||
struct CountingNode(AtomicU32);
|
||||
pub type NodeConstructor = fn(Vec<SharedNodeContainer>) -> DynFuture<'static, TypeErasedBox<'static>>;
|
||||
|
||||
impl<Input> Node<Input> for CountingNode {
|
||||
type Output = u32;
|
||||
#[derive(Clone)]
|
||||
pub struct NodeContainer {
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
pub node: *const TypeErasedNode<'static>,
|
||||
#[cfg(not(feature = "dealloc_nodes"))]
|
||||
pub node: TypeErasedRef<'static>,
|
||||
}
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<u32> {
|
||||
GPoll::Final(self.0.fetch_add(1, Ordering::Relaxed) + 1)
|
||||
}
|
||||
impl Deref for NodeContainer {
|
||||
type Target = TypeErasedNode<'static>;
|
||||
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
fn deref(&self) -> &Self::Target {
|
||||
unsafe { &*(self.node) }
|
||||
#[cfg(not(feature = "dealloc_nodes"))]
|
||||
self.node
|
||||
}
|
||||
|
||||
struct ValueNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> Node<Input> for ValueNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
struct LendNode(String);
|
||||
|
||||
impl<'e, Input: Ctx + ExtractArena<ArenaRef = &'e Arena>> Node<Input> for LendNode {
|
||||
type Output = &'e String;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<&'e String> {
|
||||
match input.arena().alloc(self.0.clone()) {
|
||||
Some((parked, _)) => GPoll::Final(parked),
|
||||
None => GPoll::arena_exhausted(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(Some(0.5), None, None, generations, arena)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrow_carrying_value_types_wire_through_the_general_constructor() {
|
||||
struct SplitBorrow<'c>(&'c str, usize);
|
||||
|
||||
struct SplitNode<Node0> {
|
||||
content: Node0,
|
||||
}
|
||||
|
||||
impl<'e, Input, Node0> Node<Input> for SplitNode<Node0>
|
||||
where
|
||||
Input: Ctx,
|
||||
Node0: Node<Input, Output = &'e String>,
|
||||
{
|
||||
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> Node<ContextImpl<'c>, Output = SplitBorrow<'c>> + Send + Sync;
|
||||
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let node: Arc<ErasedSplitEdge> = Arc::new(SplitNode {
|
||||
content: LendNode("held".to_string()),
|
||||
});
|
||||
let handle = EdgeHandle::new_erased(node, concrete!(SplitBorrow<'static>));
|
||||
assert_eq!(*handle.ty(), 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::{DeriveCtx, Derived, ExtractIndex};
|
||||
|
||||
struct RepeatNode<Node0> {
|
||||
content: Node0,
|
||||
}
|
||||
|
||||
impl<C, T, Node0> Node<C> for RepeatNode<Node0>
|
||||
where
|
||||
C: Ctx + DeriveCtx,
|
||||
Node0: for<'x> Node<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> Node<Input> for LevelsNode {
|
||||
type Output = Vec<usize>;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Vec<usize>> {
|
||||
GPoll::Final(input.try_index().map(|levels| levels.collect()).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let nested = RepeatNode {
|
||||
content: RepeatNode { content: LevelsNode },
|
||||
};
|
||||
let erased: Box<ErasedNode<Vec<Vec<Vec<usize>>>>> = Box::new(nested);
|
||||
|
||||
let GPoll::Final(outer) = erased.eval(&ctx) else {
|
||||
panic!("nested repeat must evaluate");
|
||||
};
|
||||
assert_eq!(outer.len(), 3);
|
||||
assert_eq!(outer[2][1], vec![1, 2, 0]);
|
||||
assert_eq!(outer[0][0], vec![0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_ctx_footprint_replace_reaches_the_content() {
|
||||
use crate::context::{DeriveCtx, Derived, ExtractFootprint};
|
||||
use crate::transform::Footprint;
|
||||
|
||||
struct ShiftFootprintNode<Node0> {
|
||||
content: Node0,
|
||||
}
|
||||
|
||||
impl<C, T, Node0> Node<C> for ShiftFootprintNode<Node0>
|
||||
where
|
||||
C: Ctx + DeriveCtx + ExtractFootprint,
|
||||
Node0: for<'x> Node<Derived<'x, C>, Output = T>,
|
||||
{
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, input: &C) -> GPoll<T> {
|
||||
let mut footprint = input.try_footprint().copied().unwrap_or(Footprint::DEFAULT);
|
||||
footprint.resolution.x += 7;
|
||||
let derived = input.with_footprint(&footprint);
|
||||
self.content.eval(&derived)
|
||||
}
|
||||
}
|
||||
|
||||
struct ResolutionNode;
|
||||
|
||||
impl<Input: ExtractFootprint> Node<Input> for ResolutionNode {
|
||||
type Output = u32;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<u32> {
|
||||
GPoll::Final(input.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0))
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph: Box<ErasedNode<u32>> = Box::new(ShiftFootprintNode {
|
||||
content: ShiftFootprintNode { content: ResolutionNode },
|
||||
});
|
||||
assert_eq!(graph.eval(&ctx), GPoll::Final(Footprint::DEFAULT.resolution.x + 14));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn construct_checks_arity_and_types() {
|
||||
fn construct_strlen(args: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
||||
let mut args = args.into_iter();
|
||||
let value = args.next().ok_or(ConstructionError::Arity { expected: 1, got: 0 })?.downcast::<String>()?;
|
||||
drop(value);
|
||||
Ok(EdgeHandle::new(Arc::new(ValueNode(0u32)) as Arc<ErasedNode<u32>>))
|
||||
}
|
||||
let entry = RegistryEntry {
|
||||
io: NodeIOTypes::new(concrete!(Context), concrete!(u32), vec![edge_type::<String>()]),
|
||||
constructor: construct_strlen,
|
||||
};
|
||||
|
||||
let owned = EdgeHandle::new(Arc::new(ValueNode("typed".to_string())) as Arc<ErasedNode<String>>);
|
||||
assert!(construct(&entry, vec![owned]).is_ok());
|
||||
|
||||
assert_eq!(construct(&entry, vec![]).unwrap_err(), ConstructionError::Arity { expected: 1, got: 0 });
|
||||
|
||||
let mistyped = EdgeHandle::new(Arc::new(ValueNode(1.0f64)) as Arc<ErasedNode<f64>>);
|
||||
assert_eq!(
|
||||
construct(&entry, vec![mistyped]).unwrap_err(),
|
||||
ConstructionError::Type {
|
||||
expected: Box::new(edge_type::<String>()),
|
||||
found: Box::new(edge_type::<f64>()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicated_edges_share_one_instance_and_outlive_each_other() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let handle = EdgeHandle::new(Arc::new(CountingNode(AtomicU32::new(0))) as Arc<ErasedNode<u32>>);
|
||||
let duplicate = handle.duplicate();
|
||||
assert_eq!(*duplicate.ty(), edge_type::<u32>());
|
||||
|
||||
let first = handle.downcast::<u32>().unwrap();
|
||||
let second = duplicate.downcast::<u32>().unwrap();
|
||||
assert_eq!(first.eval(&ctx), GPoll::Final(1));
|
||||
assert_eq!(second.eval(&ctx), GPoll::Final(2));
|
||||
|
||||
drop(first);
|
||||
assert_eq!(second.eval(&ctx), GPoll::Final(3));
|
||||
#[cfg(not(feature = "dealloc_nodes"))]
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.node
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Marks NodeContainer as Sync. This dissallows the use of threadlocal storage for nodes as this would invalidate references to them.
|
||||
// TODO: implement this on a higher level wrapper to avoid missuse
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
unsafe impl Send for NodeContainer {}
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
unsafe impl Sync for NodeContainer {}
|
||||
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
impl Drop for NodeContainer {
|
||||
fn drop(&mut self) {
|
||||
unsafe { self.dealloc_unchecked() }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NodeContainer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("NodeContainer").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeContainer {
|
||||
pub fn new(node: TypeErasedBox<'static>) -> SharedNodeContainer {
|
||||
let node = Box::leak(node);
|
||||
Self { node }.into()
|
||||
}
|
||||
|
||||
#[cfg(feature = "dealloc_nodes")]
|
||||
unsafe fn dealloc_unchecked(&mut self) {
|
||||
unsafe {
|
||||
drop(Box::from_raw(self.node as *mut TypeErasedNode));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Boxes the input and downcasts the output.
|
||||
/// Wraps around a node taking Box<dyn DynAny> and returning Box<dyn DynAny>
|
||||
#[derive(Clone)]
|
||||
pub struct DowncastBothNode<I, O> {
|
||||
node: SharedNodeContainer,
|
||||
_i: PhantomData<I>,
|
||||
_o: PhantomData<O>,
|
||||
}
|
||||
impl<'input, O, I> Node<'input, I> for DowncastBothNode<I, O>
|
||||
where
|
||||
O: 'input + StaticType + WasmNotSend,
|
||||
I: 'input + StaticType + WasmNotSend,
|
||||
{
|
||||
type Output = DynFuture<'input, O>;
|
||||
#[inline]
|
||||
#[track_caller]
|
||||
fn eval(&'input self, input: I) -> Self::Output {
|
||||
{
|
||||
let node_name = self.node.node_name();
|
||||
let input = Box::new(input);
|
||||
let future = self.node.eval(input);
|
||||
Box::pin(async move {
|
||||
let out = dyn_any::downcast(future.await).unwrap_or_else(|e| panic!("DowncastBothNode wrong output type: {e} in: \n{node_name}"));
|
||||
*out
|
||||
})
|
||||
}
|
||||
}
|
||||
fn reset(&self) {
|
||||
self.node.reset();
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
self.node.serialize()
|
||||
}
|
||||
}
|
||||
impl<I, O> DowncastBothNode<I, O> {
|
||||
pub const fn new(node: SharedNodeContainer) -> Self {
|
||||
Self {
|
||||
node,
|
||||
_i: PhantomData,
|
||||
_o: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct FutureWrapperNode<Node> {
|
||||
node: Node,
|
||||
}
|
||||
|
||||
impl<'i, T: 'i + WasmNotSend, N> Node<'i, T> for FutureWrapperNode<N>
|
||||
where
|
||||
N: Node<'i, T, Output: WasmNotSend> + WasmNotSend,
|
||||
{
|
||||
type Output = DynFuture<'i, N::Output>;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, input: T) -> Self::Output {
|
||||
let result = self.node.eval(input);
|
||||
Box::pin(async move { result })
|
||||
}
|
||||
#[inline(always)]
|
||||
fn reset(&self) {
|
||||
self.node.reset();
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
self.node.serialize()
|
||||
}
|
||||
}
|
||||
|
||||
impl<N> FutureWrapperNode<N> {
|
||||
pub const fn new(node: N) -> Self {
|
||||
Self { node }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DynAnyNode<I, O, Node> {
|
||||
node: Node,
|
||||
_i: PhantomData<I>,
|
||||
_o: PhantomData<O>,
|
||||
}
|
||||
|
||||
impl<'input, I, O, N> Node<'input, Any<'input>> for DynAnyNode<I, O, N>
|
||||
where
|
||||
I: 'input + StaticType + WasmNotSend,
|
||||
O: 'input + StaticType + WasmNotSend,
|
||||
N: 'input + Node<'input, I, Output = DynFuture<'input, O>>,
|
||||
{
|
||||
type Output = FutureAny<'input>;
|
||||
#[inline]
|
||||
fn eval(&'input self, input: Any<'input>) -> Self::Output {
|
||||
let node_name = std::any::type_name::<N>();
|
||||
let output = |input| {
|
||||
let result = self.node.eval(input);
|
||||
async move { Box::new(result.await) as Any<'input> }
|
||||
};
|
||||
match dyn_any::downcast(input) {
|
||||
Ok(input) => Box::pin(output(*input)),
|
||||
Err(e) => panic!("DynAnyNode Input, {e} in:\n{node_name}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn reset(&self) {
|
||||
self.node.reset();
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
self.node.serialize()
|
||||
}
|
||||
}
|
||||
impl<'input, I, O, N> DynAnyNode<I, O, N>
|
||||
where
|
||||
I: 'input + StaticType,
|
||||
O: 'input + StaticType,
|
||||
N: 'input + Node<'input, I, Output = DynFuture<'input, O>>,
|
||||
{
|
||||
pub const fn new(node: N) -> Self {
|
||||
Self {
|
||||
node,
|
||||
_i: PhantomData,
|
||||
_o: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct PanicNode<I: WasmNotSend, O: WasmNotSend>(PhantomData<I>, PhantomData<O>);
|
||||
|
||||
impl<'i, I: 'i + WasmNotSend, O: 'i + WasmNotSend> Node<'i, I> for PanicNode<I, O> {
|
||||
type Output = O;
|
||||
fn eval(&'i self, _: I) -> Self::Output {
|
||||
unimplemented!("This node should never be evaluated")
|
||||
}
|
||||
}
|
||||
|
||||
impl<I: WasmNotSend, O: WasmNotSend> PanicNode<I, O> {
|
||||
pub const fn new() -> Self {
|
||||
Self(PhantomData, PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<I: WasmNotSend, O: WasmNotSend> Default for PanicNode<I, O> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Evaluate safety
|
||||
unsafe impl<I: WasmNotSend, O: WasmNotSend> Sync for PanicNode<I, O> {}
|
||||
@@ -16,8 +16,7 @@ pub type DynRuntime = dyn Runtime + Send + Sync;
|
||||
pub type DynRuntime = dyn Runtime;
|
||||
|
||||
pub trait Runtime {
|
||||
/// Returns true when the future completed during the call, so its result is already observable.
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool;
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture);
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -41,14 +40,7 @@ impl graphene_hash::CacheHash for RuntimeHandle {
|
||||
}
|
||||
|
||||
pub trait Spawner {
|
||||
/// Returns true when the task completed during the call, so its result is already observable.
|
||||
fn spawn(&self, task: SourceFuture) -> bool;
|
||||
}
|
||||
|
||||
/// Polls `task` once with a no-op waker, returning true if it completed.
|
||||
pub fn poll_once(task: &mut SourceFuture) -> bool {
|
||||
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
|
||||
task.as_mut().poll(&mut context).is_ready()
|
||||
fn spawn(&self, task: SourceFuture);
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
@@ -62,21 +54,17 @@ pub type DynNotifier = dyn Fn() + Send + Sync;
|
||||
pub type DynNotifier = dyn Fn();
|
||||
|
||||
impl<S: Spawner + ?Sized> Spawner for Box<S> {
|
||||
fn spawn(&self, task: SourceFuture) -> bool {
|
||||
fn spawn(&self, task: SourceFuture) {
|
||||
(**self).spawn(task)
|
||||
}
|
||||
}
|
||||
|
||||
/// Polls each task once inline. Tasks that are not immediately ready never complete.
|
||||
/// Dropped tasks never complete.
|
||||
pub struct NoopSpawner;
|
||||
|
||||
impl Spawner for NoopSpawner {
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
log::warn!("async source is not immediately ready and no host spawner is wired; the task is dropped");
|
||||
false
|
||||
fn spawn(&self, _task: SourceFuture) {
|
||||
log::warn!("async source spawned before a host spawner is wired; the task is dropped");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,524 +129,20 @@ impl<S> GraphRuntime<S> {
|
||||
}
|
||||
|
||||
impl<S: Spawner> Runtime for GraphRuntime<S> {
|
||||
fn spawn(&self, source: SourceId, mut future: SourceFuture) -> bool {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) {
|
||||
let generations = Arc::clone(&self.generations);
|
||||
let dirty = Arc::clone(&self.dirty);
|
||||
let notifier = Arc::clone(&self.notifier);
|
||||
let mut first = true;
|
||||
self.spawner.spawn(Box::pin(std::future::poll_fn(move |task_context| {
|
||||
let poll = future.as_mut().poll(task_context);
|
||||
if poll.is_ready() && !first {
|
||||
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(generation) = generations.get_mut(&source) {
|
||||
*generation += 1;
|
||||
dirty.store(true, Ordering::Release);
|
||||
drop(generations);
|
||||
let notifier = Arc::clone(¬ifier.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
notifier();
|
||||
}
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
future.await;
|
||||
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(generation) = generations.get_mut(&source) {
|
||||
*generation += 1;
|
||||
dirty.store(true, Ordering::Release);
|
||||
drop(generations);
|
||||
let notifier = Arc::clone(¬ifier.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
notifier();
|
||||
}
|
||||
first = false;
|
||||
poll
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::arena::Arena;
|
||||
use crate::context::{ContextImpl, Ctx, CtxSnapshot, EvalScope, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots};
|
||||
use crate::gpoll::GPoll;
|
||||
use crate::node::Node;
|
||||
use crate::record::{Layout, RecordExtract, RecordLift, element_write};
|
||||
use crate::transform::Footprint;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockRuntime {
|
||||
futures: Mutex<Vec<(SourceId, SourceFuture)>>,
|
||||
}
|
||||
|
||||
impl Runtime for MockRuntime {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool {
|
||||
self.futures.lock().unwrap().push((source, future));
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl MockRuntime {
|
||||
fn drain(&self) -> Vec<SourceId> {
|
||||
let futures = std::mem::take(&mut *self.futures.lock().unwrap());
|
||||
let mut task_ctx = std::task::Context::from_waker(std::task::Waker::noop());
|
||||
futures
|
||||
.into_iter()
|
||||
.map(|(source, mut future)| {
|
||||
assert!(future.as_mut().poll(&mut task_ctx).is_ready());
|
||||
source
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CollectSpawner {
|
||||
tasks: Mutex<Vec<SourceFuture>>,
|
||||
}
|
||||
|
||||
impl Spawner for CollectSpawner {
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
self.tasks.lock().unwrap().push(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
struct YieldOnce(bool);
|
||||
|
||||
impl Future for YieldOnce {
|
||||
type Output = ();
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, task_context: &mut std::task::Context<'_>) -> std::task::Poll<()> {
|
||||
if self.0 {
|
||||
return std::task::Poll::Ready(());
|
||||
}
|
||||
self.0 = true;
|
||||
task_context.waker().wake_by_ref();
|
||||
std::task::Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
fn yield_once() -> YieldOnce {
|
||||
YieldOnce(false)
|
||||
}
|
||||
|
||||
impl CollectSpawner {
|
||||
fn drain(&self) -> usize {
|
||||
let tasks = std::mem::take(&mut *self.tasks.lock().unwrap());
|
||||
let mut task_ctx = std::task::Context::from_waker(std::task::Waker::noop());
|
||||
let count = tasks.len();
|
||||
for mut task in tasks {
|
||||
assert!(task.as_mut().poll(&mut task_ctx).is_ready());
|
||||
}
|
||||
count
|
||||
}
|
||||
}
|
||||
|
||||
struct SourceNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> Node<Input> for SourceNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn element_layout<T: Clone + Send + Sync + 'static>() -> Layout {
|
||||
Layout::default().with_writes(0, element_write::<T>(), &[])
|
||||
}
|
||||
|
||||
fn lifted<T: Clone + Send + Sync + 'static>(value: T) -> RecordLift<T, SourceNode<T>> {
|
||||
RecordLift::new(SourceNode(value))
|
||||
}
|
||||
|
||||
fn extract<El: Clone + Send + Sync + 'static, N>(graph: N) -> RecordExtract<El, N> {
|
||||
RecordExtract::new(graph, &element_layout::<El>())
|
||||
}
|
||||
|
||||
static SLOW_DOUBLE_RUNS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn slow_double(_: impl Ctx, value: f64) -> f64 {
|
||||
SLOW_DOUBLE_RUNS.fetch_add(1, Ordering::Relaxed);
|
||||
value * 2.
|
||||
}
|
||||
|
||||
fn stand_in(_value: &f64) -> f64 {
|
||||
-1.
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), placeholder(stand_in))]
|
||||
async fn preview_double(_: impl Ctx, value: f64) -> f64 {
|
||||
value * 2.
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), placeholder(stand_in), no_partial)]
|
||||
async fn strict_double(_: impl Ctx, value: f64) -> f64 {
|
||||
value * 2.
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn snapshot_resolution(ctx: CtxSnapshot, _primary: ()) -> u32 {
|
||||
ctx.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn snapshot_vararg(ctx: CtxSnapshot, _primary: ()) -> f64 {
|
||||
ctx.vararg(0).ok().and_then(|slot| slot.downcast_ref::<f64>()).copied().unwrap_or(0.)
|
||||
}
|
||||
|
||||
static STAGED_RUNS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn staged_double(_: impl Ctx, value: f64) -> SourceFuture<f64> {
|
||||
STAGED_RUNS.fetch_add(1, Ordering::Relaxed);
|
||||
Box::pin(async move { value * 2. })
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn staged_sum(ctx: impl Ctx, value: f64, addend: impl Node<Context<'_>, Output = f64>) -> Result<SourceFuture<f64>, crate::gpoll::Interrupt> {
|
||||
let addend = addend.eval(ctx)?;
|
||||
Ok(Box::pin(async move { value + addend }))
|
||||
}
|
||||
|
||||
struct GatedSource(Arc<std::sync::atomic::AtomicBool>, f64);
|
||||
|
||||
impl<Input> Node<Input> for GatedSource {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
match self.0.load(Ordering::Relaxed) {
|
||||
true => GPoll::Final(self.1),
|
||||
false => GPoll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(None, None, None, generations, arena)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_source_spawns_once_and_lands_via_the_slot() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = extract::<f64, _>(SlowDoubleNode::new(
|
||||
lifted(21.0f64),
|
||||
lifted(RuntimeHandle(runtime.clone())),
|
||||
lifted(7u64),
|
||||
&element_layout::<f64>(),
|
||||
&element_layout::<RuntimeHandle>(),
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(runtime.drain(), vec![7]);
|
||||
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_source_reports_the_placeholder_while_in_flight() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = extract::<f64, _>(PreviewDoubleNode::new(
|
||||
lifted(21.0f64),
|
||||
lifted(RuntimeHandle(runtime.clone())),
|
||||
lifted(1u64),
|
||||
&element_layout::<f64>(),
|
||||
&element_layout::<RuntimeHandle>(),
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Partial(-1.0));
|
||||
runtime.drain();
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_partial_maps_the_placeholder_frame_to_pending() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = extract::<f64, _>(StrictDoubleNode::new(
|
||||
lifted(21.0f64),
|
||||
lifted(RuntimeHandle(runtime.clone())),
|
||||
lifted(2u64),
|
||||
&element_layout::<f64>(),
|
||||
&element_layout::<RuntimeHandle>(),
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
runtime.drain();
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prologue_runs_sync_and_spawns_once() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = extract::<f64, _>(StagedDoubleNode::new(
|
||||
lifted(21.0f64),
|
||||
lifted(RuntimeHandle(runtime.clone())),
|
||||
lifted(8u64),
|
||||
&element_layout::<f64>(),
|
||||
&element_layout::<RuntimeHandle>(),
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "the prologue runs synchronously on the miss");
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "in flight must not rerun the prologue");
|
||||
assert_eq!(runtime.drain(), vec![8]);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prologue_interrupt_defers_the_spawn() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let gate = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = extract::<f64, _>(StagedSumNode::new(
|
||||
lifted(40.0f64),
|
||||
RecordLift::<f64, _>::new(GatedSource(gate.clone(), 2.0)),
|
||||
lifted(RuntimeHandle(runtime.clone())),
|
||||
lifted(9u64),
|
||||
&element_layout::<f64>(),
|
||||
&element_layout::<f64>(),
|
||||
&element_layout::<RuntimeHandle>(),
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(runtime.drain(), Vec::<SourceId>::new(), "an interrupted prologue must not spawn or claim the slot");
|
||||
gate.store(true, Ordering::Relaxed);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(runtime.drain(), vec![9]);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_kernels_read_captured_varargs() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
let payload = 21.5f64;
|
||||
let link = VarArgLink {
|
||||
args: VarArgSlots::Single(&payload),
|
||||
outer: None,
|
||||
};
|
||||
let ctx = root.with_varargs(&link);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = extract::<f64, _>(SnapshotVarargNode::new(
|
||||
lifted(()),
|
||||
lifted(RuntimeHandle(runtime.clone())),
|
||||
lifted(5u64),
|
||||
&element_layout::<()>(),
|
||||
&element_layout::<RuntimeHandle>(),
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
runtime.drain();
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(21.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_kernels_read_the_captured_context_snapshot() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
let footprint = Footprint::DEFAULT;
|
||||
let ctx = root.with_footprint(&footprint);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = extract::<u32, _>(SnapshotResolutionNode::new(
|
||||
lifted(()),
|
||||
lifted(RuntimeHandle(runtime.clone())),
|
||||
lifted(3u64),
|
||||
&element_layout::<()>(),
|
||||
&element_layout::<RuntimeHandle>(),
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
runtime.drain();
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(Footprint::DEFAULT.resolution.x));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_epilogue_bumps_the_generation_and_sets_dirty() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
|
||||
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
|
||||
assert_eq!(runtime.snapshot(), vec![(7, 0)], "no bump before the future completes");
|
||||
assert!(!runtime.take_dirty());
|
||||
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
assert_eq!(runtime.snapshot(), vec![(7, 1)]);
|
||||
assert!(runtime.take_dirty());
|
||||
assert!(!runtime.take_dirty(), "take_dirty drains the flag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_epilogue_notifies_after_setting_dirty() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
let observed_dirty = Arc::new(AtomicBool::new(false));
|
||||
let dirty_at_notify = Arc::clone(&runtime.dirty);
|
||||
let observed = Arc::clone(&observed_dirty);
|
||||
runtime.set_notifier(Arc::new(move || {
|
||||
observed.store(dirty_at_notify.load(Ordering::Acquire), Ordering::Relaxed);
|
||||
}));
|
||||
|
||||
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
assert!(observed_dirty.load(Ordering::Relaxed), "the notifier must observe the dirty flag already set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_epilogue_of_a_removed_source_does_not_notify() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
let notified = Arc::new(AtomicBool::new(false));
|
||||
let flag = Arc::clone(¬ified);
|
||||
runtime.set_notifier(Arc::new(move || flag.store(true, Ordering::Relaxed)));
|
||||
|
||||
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
|
||||
runtime.retain_sources(&[]);
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
assert!(!notified.load(Ordering::Relaxed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_epilogue_of_a_removed_source_is_inert() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
|
||||
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
|
||||
runtime.retain_sources(&[]);
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
|
||||
assert_eq!(runtime.snapshot(), Vec::<(SourceId, u64)>::new());
|
||||
assert!(!runtime.take_dirty(), "a removed source must not invalidate");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retain_sources_preserves_live_generations() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
|
||||
runtime.spawner().drain();
|
||||
|
||||
runtime.retain_sources(&[7, 9]);
|
||||
assert_eq!(runtime.snapshot(), vec![(7, 1), (9, 0)]);
|
||||
|
||||
runtime.retain_sources(&[9]);
|
||||
assert_eq!(runtime.snapshot(), vec![(9, 0)]);
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn epilogue_double(_: impl Ctx, value: f64) -> f64 {
|
||||
yield_once().await;
|
||||
value * 2.
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn inline_double(_: impl Ctx, value: f64) -> f64 {
|
||||
value * 2.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_immediately_ready_task_completes_inline_without_invalidating() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
|
||||
assert!(Runtime::spawn(&runtime, 7, Box::pin(async {})));
|
||||
assert_eq!(runtime.spawner().drain(), 0);
|
||||
assert_eq!(runtime.snapshot(), vec![(7, 0)], "inline completion must not bump the generation");
|
||||
assert!(!runtime.take_dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_immediately_ready_kernel_returns_final_on_the_first_eval() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
|
||||
runtime.retain_sources(&[13]);
|
||||
let graph = extract::<f64, _>(InlineDoubleNode::new(
|
||||
lifted(21.0f64),
|
||||
lifted(RuntimeHandle(runtime.clone())),
|
||||
lifted(13u64),
|
||||
&element_layout::<f64>(),
|
||||
&element_layout::<RuntimeHandle>(),
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
let snapshot = runtime.snapshot();
|
||||
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
assert!(!runtime.take_dirty());
|
||||
assert_eq!(runtime.snapshot(), vec![(13, 0)]);
|
||||
assert_eq!(runtime.spawner().drain(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_slot_lands_through_the_runtime_while_downstream_keys_invalidate() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
|
||||
runtime.retain_sources(&[11]);
|
||||
let graph = extract::<f64, _>(EpilogueDoubleNode::new(
|
||||
lifted(21.0f64),
|
||||
lifted(RuntimeHandle(runtime.clone())),
|
||||
lifted(11u64),
|
||||
&element_layout::<f64>(),
|
||||
&element_layout::<RuntimeHandle>(),
|
||||
&element_layout::<u64>(),
|
||||
));
|
||||
|
||||
let snapshot = runtime.snapshot();
|
||||
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert!(!runtime.take_dirty());
|
||||
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
assert!(runtime.take_dirty());
|
||||
let bumped = runtime.snapshot();
|
||||
assert_eq!(bumped, vec![(11, 1)]);
|
||||
|
||||
let bumped_scope = EvalScope::new(None, None, None, &bumped, &arena);
|
||||
let bumped_ctx = ContextImpl::root(&bumped_scope);
|
||||
assert_eq!(Node::eval(&graph, &bumped_ctx), GPoll::Final(42.0), "the own-generation-excluded key replays the landed slot");
|
||||
assert_eq!(runtime.spawner().drain(), 0, "a slot hit must not respawn");
|
||||
|
||||
let downstream_key = crate::registry::cache_key(&ContextImpl::root(&scope));
|
||||
let bumped_downstream_key = crate::registry::cache_key(&ContextImpl::root(&bumped_scope));
|
||||
assert_ne!(downstream_key, bumped_downstream_key, "unretained keys see the bump");
|
||||
}
|
||||
}
|
||||
@@ -235,8 +235,7 @@ pub enum Type {
|
||||
Fn(Box<Type>, Box<Type>),
|
||||
/// Represents a future which promises to return the inner type.
|
||||
Future(Box<Type>),
|
||||
/// A packed record wire over the element type; the layout stays node-resident metadata.
|
||||
Record(Box<Type>),
|
||||
Ref(Box<Type>),
|
||||
}
|
||||
|
||||
impl Default for Type {
|
||||
@@ -310,7 +309,7 @@ impl Type {
|
||||
Self::Concrete(ty) => Some(ty.size),
|
||||
Self::Fn(_, _) => None,
|
||||
Self::Future(_) => None,
|
||||
Self::Record(_) => None,
|
||||
Self::Ref(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,7 +319,7 @@ impl Type {
|
||||
Self::Concrete(ty) => Some(ty.align),
|
||||
Self::Fn(_, _) => None,
|
||||
Self::Future(_) => None,
|
||||
Self::Record(_) => None,
|
||||
Self::Ref(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -330,7 +329,7 @@ impl Type {
|
||||
Self::Concrete(_) => self,
|
||||
Self::Fn(_, output) => output.nested_type(),
|
||||
Self::Future(output) => output.nested_type(),
|
||||
Self::Record(inner) => inner.nested_type(),
|
||||
Self::Ref(inner) => inner.nested_type(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,7 +342,7 @@ impl Type {
|
||||
Self::Concrete(_) => None,
|
||||
Self::Fn(_, output) => output.replace_nested(f),
|
||||
Self::Future(output) => output.replace_nested(f),
|
||||
Self::Record(inner) => inner.replace_nested(f),
|
||||
Self::Ref(inner) => inner.replace_nested(f),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -353,7 +352,7 @@ impl Type {
|
||||
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::Future(ty) => ty.identifier_name(),
|
||||
Type::Record(ty) => ty.identifier_name(),
|
||||
Type::Ref(ty) => ty.identifier_name(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -368,7 +367,7 @@ pub fn simplify_identifier_name(ty: &str) -> String {
|
||||
/// Converts a Rust-internal type name to its user-facing form.
|
||||
pub fn make_type_user_readable(ty: &str) -> String {
|
||||
let ty = ty
|
||||
.replace("ContextImpl", "Context")
|
||||
.replace("Option<Arc<OwnedContextImpl>>", "Context")
|
||||
.replace("Raster<CPU>", "Raster")
|
||||
.replace("Raster<GPU>", "Raster")
|
||||
.replace("DAffine2", "Transform")
|
||||
@@ -448,7 +447,7 @@ impl std::fmt::Display for Type {
|
||||
Type::Concrete(ty) => write!(f, "{ty}"),
|
||||
Type::Fn(_, return_value) => write!(f, "{return_value}"),
|
||||
Type::Future(ty) => write!(f, "{ty}"),
|
||||
Type::Record(ty) => write!(f, "{ty}"),
|
||||
Type::Ref(ty) => write!(f, "{ty}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,55 +1,103 @@
|
||||
use crate::Node;
|
||||
use std::cell::{Cell, RefCell, RefMut};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
|
||||
pub struct IntNode<const N: u32>;
|
||||
|
||||
impl<'i, const N: u32, I> Node<'i, I> for IntNode<N> {
|
||||
type Output = u32;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _input: I) -> Self::Output {
|
||||
N
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy)]
|
||||
pub struct ValueNode<T>(pub T);
|
||||
|
||||
impl<'i, T: 'i, I> Node<'i, I> for ValueNode<T> {
|
||||
type Output = &'i T;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _input: I) -> Self::Output {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ValueNode<T> {
|
||||
pub const fn new(value: T) -> ValueNode<T> {
|
||||
ValueNode(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<T> for ValueNode<T> {
|
||||
fn from(value: T) -> Self {
|
||||
ValueNode::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy)]
|
||||
pub struct AsRefNode<T: AsRef<U>, U>(pub T, PhantomData<U>);
|
||||
|
||||
impl<'i, T: 'i + AsRef<U>, U: 'i> Node<'i, ()> for AsRefNode<T, U> {
|
||||
type Output = &'i U;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _input: ()) -> Self::Output {
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<U>, U> AsRefNode<T, U> {
|
||||
pub const fn new(value: T) -> AsRefNode<T, U> {
|
||||
AsRefNode(value, PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct RefCellMutNode<T>(pub RefCell<T>);
|
||||
|
||||
impl<'i, T: 'i> Node<'i, ()> for RefCellMutNode<T> {
|
||||
type Output = RefMut<'i, T>;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _input: ()) -> Self::Output {
|
||||
self.0.borrow_mut()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> RefCellMutNode<T> {
|
||||
pub const fn new(value: T) -> RefCellMutNode<T> {
|
||||
RefCellMutNode(RefCell::new(value))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct OnceCellNode<T>(pub Cell<T>);
|
||||
|
||||
impl<'i, T: Default + 'i, I> Node<'i, I> for OnceCellNode<T> {
|
||||
type Output = T;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _input: I) -> Self::Output {
|
||||
self.0.replace(T::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> OnceCellNode<T> {
|
||||
pub const fn new(value: T) -> OnceCellNode<T> {
|
||||
OnceCellNode(Cell::new(value))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ClonedNode<T: Clone>(pub T);
|
||||
|
||||
impl<T: Clone, Input> crate::node::Node<Input> for ClonedNode<T> {
|
||||
impl<'i, T: Clone + 'i, I> Node<'i, I> for ClonedNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> crate::gpoll::GPoll<T> {
|
||||
crate::gpoll::GPoll::Final(self.0.clone())
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _input: I) -> Self::Output {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value_edge<T: Clone + crate::WasmNotSend + crate::WasmNotSync + 'static>(value: T) -> crate::registry::EdgeHandle {
|
||||
crate::registry::EdgeHandle::new(std::sync::Arc::new(ClonedNode(value)) as std::sync::Arc<crate::registry::ErasedNode<T>>)
|
||||
}
|
||||
|
||||
/// The node behind every value edge: clones its constant onto the record
|
||||
/// wire per evaluation.
|
||||
pub struct ValueSource<T> {
|
||||
value: T,
|
||||
layout: crate::record::Layout,
|
||||
}
|
||||
|
||||
impl<T: Clone + Send + Sync + 'static> ValueSource<T> {
|
||||
pub fn new(value: T) -> Self {
|
||||
Self {
|
||||
value,
|
||||
layout: crate::record::Layout::default().with_writes(0, crate::record::element_write::<T>(), &[]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e, C, T> crate::node::Node<C> for ValueSource<T>
|
||||
where
|
||||
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
T: Clone + Send + Sync + 'static,
|
||||
{
|
||||
type Output = crate::record::RecordValue<'e>;
|
||||
|
||||
fn eval(&self, input: &C) -> crate::gpoll::GPoll<crate::record::RecordValue<'e>> {
|
||||
crate::record::lift_poll(crate::gpoll::GPoll::Final(self.value.clone()), &self.layout, input.arena())
|
||||
}
|
||||
|
||||
fn layout(&self) -> Option<&crate::record::Layout> {
|
||||
Some(&self.layout)
|
||||
}
|
||||
}
|
||||
|
||||
/// The native record edge of a constant.
|
||||
pub fn record_value_edge<T: Clone + Send + Sync + 'static>(value: T) -> crate::registry::EdgeHandle {
|
||||
crate::registry::EdgeHandle::new_record::<T>(std::sync::Arc::new(ValueSource::new(value)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||
}
|
||||
|
||||
impl<T: Clone> ClonedNode<T> {
|
||||
pub const fn new(value: T) -> ClonedNode<T> {
|
||||
ClonedNode(value)
|
||||
@@ -61,3 +109,103 @@ impl<T: Clone> From<T> for ClonedNode<T> {
|
||||
ClonedNode::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
/// The DebugClonedNode logs every time it is evaluated.
|
||||
/// This is useful for debugging.
|
||||
pub struct DebugClonedNode<T: Clone>(pub T);
|
||||
|
||||
impl<'i, T: Clone + 'i> Node<'i, ()> for DebugClonedNode<T> {
|
||||
type Output = T;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _input: ()) -> Self::Output {
|
||||
// KEEP THIS `debug!()` - It acts as the output for the debug node itself
|
||||
log::debug!("DebugClonedNode::eval");
|
||||
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> DebugClonedNode<T> {
|
||||
pub const fn new(value: T) -> DebugClonedNode<T> {
|
||||
DebugClonedNode(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct CopiedNode<T: Copy>(pub T);
|
||||
|
||||
impl<'i, T: Copy + 'i, I> Node<'i, I> for CopiedNode<T> {
|
||||
type Output = T;
|
||||
#[inline(always)]
|
||||
fn eval(&'i self, _input: I) -> Self::Output {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy> CopiedNode<T> {
|
||||
pub const fn new(value: T) -> CopiedNode<T> {
|
||||
CopiedNode(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct DefaultNode<T>(PhantomData<T>);
|
||||
|
||||
impl<'i, T: Default + 'i, I> Node<'i, I> for DefaultNode<T> {
|
||||
type Output = T;
|
||||
fn eval(&'i self, _input: I) -> Self::Output {
|
||||
T::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> DefaultNode<T> {
|
||||
pub fn new() -> Self {
|
||||
Self(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
/// Return the unit value
|
||||
#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
|
||||
pub struct ForgetNode;
|
||||
|
||||
impl<'i, T: 'i> Node<'i, T> for ForgetNode {
|
||||
type Output = ();
|
||||
fn eval(&'i self, _input: T) -> Self::Output {}
|
||||
}
|
||||
|
||||
impl ForgetNode {
|
||||
pub const fn new() -> Self {
|
||||
ForgetNode
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_int_node() {
|
||||
let node = IntNode::<5>;
|
||||
assert_eq!(node.eval(()), 5);
|
||||
}
|
||||
#[test]
|
||||
fn test_value_node() {
|
||||
let node = ValueNode::new(5);
|
||||
assert_eq!(node.eval(()), &5);
|
||||
let type_erased = &node as &dyn for<'a> Node<'a, (), Output = &'a i32>;
|
||||
assert_eq!(type_erased.eval(()), &5);
|
||||
}
|
||||
#[test]
|
||||
fn test_default_node() {
|
||||
let node = DefaultNode::<u32>::new();
|
||||
assert_eq!(node.eval(42), 0);
|
||||
}
|
||||
#[test]
|
||||
#[allow(clippy::unit_cmp)]
|
||||
fn test_unit_node() {
|
||||
let node = ForgetNode::new();
|
||||
assert_eq!(node.eval(()), ());
|
||||
}
|
||||
}
|
||||
@@ -9,16 +9,17 @@ use crate::texture_cache::TextureCache;
|
||||
use anyhow::Result;
|
||||
use core_types::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use futures::lock::Mutex;
|
||||
use glam::UVec2;
|
||||
use graphene_application_io::{ApplicationIo, EditorApi};
|
||||
use raster_types::Texture;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use vello::{AaConfig, AaSupport, RenderParams, Renderer, RendererOptions, Scene};
|
||||
use wgpu::{Origin3d, TextureAspect};
|
||||
|
||||
pub use context::Context as WgpuContext;
|
||||
pub use context::ContextBuilder as WgpuContextBuilder;
|
||||
pub use pipeline::AsyncPipeline as AsyncWgpuPipeline;
|
||||
pub use pipeline::Pipeline as WgpuPipeline;
|
||||
pub use pipeline::PipelineCache as WgpuPipelineCache;
|
||||
pub use rendering::RenderContext;
|
||||
@@ -60,18 +61,6 @@ impl std::fmt::Debug for WgpuExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Owned Arc handle carrying the executor as an ordinary wire value.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WgpuExecutorHandle(pub std::sync::Arc<WgpuExecutor>);
|
||||
|
||||
impl std::ops::Deref for WgpuExecutorHandle {
|
||||
type Target = WgpuExecutor;
|
||||
|
||||
fn deref(&self) -> &WgpuExecutor {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: ApplicationIo<Executor = WgpuExecutor>> From<&'a EditorApi<T>> for &'a WgpuExecutor {
|
||||
fn from(editor_api: &'a EditorApi<T>) -> Self {
|
||||
editor_api.application_io.as_ref().unwrap().gpu_executor().unwrap()
|
||||
@@ -79,8 +68,8 @@ impl<'a, T: ApplicationIo<Executor = WgpuExecutor>> From<&'a EditorApi<T>> for &
|
||||
}
|
||||
|
||||
impl WgpuExecutor {
|
||||
pub fn render_vello_scene(&self, scene: &Scene, size: UVec2, context: &RenderContext, background: Option<Color>) -> Result<Texture> {
|
||||
let texture = self.request_texture(size);
|
||||
pub async 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_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
@@ -93,7 +82,7 @@ impl WgpuExecutor {
|
||||
};
|
||||
|
||||
{
|
||||
let mut renderer = self.inner.vello_renderer.lock().unwrap();
|
||||
let mut renderer = self.inner.vello_renderer.lock().await;
|
||||
for (image_brush, texture) in context.resource_overrides.iter() {
|
||||
let texture_view = wgpu::TexelCopyTextureInfoBase {
|
||||
texture: (**texture).clone(),
|
||||
@@ -120,8 +109,8 @@ impl WgpuExecutor {
|
||||
pipeline.init::<P>(self);
|
||||
}
|
||||
|
||||
pub fn request_texture(&self, size: UVec2) -> Texture {
|
||||
self.inner.texture_cache.lock().unwrap().request_texture(&self.context().device, size)
|
||||
pub async fn request_texture(&self, size: UVec2) -> Texture {
|
||||
self.inner.texture_cache.lock().await.request_texture(&self.context().device, size)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,42 @@
|
||||
use dyn_any::DynAny;
|
||||
use std::any::Any;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use crate::WgpuExecutor;
|
||||
|
||||
pub type PipelineFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
||||
pub trait Pipeline: 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<'_>) -> Self::Out;
|
||||
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> PipelineFuture<'a, 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)]
|
||||
@@ -25,13 +51,13 @@ impl PipelineCache {
|
||||
self.pipeline.get_or_init(|| Box::new(P::create(executor)));
|
||||
}
|
||||
|
||||
pub fn run<P: Pipeline>(&self, args: &P::Args<'_>) -> P::Out {
|
||||
pub async fn run<P: Pipeline>(&self, args: &P::Args<'_>) -> P::Out {
|
||||
let executor = self.executor.get().expect("PipelineCache not initialized");
|
||||
let entry = self.pipeline.get().expect("PipelineCache not initialized");
|
||||
let pipeline = (**entry)
|
||||
let pipeline = (&**entry)
|
||||
.downcast_ref::<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)
|
||||
pipeline.run(executor, args).await
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@ use crate::WgpuContext;
|
||||
use crate::shader_runtime::{FULLSCREEN_VERTEX_SHADER_NAME, ShaderRuntime};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::shaders::buffer_struct::BufferStruct;
|
||||
use futures::lock::Mutex;
|
||||
use raster_types::{GPU, Raster};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use wgpu::util::{BufferInitDescriptor, DeviceExt};
|
||||
use wgpu::{
|
||||
BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingType, Buffer, BufferBinding, BufferBindingType, BufferUsages, ColorTargetState, Face,
|
||||
@@ -33,8 +33,8 @@ impl PerPixelAdjustShaderRuntime {
|
||||
}
|
||||
|
||||
impl ShaderRuntime {
|
||||
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().unwrap_or_else(PoisonError::into_inner);
|
||||
pub async 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 pipeline = cache
|
||||
.entry(shaders.fragment_shader_name.to_owned())
|
||||
.or_insert_with(|| PerPixelAdjustGraphicsPipeline::new(&self.context, shaders));
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
use crate::WgpuExecutorHandle;
|
||||
use crate::WgpuExecutor;
|
||||
use core_types::Color;
|
||||
use core_types::Ctx;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::ops::{Convert, ConvertAsync};
|
||||
use core_types::runtime::SourceFuture;
|
||||
use core_types::ops::Convert;
|
||||
use core_types::transform::Footprint;
|
||||
use raster_types::Image;
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -39,52 +38,6 @@ fn upload_to_texture(device: &wgpu::Device, queue: &wgpu::Queue, image: &Raster<
|
||||
)
|
||||
}
|
||||
|
||||
/// Passthrough conversion for GPU `List`s - no conversion needed
|
||||
impl Convert<List<Raster<GPU>>, WgpuExecutorHandle> for List<Raster<GPU>> {
|
||||
fn convert(self, _: Footprint, _converter: WgpuExecutorHandle) -> List<Raster<GPU>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a `List<Raster<CPU>>` to `List<Raster<GPU>>` by uploading each image to a texture
|
||||
impl Convert<List<Raster<GPU>>, WgpuExecutorHandle> for List<Raster<CPU>> {
|
||||
fn convert(self, _: Footprint, executor: WgpuExecutorHandle) -> List<Raster<GPU>> {
|
||||
let device = &executor.context().device;
|
||||
let queue = executor.context().queue.lock();
|
||||
let list = self
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let (image, attributes) = row.into_parts();
|
||||
let texture = upload_to_texture(device, &queue, &image);
|
||||
|
||||
Item::from_parts(Raster::new_gpu(texture), attributes)
|
||||
})
|
||||
.collect();
|
||||
|
||||
queue.submit([]);
|
||||
list
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts single CPU raster to GPU by uploading to texture
|
||||
impl Convert<Raster<GPU>, WgpuExecutorHandle> for Raster<CPU> {
|
||||
fn convert(self, _: Footprint, executor: WgpuExecutorHandle) -> Raster<GPU> {
|
||||
let device = &executor.context().device;
|
||||
let queue = executor.context().queue.lock();
|
||||
let texture = upload_to_texture(device, &queue, &self);
|
||||
|
||||
queue.submit([]);
|
||||
Raster::new_gpu(texture)
|
||||
}
|
||||
}
|
||||
|
||||
/// Passthrough conversion for CPU `List`s - no conversion needed
|
||||
impl Convert<List<Raster<CPU>>, WgpuExecutorHandle> for List<Raster<CPU>> {
|
||||
fn convert(self, _: Footprint, _converter: WgpuExecutorHandle) -> List<Raster<CPU>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a Raster<GPU> texture to Raster<CPU> by downloading the underlying texture data.
|
||||
///
|
||||
/// Assumptions:
|
||||
@@ -189,11 +142,57 @@ impl RasterGpuToRasterCpuConverter {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 ConvertAsync<List<Raster<CPU>>, WgpuExecutorHandle> for List<Raster<GPU>> {
|
||||
fn convert(self, _: Footprint, executor: WgpuExecutorHandle) -> SourceFuture<List<Raster<CPU>>> {
|
||||
let device = executor.context().device.clone();
|
||||
/// Passthrough conversion for GPU `List`s - no conversion needed
|
||||
impl<'i> Convert<List<Raster<GPU>>, &'i WgpuExecutor> for List<Raster<GPU>> {
|
||||
async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<GPU>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a `List<Raster<CPU>>` to `List<Raster<GPU>>` by uploading each image to a texture
|
||||
impl<'i> Convert<List<Raster<GPU>>, &'i WgpuExecutor> for List<Raster<CPU>> {
|
||||
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> List<Raster<GPU>> {
|
||||
let device = &executor.context().device;
|
||||
let queue = executor.context().queue.lock();
|
||||
let list = self
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let (image, attributes) = row.into_parts();
|
||||
let texture = upload_to_texture(device, &queue, &image);
|
||||
|
||||
Item::from_parts(Raster::new_gpu(texture), attributes)
|
||||
})
|
||||
.collect();
|
||||
|
||||
queue.submit([]);
|
||||
list
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts single CPU raster to GPU by uploading to texture
|
||||
impl<'i> Convert<Raster<GPU>, &'i WgpuExecutor> for Raster<CPU> {
|
||||
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<GPU> {
|
||||
let device = &executor.context().device;
|
||||
let queue = executor.context().queue.lock();
|
||||
let texture = upload_to_texture(device, &queue, &self);
|
||||
|
||||
queue.submit([]);
|
||||
Raster::new_gpu(texture)
|
||||
}
|
||||
}
|
||||
|
||||
/// Passthrough conversion for CPU `List`s - no conversion needed
|
||||
impl<'i> Convert<List<Raster<CPU>>, &'i WgpuExecutor> for List<Raster<CPU>> {
|
||||
async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<CPU>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a `List<Raster<GPU>>` to `List<Raster<CPU>>` by downloading texture data in one go then asynchronously maps all buffers and processes the results.
|
||||
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"),
|
||||
@@ -204,50 +203,48 @@ impl ConvertAsync<List<Raster<CPU>>, WgpuExecutorHandle> for List<Raster<GPU>> {
|
||||
|
||||
for row in self {
|
||||
let (element, attributes) = row.into_parts();
|
||||
converters.push(RasterGpuToRasterCpuConverter::new(&device, &mut encoder, element));
|
||||
converters.push(RasterGpuToRasterCpuConverter::new(device, &mut encoder, element));
|
||||
rows_meta.push(Item::from_parts((), attributes));
|
||||
}
|
||||
|
||||
queue.submit([encoder.finish()]);
|
||||
|
||||
Box::pin(async move {
|
||||
let mut map_futures = Vec::new();
|
||||
for converter in converters {
|
||||
map_futures.push(converter.convert(&device));
|
||||
}
|
||||
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");
|
||||
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()
|
||||
})
|
||||
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 ConvertAsync<Raster<CPU>, WgpuExecutorHandle> for Raster<GPU> {
|
||||
fn convert(self, _: Footprint, executor: WgpuExecutorHandle) -> SourceFuture<Raster<CPU>> {
|
||||
let device = executor.context().device.clone();
|
||||
let queue = executor.context().queue.lock();
|
||||
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);
|
||||
let converter = RasterGpuToRasterCpuConverter::new(device, &mut encoder, self);
|
||||
|
||||
queue.submit([encoder.finish()]);
|
||||
|
||||
Box::pin(async move { converter.convert(&device).await.expect("Failed to download texture data") })
|
||||
converter.convert(device).await.expect("Failed to download texture data")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,10 +252,10 @@ impl ConvertAsync<Raster<CPU>, WgpuExecutorHandle> for Raster<GPU> {
|
||||
///
|
||||
/// Accepts either individual raster data or a `List` of raster elements and converts it to the GPU format using the WgpuExecutor's device and queue.
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn upload_texture<T: Convert<List<Raster<GPU>>, WgpuExecutorHandle>>(
|
||||
pub async fn upload_texture<'a: 'n, T: Convert<List<Raster<GPU>>, &'a WgpuExecutor>>(
|
||||
_: impl Ctx,
|
||||
#[implementations(List<Raster<CPU>>, List<Raster<GPU>>)] input: T,
|
||||
executor: WgpuExecutorHandle,
|
||||
executor: &'a WgpuExecutor,
|
||||
) -> List<Raster<GPU>> {
|
||||
input.convert(Footprint::DEFAULT, executor)
|
||||
input.convert(Footprint::DEFAULT, executor).await
|
||||
}
|
||||
+346
-2671
File diff suppressed because it is too large.
Load diff
@@ -7,8 +7,8 @@ use syn::punctuated::Punctuated;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::token::{Comma, RArrow};
|
||||
use syn::{
|
||||
AttrStyle, Attribute, Error, Expr, FnArg, GenericArgument, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, PathArguments, ReturnType,
|
||||
TraitBound, Type, TypeImplTrait, TypeParam, TypeParamBound, Visibility, WhereClause, parse_quote,
|
||||
AttrStyle, Attribute, Error, Expr, FnArg, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, ReturnType, TraitBound, Type, TypeImplTrait, TypeParam,
|
||||
TypeParamBound, Visibility, WhereClause, parse_quote,
|
||||
};
|
||||
|
||||
use crate::codegen::generate_node_code;
|
||||
@@ -39,74 +39,6 @@ pub(crate) struct ParsedNodeFn {
|
||||
pub(crate) description: String,
|
||||
}
|
||||
|
||||
/// An `Attr<Marker>` slot in a parameter's read tuple: a declared attribute
|
||||
/// read on that input's wire, not a wired input of its own.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct AttributeRead {
|
||||
pub(crate) pat_ident: PatIdent,
|
||||
pub(crate) marker: Type,
|
||||
}
|
||||
|
||||
/// The write half of a record kernel's return: the element type in the first
|
||||
/// tuple slot, then the attribute markers written and the ones removed. `None`
|
||||
/// unless the value is a well-formed write tuple (a non-marker element first,
|
||||
/// then only `Attr` and `RemoveAttr` slots, at least one).
|
||||
pub(crate) struct RecordWrites {
|
||||
pub(crate) element: Type,
|
||||
pub(crate) markers: Vec<Type>,
|
||||
pub(crate) removes: Vec<Type>,
|
||||
}
|
||||
|
||||
pub(crate) fn record_writes(value: &Type) -> Option<RecordWrites> {
|
||||
let Type::Tuple(tuple) = value else { return None };
|
||||
let mut slots = tuple.elems.iter();
|
||||
let element = slots.next()?;
|
||||
if attr_marker(element).is_some() || remove_attr_marker(element).is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut markers = Vec::new();
|
||||
let mut removes = Vec::new();
|
||||
for slot in slots {
|
||||
if let Some(marker) = attr_marker(slot) {
|
||||
markers.push(marker);
|
||||
} else if let Some(marker) = remove_attr_marker(slot) {
|
||||
removes.push(marker);
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(!markers.is_empty() || !removes.is_empty()).then(|| RecordWrites {
|
||||
element: element.clone(),
|
||||
markers,
|
||||
removes,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the marker type of an `Attr<Marker>` type, if `ty` is one.
|
||||
pub(crate) fn attr_marker(ty: &Type) -> Option<Type> {
|
||||
marker_of(ty, "Attr")
|
||||
}
|
||||
|
||||
/// Returns the marker type of a `RemoveAttr<Marker>` type, if `ty` is one.
|
||||
pub(crate) fn remove_attr_marker(ty: &Type) -> Option<Type> {
|
||||
marker_of(ty, "RemoveAttr")
|
||||
}
|
||||
|
||||
fn marker_of(ty: &Type, wrapper: &str) -> Option<Type> {
|
||||
let Type::Path(path) = ty else { return None };
|
||||
let segment = path.path.segments.last()?;
|
||||
if segment.ident != wrapper {
|
||||
return None;
|
||||
}
|
||||
let PathArguments::AngleBracketed(args) = &segment.arguments else { return None };
|
||||
let mut types = args.args.iter().filter_map(|argument| match argument {
|
||||
GenericArgument::Type(ty) => Some(ty),
|
||||
_ => None,
|
||||
});
|
||||
let marker = types.next()?;
|
||||
types.next().is_none().then(|| marker.clone())
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub(crate) struct NodeFnAttributes {
|
||||
pub(crate) category: Option<LitStr>,
|
||||
@@ -124,16 +56,6 @@ pub(crate) struct NodeFnAttributes {
|
||||
pub(crate) memoize: bool,
|
||||
/// Whether this node provides a scope
|
||||
pub(crate) inject_scope: bool,
|
||||
/// Function producing a stand-in value while an async source node's real value is in flight
|
||||
pub(crate) placeholder: Option<Path>,
|
||||
/// Function overriding the generated `extent` method
|
||||
pub(crate) extent: Option<Path>,
|
||||
/// Function overriding the generated `eval_batch` method
|
||||
pub(crate) batch: Option<Path>,
|
||||
/// Whether partial upstream values are mapped to `Pending` instead of flowing into this node
|
||||
pub(crate) no_partial: bool,
|
||||
/// Whether this node keeps the plain-wire lowering during the record transition
|
||||
pub(crate) plain: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -141,8 +63,7 @@ pub enum ParsedValueSource {
|
||||
#[default]
|
||||
None,
|
||||
Default(TokenStream2),
|
||||
Scope(Box<Expr>),
|
||||
SourceId,
|
||||
Scope(Expr),
|
||||
}
|
||||
|
||||
// #[widget(ParsedWidgetOverride::Hidden)]
|
||||
@@ -197,9 +118,6 @@ pub struct ParsedField {
|
||||
pub number_step: Option<LitFloat>,
|
||||
pub unit: Option<LitStr>,
|
||||
pub is_data_field: bool,
|
||||
/// The attribute reads destructured from this input's tuple, resolved
|
||||
/// against this input's wire.
|
||||
pub(crate) attribute_reads: Vec<AttributeRead>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -313,8 +231,6 @@ impl Parse for NumberRange {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RegularParsedField {
|
||||
pub ty: Type,
|
||||
/// The original reference tokens when the parameter was written `&T`; `ty` holds the peeled inner type.
|
||||
pub lend: Option<syn::TypeReference>,
|
||||
pub exposed: bool,
|
||||
pub value_source: ParsedValueSource,
|
||||
pub number_soft_min: Option<NumberBound>,
|
||||
@@ -395,11 +311,6 @@ impl Parse for NodeFnAttributes {
|
||||
let mut serialize = None;
|
||||
let mut memoize = false;
|
||||
let mut inject_scope = false;
|
||||
let mut placeholder = None;
|
||||
let mut extent = None;
|
||||
let mut batch = None;
|
||||
let mut no_partial = false;
|
||||
let mut plain = false;
|
||||
|
||||
let content = input;
|
||||
// let content;
|
||||
@@ -542,70 +453,13 @@ impl Parse for NodeFnAttributes {
|
||||
}
|
||||
inject_scope = true;
|
||||
}
|
||||
// Function producing a stand-in value for an async source node while the spawned future is in flight.
|
||||
// The node reports `Partial` with the stand-in until the real value lands; without a placeholder it reports `Pending`.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., placeholder(empty_image), ...)]
|
||||
"placeholder" => {
|
||||
let meta = meta.require_list()?;
|
||||
if placeholder.is_some() {
|
||||
return Err(Error::new_spanned(meta, "Multiple 'placeholder' attributes are not allowed"));
|
||||
}
|
||||
let parsed_path: Path = meta
|
||||
.parse_args()
|
||||
.map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'placeholder', e.g., placeholder(empty_image)"))?;
|
||||
placeholder = Some(parsed_path);
|
||||
}
|
||||
// Function overriding the generated `extent` method, replacing the default meet over the node's inputs.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., extent(my_extent), ...)]
|
||||
"extent" => {
|
||||
let meta = meta.require_list()?;
|
||||
if extent.is_some() {
|
||||
return Err(Error::new_spanned(meta, "Multiple 'extent' attributes are not allowed"));
|
||||
}
|
||||
let parsed_path: Path = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'extent', e.g., extent(my_extent)"))?;
|
||||
extent = Some(parsed_path);
|
||||
}
|
||||
// Function overriding the generated `eval_batch` method, replacing the trait's per-lane spec loop.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., batch(my_batch), ...)]
|
||||
"batch" => {
|
||||
let meta = meta.require_list()?;
|
||||
if batch.is_some() {
|
||||
return Err(Error::new_spanned(meta, "Multiple 'batch' attributes are not allowed"));
|
||||
}
|
||||
let parsed_path: Path = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'batch', e.g., batch(my_batch)"))?;
|
||||
batch = Some(parsed_path);
|
||||
}
|
||||
// Instructs the generated eval to report `Pending` instead of passing partial upstream values into this node.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., no_partial, ...)]
|
||||
"plain" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if plain {
|
||||
return Err(Error::new_spanned(path, "Multiple 'plain' attributes are not allowed"));
|
||||
}
|
||||
plain = true;
|
||||
}
|
||||
"no_partial" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if no_partial {
|
||||
return Err(Error::new_spanned(path, "Multiple 'no_partial' attributes are not allowed"));
|
||||
}
|
||||
no_partial = true;
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::new_spanned(
|
||||
meta,
|
||||
indoc!(
|
||||
r#"
|
||||
Unsupported attribute in `node`.
|
||||
Supported attributes are 'category', 'name', 'path', 'skip_impl', 'properties', 'cfg', 'shader_node', 'serialize', 'memoize', 'inject_scope', 'placeholder', 'extent', 'batch', and 'no_partial'.
|
||||
Supported attributes are 'category', 'name', 'path', 'skip_impl', 'properties', 'cfg', 'shader_node', 'serialize', 'memoize', and 'inject_scope'.
|
||||
Example usage:
|
||||
#[node_macro::node(..., name("Test Node"), ...)]
|
||||
"#
|
||||
@@ -639,11 +493,6 @@ impl Parse for NodeFnAttributes {
|
||||
serialize,
|
||||
memoize,
|
||||
inject_scope,
|
||||
placeholder,
|
||||
extent,
|
||||
batch,
|
||||
no_partial,
|
||||
plain,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -735,24 +584,8 @@ fn parse_inputs(inputs: &Punctuated<FnArg, Comma>) -> syn::Result<(Input, Vec<Pa
|
||||
context_features,
|
||||
});
|
||||
} else if let Pat::Ident(pat_ident) = &**pat {
|
||||
if attr_marker(ty).is_some() {
|
||||
return Err(Error::new_spanned(pat_ident, "an attribute read binds to an input: destructure it as `(value, Attr<..>)`"));
|
||||
}
|
||||
let field = parse_field(pat_ident.clone(), (**ty).clone(), attrs).map_err(|e| Error::new_spanned(pat_ident, format!("Failed to parse argument '{}': {}", pat_ident.ident, e)))?;
|
||||
fields.push(field);
|
||||
} else if let Pat::Tuple(pat_tuple) = &**pat {
|
||||
let field = parse_read_tuple(pat_tuple, ty, attrs, index)?;
|
||||
fields.push(field);
|
||||
} else if let Pat::Wild(wild) = &**pat {
|
||||
let pat_ident = PatIdent {
|
||||
attrs: wild.attrs.clone(),
|
||||
by_ref: None,
|
||||
mutability: None,
|
||||
ident: format_ident!("_unit{}", index, span = wild.underscore_token.span),
|
||||
subpat: None,
|
||||
};
|
||||
let field = parse_field(pat_ident, (**ty).clone(), attrs).map_err(|e| Error::new_spanned(pat, format!("Failed to parse argument: {e}")))?;
|
||||
fields.push(field);
|
||||
} else {
|
||||
return Err(Error::new_spanned(pat, "Expected a simple identifier for the field name"));
|
||||
}
|
||||
@@ -765,85 +598,6 @@ fn parse_inputs(inputs: &Punctuated<FnArg, Comma>) -> syn::Result<(Input, Vec<Pa
|
||||
Ok((input, fields))
|
||||
}
|
||||
|
||||
/// Splits a lazy input's `Output = (T, Attr<..>..)` tuple into the element
|
||||
/// type (the wire type) and the declared reads on that edge. A tuple without
|
||||
/// `Attr` slots is an ordinary tuple output and passes through untouched.
|
||||
fn split_lazy_reads(output_type: Type) -> syn::Result<(Type, Vec<AttributeRead>)> {
|
||||
let Type::Tuple(tuple) = &output_type else {
|
||||
return Ok((output_type, Vec::new()));
|
||||
};
|
||||
if !tuple.elems.iter().any(|slot| attr_marker(slot).is_some()) {
|
||||
return Ok((output_type, Vec::new()));
|
||||
}
|
||||
let spelling = "a lazy input with attribute reads declares `Output = (T, Attr<..>)`";
|
||||
let mut slots = tuple.elems.iter();
|
||||
let element = slots.next().ok_or_else(|| Error::new_spanned(tuple, spelling))?;
|
||||
if attr_marker(element).is_some() {
|
||||
return Err(Error::new_spanned(element, spelling));
|
||||
}
|
||||
let attribute_reads: Vec<AttributeRead> = slots
|
||||
.enumerate()
|
||||
.map(|(index, slot)| {
|
||||
let marker = attr_marker(slot).ok_or_else(|| Error::new_spanned(slot, spelling))?;
|
||||
Ok(AttributeRead {
|
||||
pat_ident: PatIdent {
|
||||
attrs: Vec::new(),
|
||||
by_ref: None,
|
||||
mutability: None,
|
||||
ident: format_ident!("__lazy_read_{}", index, span = slot.span()),
|
||||
subpat: None,
|
||||
},
|
||||
marker,
|
||||
})
|
||||
})
|
||||
.collect::<syn::Result<_>>()?;
|
||||
Ok((element.clone(), attribute_reads))
|
||||
}
|
||||
|
||||
/// Parses a `(value, reads..): (T, Attr<..>..)` parameter: the value component
|
||||
/// is an ordinary field of the value type, each `Attr` component a read bound
|
||||
/// to this input's wire.
|
||||
fn parse_read_tuple(pat_tuple: &syn::PatTuple, ty: &Type, attrs: &[Attribute], index: usize) -> syn::Result<ParsedField> {
|
||||
let spelling = "an input with attribute reads destructures as `(value, Attr<..>)` over `(T, Attr<..>)`";
|
||||
let Type::Tuple(ty_tuple) = ty else {
|
||||
return Err(Error::new_spanned(ty, spelling));
|
||||
};
|
||||
if pat_tuple.elems.len() != ty_tuple.elems.len() || ty_tuple.elems.len() < 2 {
|
||||
return Err(Error::new_spanned(pat_tuple, spelling));
|
||||
}
|
||||
let mut slots = pat_tuple.elems.iter().zip(ty_tuple.elems.iter());
|
||||
let (value_pat, value_ty) = slots.next().expect("length checked above");
|
||||
if attr_marker(value_ty).is_some() {
|
||||
return Err(Error::new_spanned(value_ty, spelling));
|
||||
}
|
||||
let value_ident = match value_pat {
|
||||
Pat::Ident(pat_ident) => pat_ident.clone(),
|
||||
Pat::Wild(wild) => PatIdent {
|
||||
attrs: wild.attrs.clone(),
|
||||
by_ref: None,
|
||||
mutability: None,
|
||||
ident: format_ident!("_value{}", index, span = wild.underscore_token.span),
|
||||
subpat: None,
|
||||
},
|
||||
_ => return Err(Error::new_spanned(value_pat, "Expected a simple identifier for the value component")),
|
||||
};
|
||||
let attribute_reads: Vec<AttributeRead> = slots
|
||||
.map(|(pat, ty)| {
|
||||
let marker = attr_marker(ty).ok_or_else(|| Error::new_spanned(ty, spelling))?;
|
||||
let Pat::Ident(pat_ident) = pat else {
|
||||
return Err(Error::new_spanned(pat, "Expected a simple identifier for the attribute read"));
|
||||
};
|
||||
Ok(AttributeRead {
|
||||
pat_ident: pat_ident.clone(),
|
||||
marker,
|
||||
})
|
||||
})
|
||||
.collect::<syn::Result<_>>()?;
|
||||
let mut field = parse_field(value_ident.clone(), value_ty.clone(), attrs).map_err(|e| Error::new_spanned(&value_ident, format!("Failed to parse argument '{}': {}", value_ident.ident, e)))?;
|
||||
field.attribute_reads = attribute_reads;
|
||||
Ok(field)
|
||||
}
|
||||
|
||||
/// Parse context feature identifiers from the trait bounds of a context parameter.
|
||||
fn parse_context_feature_idents(ty: &Type) -> Vec<Ident> {
|
||||
let mut features = Vec::new();
|
||||
@@ -969,7 +723,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
let value_source = match (default_value, scope) {
|
||||
(Some(_), Some(_)) => return Err(Error::new_spanned(&pat_ident, "Cannot have both `default` and `scope` attributes")),
|
||||
(Some(default_value), _) => ParsedValueSource::Default(default_value),
|
||||
(_, Some(scope)) => ParsedValueSource::Scope(Box::new(scope)),
|
||||
(_, Some(scope)) => ParsedValueSource::Scope(scope),
|
||||
_ => ParsedValueSource::None,
|
||||
};
|
||||
|
||||
@@ -1062,7 +816,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
|
||||
let (output_type, attribute_reads) = split_lazy_reads(output_type)?;
|
||||
Ok(ParsedField {
|
||||
pat_ident,
|
||||
ty: ParsedFieldType::Node(NodeParsedField {
|
||||
@@ -1077,7 +830,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
number_step,
|
||||
unit,
|
||||
is_data_field,
|
||||
attribute_reads,
|
||||
})
|
||||
} else {
|
||||
let implementations = extract_attribute(attrs, "implementations")
|
||||
@@ -1085,11 +837,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
|
||||
let (ty, lend) = match ty {
|
||||
Type::Reference(reference) => ((*reference.elem).clone(), Some(reference)),
|
||||
ty => (ty, None),
|
||||
};
|
||||
|
||||
// Error if a float literal is given for a bound on an integer-typed field
|
||||
if is_integer_type(&ty) {
|
||||
let bound_attrs = [
|
||||
@@ -1122,7 +869,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
number_hard_max,
|
||||
number_mode_range,
|
||||
ty,
|
||||
lend,
|
||||
value_source,
|
||||
implementations,
|
||||
gpu_image,
|
||||
@@ -1134,7 +880,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
number_step,
|
||||
unit,
|
||||
is_data_field,
|
||||
attribute_reads: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1186,10 +931,6 @@ pub fn new_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<TokenS
|
||||
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}")))?;
|
||||
parsed_node.replace_impl_trait_in_input();
|
||||
if parsed_node.injects_async_source_fields() {
|
||||
let core_types = crate_ident.gcore()?.clone();
|
||||
parsed_node.inject_async_source_fields(&core_types);
|
||||
}
|
||||
crate::validation::validate_node_fn(&parsed_node).map_err(|e| Error::new(e.span(), format!("Validation error:\n{e}")))?;
|
||||
generate_node_code(&crate_ident, &parsed_node).map_err(|e| Error::new(e.span(), format!("Failed to generate node code:\n{e}")))
|
||||
}
|
||||
@@ -1217,49 +958,6 @@ impl ParsedNodeFn {
|
||||
self.input.pat_ident.ident = Ident::new("__ctx", self.input.pat_ident.ident.span());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn injects_async_source_fields(&self) -> bool {
|
||||
self.is_async || crate::codegen::is_source_kernel(&self.output_type)
|
||||
}
|
||||
|
||||
pub fn inject_async_source_fields(&mut self, core_types: &TokenStream2) {
|
||||
let hidden_field = |name: &str, ty: Type, value_source: ParsedValueSource| ParsedField {
|
||||
pat_ident: PatIdent {
|
||||
attrs: Vec::new(),
|
||||
by_ref: None,
|
||||
mutability: None,
|
||||
ident: Ident::new(name, proc_macro2::Span::call_site()),
|
||||
subpat: None,
|
||||
},
|
||||
name: None,
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::Hidden,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty,
|
||||
lend: None,
|
||||
exposed: false,
|
||||
value_source,
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
number_hard_max: None,
|
||||
number_mode_range: false,
|
||||
implementations: Default::default(),
|
||||
gpu_image: false,
|
||||
}),
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
is_data_field: false,
|
||||
attribute_reads: Vec::new(),
|
||||
};
|
||||
self.fields.push(hidden_field(
|
||||
"_runtime",
|
||||
parse_quote!(#core_types::runtime::RuntimeHandle),
|
||||
ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::runtime::RuntimeNode"))),
|
||||
));
|
||||
self.fields.push(hidden_field("_source", parse_quote!(#core_types::SourceId), ParsedValueSource::SourceId));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1384,11 +1082,6 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
},
|
||||
fn_name: Ident::new("add", Span::call_site()),
|
||||
struct_name: Ident::new("Add", Span::call_site()),
|
||||
@@ -1409,7 +1102,6 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1425,7 +1117,6 @@ mod tests {
|
||||
number_step: None,
|
||||
unit: None,
|
||||
is_data_field: false,
|
||||
attribute_reads: Vec::new(),
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::from("Multi\nLine\n"),
|
||||
@@ -1461,11 +1152,6 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
},
|
||||
fn_name: Ident::new("transform", Span::call_site()),
|
||||
struct_name: Ident::new("Transform", Span::call_site()),
|
||||
@@ -1495,7 +1181,6 @@ mod tests {
|
||||
number_step: None,
|
||||
unit: None,
|
||||
is_data_field: false,
|
||||
attribute_reads: Vec::new(),
|
||||
},
|
||||
ParsedField {
|
||||
pat_ident: pat_ident("translate"),
|
||||
@@ -1503,7 +1188,6 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(DVec2),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1519,7 +1203,6 @@ mod tests {
|
||||
number_step: None,
|
||||
unit: None,
|
||||
is_data_field: false,
|
||||
attribute_reads: Vec::new(),
|
||||
},
|
||||
],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1553,11 +1236,6 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
},
|
||||
fn_name: Ident::new("circle", Span::call_site()),
|
||||
struct_name: Ident::new("Circle", Span::call_site()),
|
||||
@@ -1578,7 +1256,6 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::Default(quote!(50.)),
|
||||
@@ -1594,7 +1271,6 @@ mod tests {
|
||||
number_step: None,
|
||||
unit: None,
|
||||
is_data_field: false,
|
||||
attribute_reads: Vec::new(),
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: "Test\n".into(),
|
||||
@@ -1626,11 +1302,6 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
},
|
||||
fn_name: Ident::new("levels", Span::call_site()),
|
||||
struct_name: Ident::new("Levels", Span::call_site()),
|
||||
@@ -1651,7 +1322,6 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1672,7 +1342,6 @@ mod tests {
|
||||
number_step: None,
|
||||
unit: None,
|
||||
is_data_field: false,
|
||||
attribute_reads: Vec::new(),
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::new(),
|
||||
@@ -1711,11 +1380,6 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
},
|
||||
fn_name: Ident::new("add", Span::call_site()),
|
||||
struct_name: Ident::new("Add", Span::call_site()),
|
||||
@@ -1736,7 +1400,6 @@ mod tests {
|
||||
description: String::from("b"),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1752,7 +1415,6 @@ mod tests {
|
||||
number_step: None,
|
||||
unit: None,
|
||||
is_data_field: false,
|
||||
attribute_reads: Vec::new(),
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::new(),
|
||||
@@ -1799,11 +1461,6 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
},
|
||||
fn_name: Ident::new("load_image", Span::call_site()),
|
||||
struct_name: Ident::new("LoadImage", Span::call_site()),
|
||||
@@ -1824,7 +1481,6 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(String),
|
||||
exposed: true,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1840,7 +1496,6 @@ mod tests {
|
||||
number_step: None,
|
||||
unit: None,
|
||||
is_data_field: false,
|
||||
attribute_reads: Vec::new(),
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
description: String::new(),
|
||||
@@ -1872,11 +1527,6 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
plain: false,
|
||||
},
|
||||
fn_name: Ident::new("custom_node", Span::call_site()),
|
||||
struct_name: Ident::new("CustomNode", Span::call_site()),
|
||||
|
||||
@@ -146,7 +146,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
ParamType::Uniform => quote!(uniform.#ident),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let context = quote!(&());
|
||||
let context = quote!(());
|
||||
|
||||
let entry_point_mod = &self.entry_point_mod;
|
||||
let entry_point_name = &self.entry_point_name_ident;
|
||||
@@ -231,10 +231,9 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
description: "".to_string(),
|
||||
widget_override: Default::default(),
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
|
||||
lend: None,
|
||||
ty: parse_quote!(&'a WgpuExecutor),
|
||||
exposed: true,
|
||||
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode"))),
|
||||
value_source: ParsedValueSource::Scope(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode")),
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
@@ -247,7 +246,6 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
number_step: None,
|
||||
unit: None,
|
||||
is_data_field: false,
|
||||
attribute_reads: Vec::new(),
|
||||
});
|
||||
|
||||
// find exactly one gpu_image field, runtime doesn't support more than 1 atm
|
||||
@@ -289,7 +287,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
wgsl_shader: crate::WGSL_SHADER,
|
||||
fragment_shader_name: super::#entry_point_name,
|
||||
has_uniform: #has_uniform,
|
||||
}, #gpu_image, #uniform_buffer)
|
||||
}, #gpu_image, #uniform_buffer).await
|
||||
}
|
||||
};
|
||||
|
||||
@@ -307,7 +305,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
fn_name: self.shader_node_mod.clone(),
|
||||
struct_name: format_ident!("{}", self.shader_node_mod.to_string().to_case(Case::Pascal)),
|
||||
mod_name: self.shader_node_mod.clone(),
|
||||
fn_generics: Vec::new(),
|
||||
fn_generics: vec![parse_quote!('a: 'n)],
|
||||
where_clause: None,
|
||||
input: Input {
|
||||
pat_ident: self.parsed.input.pat_ident.clone(),
|
||||
@@ -316,7 +314,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
context_features: self.parsed.input.context_features.clone(),
|
||||
},
|
||||
output_type: raster_gpu,
|
||||
is_async: false,
|
||||
is_async: true,
|
||||
fields,
|
||||
body,
|
||||
description: self.parsed.description.clone(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::parsing::{Implementation, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, attr_marker, record_writes, remove_attr_marker};
|
||||
use crate::parsing::{Implementation, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField};
|
||||
use proc_macro_error2::emit_error;
|
||||
use quote::{ToTokens, quote};
|
||||
use quote::quote;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{GenericParam, Type};
|
||||
|
||||
@@ -11,10 +11,6 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
validate_primary_input_expose,
|
||||
validate_min_max,
|
||||
validate_range_slider_bounds,
|
||||
validate_async_source,
|
||||
validate_lend_fields,
|
||||
validate_record_io,
|
||||
validate_lazy_reads,
|
||||
];
|
||||
|
||||
for validator in validators {
|
||||
@@ -24,256 +20,6 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_record_io(parsed: &ParsedNodeFn) {
|
||||
let value = crate::codegen::slot_value_type(&parsed.output_type);
|
||||
if let Type::Tuple(tuple) = &value {
|
||||
let has_marker_slot = tuple.elems.iter().any(|slot| attr_marker(slot).is_some() || remove_attr_marker(slot).is_some());
|
||||
if has_marker_slot && record_writes(&value).is_none() {
|
||||
emit_error!(
|
||||
parsed.output_type.span(),
|
||||
"a record return tuple is the element first, then only `Attr<..>` writes and `RemoveAttr<..>` deletions"
|
||||
);
|
||||
}
|
||||
} else if attr_marker(&value).is_some() || remove_attr_marker(&value).is_some() {
|
||||
emit_error!(parsed.output_type.span(), "an attribute write needs an element in the first tuple slot, e.g. `(T, Attr<..>)`");
|
||||
}
|
||||
|
||||
let writes = record_writes(&value);
|
||||
let has_reads = parsed
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
|
||||
if !has_reads && writes.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
if parsed.is_async || crate::codegen::is_source_kernel(&parsed.output_type) {
|
||||
emit_error!(parsed.output_type.span(), "attribute io is not supported on async source kernels");
|
||||
}
|
||||
if crate::codegen::is_poll_kernel(&parsed.output_type) {
|
||||
emit_error!(parsed.output_type.span(), "attribute io needs a plain or `Result<_, Interrupt>` kernel, not a `GPoll` one");
|
||||
}
|
||||
|
||||
for field in parsed.fields.iter().skip(1) {
|
||||
if matches!(field.ty, ParsedFieldType::Node(_)) {
|
||||
emit_error!(field.pat_ident.span(), "record nodes take no lazy inputs yet");
|
||||
}
|
||||
}
|
||||
for (index, field) in parsed.fields.iter().enumerate() {
|
||||
if field.attribute_reads.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if field.is_data_field {
|
||||
emit_error!(field.pat_ident.span(), "a `#[data]` field has no wire to read attributes from");
|
||||
continue;
|
||||
}
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. }) => {
|
||||
emit_error!(field.pat_ident.span(), "attribute reads need an owned value; take `T` instead of `&T`");
|
||||
}
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => {
|
||||
if matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty()) {
|
||||
emit_error!(field.pat_ident.span(), "attribute-only inputs are not supported yet; the value component cannot be `()`");
|
||||
}
|
||||
let is_token_carrier = index == 0 && implementations.is_empty() && crate::codegen::unbounded_generic(parsed, ty).is_some();
|
||||
if !is_token_carrier && crate::codegen::contains_open_generic(parsed, ty) {
|
||||
emit_error!(
|
||||
field.pat_ident.span(),
|
||||
"a reading input's value is monomorphic for now; use a concrete type or an unbounded passthrough generic in the primary input"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Lazy-input reads are validated by `validate_lazy_reads`; a
|
||||
// record-io node already rejects lazy inputs above.
|
||||
ParsedFieldType::Node(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(carrier) = parsed.fields.first() else {
|
||||
emit_error!(
|
||||
parsed.fn_name.span(),
|
||||
"attribute io needs a primary input as the first parameter after the context (`_: ()` for none)"
|
||||
);
|
||||
return;
|
||||
};
|
||||
let carrier_ty = match &carrier.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: None, .. }) if !carrier.is_data_field => Some(ty),
|
||||
_ => None,
|
||||
};
|
||||
let Some(carrier_ty) = carrier_ty else {
|
||||
emit_error!(
|
||||
carrier.pat_ident.span(),
|
||||
"a record node's primary input is an owned element, an unbounded passthrough generic, or `_: ()`; not `#[data]`, `&T`, or `impl Node`"
|
||||
);
|
||||
return;
|
||||
};
|
||||
|
||||
let no_carrier = matches!(carrier_ty, Type::Tuple(tuple) if tuple.elems.is_empty());
|
||||
let token = match (no_carrier, &carrier.ty) {
|
||||
(false, ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. })) if implementations.is_empty() => crate::codegen::unbounded_generic(parsed, ty),
|
||||
_ => None,
|
||||
};
|
||||
let element = writes.as_ref().map(|writes| &writes.element).unwrap_or(&value);
|
||||
match &token {
|
||||
Some(token) => {
|
||||
if !matches!(crate::codegen::bare_ident(element), Some(ident) if ident == token) {
|
||||
emit_error!(
|
||||
parsed.output_type.span(),
|
||||
"a generic element passes through unchanged: return `{}` in the first tuple position",
|
||||
token
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(ident) = crate::codegen::unbounded_generic(parsed, element) {
|
||||
emit_error!(parsed.output_type.span(), "the returned generic element `{}` has no matching input", ident);
|
||||
} else if !no_carrier && crate::codegen::contains_open_generic(parsed, carrier_ty) {
|
||||
emit_error!(
|
||||
carrier.pat_ident.span(),
|
||||
"record element reads are monomorphic for now; use a concrete element type or an unbounded passthrough generic"
|
||||
);
|
||||
} else if crate::codegen::contains_open_generic(parsed, element) {
|
||||
emit_error!(parsed.output_type.span(), "a written element must be a concrete type");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for field in &parsed.fields {
|
||||
let mut seen_reads: Vec<String> = Vec::new();
|
||||
for read in &field.attribute_reads {
|
||||
let marker = read.marker.to_token_stream().to_string();
|
||||
if seen_reads.contains(&marker) {
|
||||
emit_error!(read.pat_ident.span(), "attribute `{}` is read twice from `{}`", marker, field.pat_ident.ident);
|
||||
}
|
||||
seen_reads.push(marker);
|
||||
}
|
||||
}
|
||||
if let Some(writes) = &writes {
|
||||
let mut seen_writes: Vec<String> = Vec::new();
|
||||
for marker in &writes.markers {
|
||||
let written = marker.to_token_stream().to_string();
|
||||
if seen_writes.contains(&written) {
|
||||
emit_error!(parsed.output_type.span(), "attribute `{}` is written twice", written);
|
||||
}
|
||||
seen_writes.push(written);
|
||||
}
|
||||
let mut seen_removes: Vec<String> = Vec::new();
|
||||
for marker in &writes.removes {
|
||||
let removed = marker.to_token_stream().to_string();
|
||||
if seen_removes.contains(&removed) {
|
||||
emit_error!(parsed.output_type.span(), "attribute `{}` is removed twice", removed);
|
||||
}
|
||||
if seen_writes.contains(&removed) {
|
||||
emit_error!(parsed.output_type.span(), "attribute `{}` is both written and removed", removed);
|
||||
}
|
||||
seen_removes.push(removed);
|
||||
}
|
||||
if no_carrier && !writes.removes.is_empty() {
|
||||
emit_error!(parsed.output_type.span(), "a node without a primary input writes a fresh record; there is nothing to remove");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_lazy_reads(parsed: &ParsedNodeFn) {
|
||||
if !crate::codegen::has_lazy_reads(parsed) {
|
||||
return;
|
||||
}
|
||||
if !crate::codegen::record_flip(parsed) {
|
||||
emit_error!(
|
||||
parsed.fn_name.span(),
|
||||
"attribute reads on a lazy input need the record lowering; routing, `plain`, shader, batch, and non-row-assignable generic nodes keep the plain one"
|
||||
);
|
||||
}
|
||||
for field in &parsed.fields {
|
||||
let ParsedFieldType::Node(NodeParsedField { output_type, .. }) = &field.ty else {
|
||||
continue;
|
||||
};
|
||||
if field.attribute_reads.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if crate::codegen::unbounded_generic(parsed, output_type).is_some() {
|
||||
emit_error!(
|
||||
field.pat_ident.span(),
|
||||
"an unbounded generic source forwards its whole record; attribute reads need a concrete output type"
|
||||
);
|
||||
}
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
for read in &field.attribute_reads {
|
||||
let marker = read.marker.to_token_stream().to_string();
|
||||
if seen.contains(&marker) {
|
||||
emit_error!(read.marker.span(), "attribute `{}` is read twice from `{}`", marker, field.pat_ident.ident);
|
||||
}
|
||||
seen.push(marker);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_async_source(parsed: &ParsedNodeFn) {
|
||||
let snapshot_ctx = matches!(&parsed.input.ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "CtxSnapshot"));
|
||||
let future_kernel = crate::codegen::is_source_kernel(&parsed.output_type);
|
||||
if let Some(placeholder) = &parsed.attributes.placeholder
|
||||
&& !parsed.is_async
|
||||
&& !future_kernel
|
||||
{
|
||||
emit_error!(
|
||||
placeholder.span(),
|
||||
"`placeholder` applies only to async and source kernels; a synchronous node never reports `Partial`, so the stand-in is unused"
|
||||
);
|
||||
}
|
||||
if parsed.is_async && future_kernel {
|
||||
emit_error!(
|
||||
parsed.output_type.span(),
|
||||
"an `async fn` kernel already is the async part; returning `SourceFuture` is the sync-prologue form, so drop the `async` keyword or return the value directly"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if !parsed.is_async {
|
||||
if snapshot_ctx {
|
||||
emit_error!(
|
||||
parsed.input.pat_ident.span(),
|
||||
"`CtxSnapshot` is the async source context; synchronous nodes take `impl Ctx` and read through extract bounds"
|
||||
);
|
||||
}
|
||||
if !future_kernel {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if parsed.is_async {
|
||||
for field in &parsed.fields {
|
||||
if matches!(field.ty, ParsedFieldType::Node(_)) {
|
||||
emit_error!(
|
||||
field.pat_ident.span(),
|
||||
"`async fn` source nodes cannot take `impl Node` inputs: the spawned future outlives any borrow of the graph, so it cannot evaluate other nodes; use the sync-prologue form (return `SourceFuture`) to evaluate lazy inputs before spawning"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_lend_fields(parsed: &ParsedNodeFn) {
|
||||
let future_kernel = crate::codegen::is_source_kernel(&parsed.output_type);
|
||||
for field in &parsed.fields {
|
||||
let ParsedFieldType::Regular(RegularParsedField { lend: Some(reference), .. }) = &field.ty else {
|
||||
continue;
|
||||
};
|
||||
if let Some(mutability) = &reference.mutability {
|
||||
emit_error!(mutability.span(), "reference parameters are read-only lends; `&mut` is not supported");
|
||||
}
|
||||
if let Some(lifetime) = &reference.lifetime {
|
||||
emit_error!(lifetime.span(), "reference parameters use the eval lifetime implicitly; write a bare `&T`");
|
||||
}
|
||||
if field.is_data_field {
|
||||
emit_error!(field.pat_ident.span(), "`#[data]` fields are node-resident state and cannot be references");
|
||||
}
|
||||
if parsed.is_async || future_kernel {
|
||||
emit_error!(
|
||||
field.pat_ident.span(),
|
||||
"source kernels move their inputs into the spawned task, so they cannot take reference parameters"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_min_max(parsed: &ParsedNodeFn) {
|
||||
for field in &parsed.fields {
|
||||
if let ParsedField {
|
||||
@@ -392,18 +138,6 @@ fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
|
||||
|
||||
fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
|
||||
let has_skip_impl = parsed.attributes.skip_impl;
|
||||
let routing = crate::codegen::routing_io(parsed);
|
||||
let record_token = crate::codegen::record_shape(parsed).and_then(|shape| match shape.carrier {
|
||||
crate::codegen::RecordCarrier::Token(token) => Some(token),
|
||||
_ => None,
|
||||
});
|
||||
let opaque_record_generic = |ty: &Type| {
|
||||
let ident = match ty {
|
||||
Type::Path(path) => path.path.get_ident(),
|
||||
_ => None,
|
||||
};
|
||||
ident.is_some() && (ident == routing.as_ref().map(|routing| &routing.generic) || ident == record_token.as_ref())
|
||||
};
|
||||
|
||||
if !has_skip_impl && !parsed.fn_generics.is_empty() {
|
||||
for field in &parsed.fields {
|
||||
@@ -415,9 +149,6 @@ fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
|
||||
let pat_ident = &field.pat_ident;
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => {
|
||||
if opaque_record_generic(ty) {
|
||||
continue;
|
||||
}
|
||||
if contains_generic_param(ty, &parsed.fn_generics) && implementations.is_empty() {
|
||||
emit_error!(
|
||||
ty.span(),
|
||||
@@ -435,9 +166,6 @@ fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
|
||||
implementations,
|
||||
..
|
||||
}) => {
|
||||
if opaque_record_generic(output_type) {
|
||||
continue;
|
||||
}
|
||||
if (contains_generic_param(input_type, &parsed.fn_generics) || contains_generic_param(output_type, &parsed.fn_generics)) && implementations.is_empty() {
|
||||
emit_error!(
|
||||
pat_ident.span(),
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
use crate::brush_cache::BrushCache;
|
||||
use crate::brush_stroke::{BrushStroke, BrushStyle};
|
||||
use core_types::Ctx;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::color::{Alpha, Color, Pixel, Sample};
|
||||
use core_types::generic::FnNode;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::bbox::{AxisAlignedBbox, Bbox};
|
||||
use core_types::registry::FutureWrapperNode;
|
||||
use core_types::transform::Transform;
|
||||
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::{Ctx, Node};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_nodes::blending_nodes::blend_colors;
|
||||
use raster_nodes::std_nodes::{empty_image, extend_image_to_bounds};
|
||||
@@ -60,7 +63,7 @@ impl<P: Pixel + Alpha> Sample for BrushStampGenerator<P> {
|
||||
/// 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.
|
||||
#[node_macro::node(category(""), skip_impl)]
|
||||
fn brush_stamp_generator(_: impl Ctx, #[unit(" px")] diameter: f64, color: Color, hardness: f64, flow: f64) -> BrushStampGenerator<Color> {
|
||||
fn brush_stamp_generator(#[unit(" px")] diameter: f64, color: Color, hardness: f64, flow: f64) -> BrushStampGenerator<Color> {
|
||||
// Diameter
|
||||
let radius = diameter / 2.;
|
||||
|
||||
@@ -80,9 +83,9 @@ fn brush_stamp_generator(_: impl Ctx, #[unit(" px")] diameter: f64, color: Color
|
||||
|
||||
/// 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)]
|
||||
fn blit<BlendFn>(_: impl Ctx, mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>>
|
||||
fn blit<BlendFn>(mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>>
|
||||
where
|
||||
BlendFn: Fn(Color, Color) -> Color,
|
||||
BlendFn: for<'any_input> Node<'any_input, (Color, Color), Output = Color>,
|
||||
{
|
||||
if positions.is_empty() {
|
||||
return target;
|
||||
@@ -122,7 +125,7 @@ where
|
||||
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 dst_pixel = &mut element.data_mut().data[target_index(x + clamp_start.x, y + clamp_start.y)];
|
||||
*dst_pixel = blend_mode(src_pixel, *dst_pixel);
|
||||
*dst_pixel = blend_mode.eval((src_pixel, *dst_pixel));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,10 +134,10 @@ where
|
||||
target
|
||||
}
|
||||
|
||||
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);
|
||||
pub async 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 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.));
|
||||
|
||||
image.into_element()
|
||||
@@ -185,7 +188,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.
|
||||
/// If an input image is supplied, strokes are drawn on top of it, expanding bounds as needed.
|
||||
#[node_macro::node(category("Raster"))]
|
||||
fn brush(
|
||||
async fn brush(
|
||||
_: impl Ctx,
|
||||
/// Optional raster content that may be drawn onto.
|
||||
mut background: List<Raster<CPU>>,
|
||||
@@ -221,7 +224,7 @@ fn brush(
|
||||
let mut brush_plan = cache.compute_brush_plan(list_item, &draw_strokes);
|
||||
|
||||
// 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();
|
||||
};
|
||||
|
||||
@@ -231,7 +234,7 @@ fn brush(
|
||||
// TODO: apply rotation from layer to stamp for non-rotationally-symmetric brushes.
|
||||
let mut brush_texture = cache.get_cached_brush(&stroke.style);
|
||||
if brush_texture.is_none() {
|
||||
let tex = create_brush_texture(&stroke.style);
|
||||
let tex = create_brush_texture(&stroke.style).await;
|
||||
cache.store_brush(stroke.style.clone(), tex.clone());
|
||||
brush_texture = Some(tex);
|
||||
}
|
||||
@@ -252,14 +255,21 @@ fn brush(
|
||||
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 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 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 {
|
||||
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(&(), blit_target, brush_texture, positions, |a, b| blend_colors(a, b, BlendMode::Normal, 1.));
|
||||
let list = blit_node.eval(blit_target).await;
|
||||
assert_eq!(list.len(), 1);
|
||||
list.into_iter().next().unwrap_or_default()
|
||||
};
|
||||
@@ -281,7 +291,7 @@ fn brush(
|
||||
for stroke in trace.into_iter().map(|row| row.into_element()) {
|
||||
let mut brush_texture = cache.get_cached_brush(&stroke.style);
|
||||
if brush_texture.is_none() {
|
||||
let tex = create_brush_texture(&stroke.style);
|
||||
let tex = create_brush_texture(&stroke.style).await;
|
||||
cache.store_brush(stroke.style.clone(), tex.clone());
|
||||
brush_texture = Some(tex);
|
||||
}
|
||||
@@ -295,15 +305,17 @@ fn brush(
|
||||
_ => BlendMode::Restore,
|
||||
};
|
||||
|
||||
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.)
|
||||
})
|
||||
.into_iter()
|
||||
.next()
|
||||
.unwrap_or_default();
|
||||
let blend_params = FnNode::new(move |(a, b)| blend_colors(a, b, mask_blend_mode, 1.));
|
||||
let blit_node = BlitNode::new(
|
||||
FutureWrapperNode::new(ClonedNode::new(brush_texture)),
|
||||
FutureWrapperNode::new(ClonedNode::new(positions)),
|
||||
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();
|
||||
}
|
||||
|
||||
actual_image = blend_image_closure(erase_restore_mask, actual_image, |a, b| blend_colors(a, b, BlendMode::MultiplyAlpha, 1.));
|
||||
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_params.eval((a, b)));
|
||||
}
|
||||
|
||||
let transform: DAffine2 = actual_image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
@@ -398,16 +410,16 @@ mod test {
|
||||
#[test]
|
||||
fn test_brush_texture() {
|
||||
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.)));
|
||||
// center pixel should be BLACK
|
||||
assert_eq!(image.sample(DVec2::splat(0.), DVec2::ONE), Some(Color::BLACK));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_brush_output_size() {
|
||||
#[tokio::test]
|
||||
async fn test_brush_output_size() {
|
||||
let image = brush(
|
||||
&(),
|
||||
(),
|
||||
&BrushCache::default(),
|
||||
List::new_from_element(Raster::new_cpu(Image::<Color>::default())),
|
||||
List::new_from_element(BrushStroke {
|
||||
@@ -421,7 +433,8 @@ mod test {
|
||||
blend_mode: BlendMode::Normal,
|
||||
},
|
||||
}),
|
||||
);
|
||||
)
|
||||
.await;
|
||||
assert_eq!(image.element(0).unwrap().width, 20);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::List;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{CacheHash, Color, Context, Ctx, DeriveCtx, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
|
||||
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::vector_types::GradientStops;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
@@ -62,8 +61,8 @@ fn animation_time(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
fn quantize_real_time<T>(
|
||||
ctx: impl Ctx + ExtractRealTime + DeriveCtx,
|
||||
async fn quantize_real_time<T>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs,
|
||||
#[implementations(
|
||||
Context -> bool,
|
||||
Context -> u32,
|
||||
@@ -85,11 +84,11 @@ fn quantize_real_time<T>(
|
||||
Context -> List<f64>,
|
||||
Context -> (),
|
||||
)]
|
||||
value: impl Node<Context<'_>, Output = T>,
|
||||
value: impl Node<'n, Context<'static>, Output = T>,
|
||||
#[default(1)]
|
||||
#[unit("sec")]
|
||||
quantum: f64,
|
||||
) -> GPoll<T> {
|
||||
) -> T {
|
||||
let time = ctx.try_real_time().unwrap_or_default();
|
||||
let time = time / 1000.;
|
||||
let mut quantized_time = (time * quantum.recip()).round() / quantum.recip();
|
||||
@@ -97,13 +96,13 @@ fn quantize_real_time<T>(
|
||||
quantized_time = time;
|
||||
}
|
||||
let quantized_time = quantized_time * 1000.;
|
||||
let scope = ctx.scope().with_real_time(Some(quantized_time));
|
||||
value.eval(&ctx.with_scope(&scope))
|
||||
let new_context = OwnedContextImpl::from(ctx).with_real_time(quantized_time);
|
||||
value.eval(Some(new_context.into())).await
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
fn quantize_animation_time<T>(
|
||||
ctx: impl Ctx + ExtractAnimationTime + DeriveCtx,
|
||||
async fn quantize_animation_time<T>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs,
|
||||
#[implementations(
|
||||
Context -> bool,
|
||||
Context -> u32,
|
||||
@@ -125,18 +124,18 @@ fn quantize_animation_time<T>(
|
||||
Context -> List<f64>,
|
||||
Context -> (),
|
||||
)]
|
||||
value: impl Node<Context<'_>, Output = T>,
|
||||
value: impl Node<'n, Context<'static>, Output = T>,
|
||||
#[default(1)]
|
||||
#[unit("sec")]
|
||||
quantum: f64,
|
||||
) -> GPoll<T> {
|
||||
) -> T {
|
||||
let time = ctx.try_animation_time().unwrap_or_default();
|
||||
let mut quantized_time = (time * quantum.recip()).round() / quantum.recip();
|
||||
if !quantized_time.is_finite() {
|
||||
quantized_time = time;
|
||||
}
|
||||
let scope = ctx.scope().with_animation_time(Some(quantized_time));
|
||||
value.eval(&ctx.with_scope(&scope))
|
||||
let new_context = OwnedContextImpl::from(ctx).with_animation_time(quantized_time);
|
||||
value.eval(Some(new_context.into())).await
|
||||
}
|
||||
|
||||
/// Produces the current position of the user's pointer within the document canvas.
|
||||
|
||||
@@ -47,7 +47,7 @@ fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> List<GradientStops> {
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Context"), path(core_types::vector))]
|
||||
fn read_position(
|
||||
async fn read_position(
|
||||
ctx: impl Ctx + ExtractPosition,
|
||||
_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.
|
||||
@@ -64,7 +64,7 @@ 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.
|
||||
#[node_macro::node(category("Context"), path(core_types::vector))]
|
||||
fn read_index(
|
||||
async fn read_index(
|
||||
ctx: impl Ctx + ExtractIndex,
|
||||
_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.
|
||||
|
||||
@@ -1,16 +1,120 @@
|
||||
use core_types::context::{Context, ContextModification, Ctx, DeriveCtx};
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core::f64;
|
||||
use core_types::context::{CloneVarArgs, Context, ContextFeatures, Ctx, ExtractAll};
|
||||
use core_types::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{Color, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::vector_types::GradientStops;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
|
||||
/// Filters out what should be unused components of the context based on the specified requirements.
|
||||
/// This node is inserted by the compiler to "zero out" unused context components.
|
||||
#[node_macro::node(category(""))]
|
||||
fn context_modification<T>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
async fn context_modification<T>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
/// The data to pass through, evaluated with the stripped down context.
|
||||
value: impl Node<Context<'_>, Output = T>,
|
||||
#[implementations(
|
||||
Context -> (),
|
||||
Context -> bool,
|
||||
Context -> u32,
|
||||
Context -> u64,
|
||||
Context -> f32,
|
||||
Context -> f64,
|
||||
Context -> String,
|
||||
Context -> DAffine2,
|
||||
Context -> Footprint,
|
||||
Context -> DVec2,
|
||||
Context -> List<String>,
|
||||
Context -> List<NodeId>,
|
||||
Context -> List<f64>,
|
||||
Context -> List<u8>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Artboard>,
|
||||
Context -> List<GradientStops>,
|
||||
Context -> AttributeDyn,
|
||||
Context -> AttributeValueDyn,
|
||||
Context -> ListDyn,
|
||||
)]
|
||||
value: impl Node<Context<'static>, Output = T>,
|
||||
/// The parts of the context to keep when evaluating the input value. All other parts are nullified.
|
||||
modification: ContextModification,
|
||||
) -> Result<T, Interrupt> {
|
||||
let scope = ctx.scope().nullified(modification.features, Some(modification.sources()));
|
||||
value.eval(&ctx.nullified(modification.features, &scope))
|
||||
features_to_keep: ContextFeatures,
|
||||
) -> T {
|
||||
let new_context = OwnedContextImpl::from_flags(ctx, features_to_keep);
|
||||
|
||||
value.eval(Some(new_context.into())).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::transform::Footprint;
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::hash::Hasher;
|
||||
|
||||
/// Verifies that nullified context fields don't affect the cache hash — only the kept features matter.
|
||||
#[test]
|
||||
fn test_nullified_context_hash_stability() {
|
||||
use core_types::Context;
|
||||
use std::sync::Arc;
|
||||
|
||||
let original_ctx: Context = Some(Arc::new(
|
||||
OwnedContextImpl::empty()
|
||||
.with_footprint(Footprint::default())
|
||||
.with_index(1)
|
||||
.with_real_time(10.5)
|
||||
.with_vararg(Box::new("test"))
|
||||
.with_animation_time(20.25),
|
||||
));
|
||||
|
||||
// A second context with different values for the nullified fields
|
||||
let changed_ctx: Context = Some(Arc::new(
|
||||
OwnedContextImpl::empty()
|
||||
.with_footprint(Footprint::default())
|
||||
.with_index(2)
|
||||
.with_real_time(999.9)
|
||||
.with_vararg(Box::new("test"))
|
||||
.with_animation_time(888.8),
|
||||
));
|
||||
|
||||
// Nullify everything — both should hash the same regardless of their field values
|
||||
let features_to_keep = ContextFeatures::empty();
|
||||
let nullified1 = OwnedContextImpl::from_flags(original_ctx.clone().unwrap(), features_to_keep);
|
||||
let nullified2 = OwnedContextImpl::from_flags(changed_ctx.clone().unwrap(), features_to_keep);
|
||||
|
||||
let mut hasher1 = DefaultHasher::new();
|
||||
nullified1.cache_hash(&mut hasher1);
|
||||
|
||||
let mut hasher2 = DefaultHasher::new();
|
||||
nullified2.cache_hash(&mut hasher2);
|
||||
|
||||
assert_eq!(
|
||||
hasher1.finish(),
|
||||
hasher2.finish(),
|
||||
"Hash of nullified context should remain stable regardless of input changes when features are nullified"
|
||||
);
|
||||
|
||||
// Keep only footprint and varargs — both have the same footprint and vararg, so hash should still match
|
||||
let partial_features = ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS;
|
||||
let partial1 = OwnedContextImpl::from_flags(original_ctx.clone().unwrap(), partial_features);
|
||||
let partial2 = OwnedContextImpl::from_flags(changed_ctx.clone().unwrap(), partial_features);
|
||||
|
||||
let mut hasher3 = DefaultHasher::new();
|
||||
partial1.cache_hash(&mut hasher3);
|
||||
|
||||
let mut hasher4 = DefaultHasher::new();
|
||||
partial2.cache_hash(&mut hasher4);
|
||||
|
||||
assert_eq!(
|
||||
hasher3.finish(),
|
||||
hasher4.finish(),
|
||||
"Hash should be stable when keeping only footprint and varargs and their values are the same"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -29,8 +29,8 @@ fn unwrap_option<T: Default>(_: impl Ctx, #[implementations(Option<f64>, Option<
|
||||
input.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Clones the element out of its record wire.
|
||||
/// Meant for debugging purposes, not general use. Clones the input value.
|
||||
#[node_macro::node(category("Debug"))]
|
||||
fn clone<T: Clone>(_: impl Ctx, #[implementations(List<Raster<CPU>>)] value: &T) -> T {
|
||||
fn clone<'i, T: Clone + 'i>(_: impl Ctx, #[implementations(&List<Raster<CPU>>)] value: &'i T) -> T {
|
||||
value.clone()
|
||||
}
|
||||
@@ -5,8 +5,6 @@ pub mod debug;
|
||||
pub mod extract_xy;
|
||||
pub mod memo;
|
||||
pub mod ops;
|
||||
#[cfg(test)]
|
||||
mod record;
|
||||
|
||||
// Re-export all nodes
|
||||
pub use animation::*;
|
||||
|
||||
@@ -1,287 +1,54 @@
|
||||
use core_types::arena::ArenaCell;
|
||||
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll, ExtractArena};
|
||||
use core_types::frame_table::{FrameTable, Lookup};
|
||||
use core_types::gpoll::{Extent, Finality, GPoll};
|
||||
use core_types::WasmNotSend;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::memo::IORecord;
|
||||
use core_types::node::Node;
|
||||
use core_types::record::{OwnedRecord, RecordCapture, RecordValue, copy_record_bytes, record_from_bytes};
|
||||
use core_types::registry::cache_key;
|
||||
use core_types::memo::*;
|
||||
use std::hash::DefaultHasher;
|
||||
use std::hash::Hasher;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Helps speed up repeated renders in a computationally-heavy part of the node graph.
|
||||
///
|
||||
/// Stores a deep copy of the last record that flowed through this node and replays it on subsequent renders if the context has not changed.
|
||||
#[node_macro::node(category("General"), path(graphene_core::memo), extent(memoize_extent))]
|
||||
fn memoize<'e>(
|
||||
ctx: impl Ctx + CacheHash + ExtractArena<'e>,
|
||||
#[data] cache: Arc<Mutex<Option<(u64, OwnedRecord, Finality)>>>,
|
||||
content: impl Node<Context<'_>, Output = RecordValue<'e>>,
|
||||
) -> GPoll<RecordValue<'e>> {
|
||||
let key = cache_key(&ctx);
|
||||
if let Some((hash, copy, finality)) = cache.lock().unwrap().as_ref()
|
||||
&& *hash == key
|
||||
{
|
||||
return match copy.replay(content.layout(), ctx.arena()) {
|
||||
Some(value) => match finality {
|
||||
Finality::AllFinal => GPoll::Final(value),
|
||||
Finality::Partial => GPoll::Partial(value),
|
||||
},
|
||||
None => GPoll::arena_exhausted(),
|
||||
};
|
||||
/// 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)]
|
||||
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 {
|
||||
// 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 hit occurs when the Option is Some and has a stored hash matching the hash of the call argument. In this case, the node returns the cached value without re-evaluating the inner node.
|
||||
//
|
||||
// Currently, only one input-output pair is cached. Subsequent calls with different inputs will overwrite the previous cache.
|
||||
|
||||
let mut hasher = DefaultHasher::new();
|
||||
input.cache_hash(&mut hasher);
|
||||
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())) {
|
||||
return data;
|
||||
}
|
||||
let result = content.eval(&ctx);
|
||||
let publishable = match &result {
|
||||
GPoll::Final(value) => Some((value, Finality::AllFinal)),
|
||||
GPoll::Partial(value) => Some((value, Finality::Partial)),
|
||||
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => None,
|
||||
};
|
||||
if let Some((value, finality)) = publishable {
|
||||
// SAFETY: the value came from this edge, so it carries the edge's layout.
|
||||
let copy = unsafe { OwnedRecord::copy_out(content.layout(), content.layout().rec(value)) };
|
||||
*cache.lock().unwrap() = Some((key, copy, finality));
|
||||
}
|
||||
result
|
||||
|
||||
let value = content.eval(input).await;
|
||||
*cache.lock().unwrap() = Some((hash, value.clone()));
|
||||
value
|
||||
}
|
||||
|
||||
fn memoize_extent<C, NodeContent>(node: &MemoizeNode<NodeContent>, ctx: &C) -> GPoll<Extent>
|
||||
where
|
||||
NodeContent: Node<C>,
|
||||
{
|
||||
node.content.extent(ctx)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), extent(frame_memo_extent))]
|
||||
fn frame_memo<'e>(
|
||||
ctx: impl Ctx + CacheHash + ExtractArena<'e>,
|
||||
#[data] cell: ArenaCell<FrameTable<Box<[u8]>, 32>>,
|
||||
content: impl Node<Context<'_>, Output = RecordValue<'e>>,
|
||||
) -> GPoll<RecordValue<'e>> {
|
||||
let arena = ctx.arena();
|
||||
let table = match cell.load(arena) {
|
||||
Some(table) => table,
|
||||
None => match arena.alloc(FrameTable::new()) {
|
||||
Some((table, weak)) => {
|
||||
cell.store(weak);
|
||||
table
|
||||
}
|
||||
None => return content.eval(&ctx),
|
||||
},
|
||||
};
|
||||
// SAFETY: published bytes are same-frame copies of this edge's records,
|
||||
// so they carry the edge's layout with live parked references.
|
||||
let revive = |bytes: &'e Box<[u8]>| unsafe { record_from_bytes(content.layout(), bytes) };
|
||||
match table.lookup(cache_key(ctx)) {
|
||||
Lookup::Hit(Finality::AllFinal, bytes) => GPoll::Final(revive(bytes)),
|
||||
Lookup::Hit(Finality::Partial, bytes) => GPoll::Partial(revive(bytes)),
|
||||
Lookup::Vacant(slot) => match content.eval(&ctx) {
|
||||
GPoll::Final(value) => {
|
||||
// SAFETY: the value came from this edge, so it carries the edge's layout.
|
||||
let bytes = unsafe { copy_record_bytes(content.layout(), content.layout().rec(&value)) };
|
||||
GPoll::Final(revive(slot.publish(bytes, Finality::AllFinal)))
|
||||
}
|
||||
GPoll::Partial(value) => {
|
||||
// SAFETY: as above.
|
||||
let bytes = unsafe { copy_record_bytes(content.layout(), content.layout().rec(&value)) };
|
||||
GPoll::Partial(revive(slot.publish(bytes, Finality::Partial)))
|
||||
}
|
||||
unpublishable => {
|
||||
slot.release();
|
||||
unpublishable
|
||||
}
|
||||
},
|
||||
Lookup::Full => content.eval(&ctx),
|
||||
}
|
||||
}
|
||||
|
||||
fn frame_memo_extent<C, NodeContent>(node: &FrameMemoNode<NodeContent>, ctx: &C) -> GPoll<Extent>
|
||||
where
|
||||
NodeContent: Node<C>,
|
||||
{
|
||||
node.content.extent(ctx)
|
||||
}
|
||||
|
||||
type MonitorValue = Arc<Mutex<Option<IORecord<CtxSnapshot, RecordCapture>>>>;
|
||||
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.
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), properties("monitor_properties"))]
|
||||
fn monitor<'e>(ctx: impl Ctx + DeriveCtx + ExtractAll + ExtractArena<'e>, #[data] io: MonitorValue, content: impl Node<Context<'_>, Output = RecordValue<'e>>) -> GPoll<RecordValue<'e>> {
|
||||
let result = content.eval(&ctx);
|
||||
if let GPoll::Final(value) | GPoll::Partial(value) = &result {
|
||||
// SAFETY: the value came from this edge, so it carries the edge's layout.
|
||||
let captured = unsafe { RecordCapture::capture(content.layout(), content.layout().rec(value), ctx.arena()) };
|
||||
*io.lock().unwrap() = captured.map(|output| IORecord {
|
||||
input: CtxSnapshot::capture(ctx),
|
||||
output,
|
||||
});
|
||||
}
|
||||
result
|
||||
#[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>(
|
||||
input: I,
|
||||
#[allow(clippy::type_complexity)]
|
||||
#[data]
|
||||
io: MonitorValue<I, T>,
|
||||
content: impl Node<I, Output = T>,
|
||||
) -> T {
|
||||
let output = content.eval(input.clone()).await;
|
||||
*io.lock().unwrap() = Some(Arc::new(IORecord { input, output: output.clone() }));
|
||||
output
|
||||
}
|
||||
|
||||
fn serialize_monitor(io: &MonitorValue) -> 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>> {
|
||||
let io = io.lock().unwrap();
|
||||
io.as_ref().map(|io| Arc::new(io.clone()) as Arc<dyn std::any::Any + Send + Sync>)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::SourceId;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope};
|
||||
use core_types::registry::{EdgeHandle, ErasedNode, ErasedRecordNode};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
struct CountingNode(AtomicU32);
|
||||
|
||||
impl<Input> Node<Input> for CountingNode {
|
||||
type Output = u32;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<u32> {
|
||||
GPoll::Final(self.0.fetch_add(1, Ordering::Relaxed) + 1)
|
||||
}
|
||||
}
|
||||
|
||||
struct PartialCountingNode(AtomicU32);
|
||||
|
||||
impl<Input> Node<Input> for PartialCountingNode {
|
||||
type Output = u32;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<u32> {
|
||||
GPoll::Partial(self.0.fetch_add(1, Ordering::Relaxed) + 1)
|
||||
}
|
||||
}
|
||||
|
||||
struct ValueNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> Node<Input> for ValueNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(Some(0.5), None, None, generations, arena)
|
||||
}
|
||||
|
||||
fn element_layout<T: Clone + Send + Sync + 'static>() -> core_types::record::Layout {
|
||||
core_types::record::Layout::default().with_writes(0, core_types::record::element_write::<T>(), &[])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_serialize_exposes_the_capture_through_the_edge() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let monitor = MonitorNode::new(core_types::record::RecordLift::<u32, _>::new(ValueNode(11u32)), &layout);
|
||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||
assert!(handle.serialize().is_none(), "no capture before the first eval");
|
||||
|
||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||
let GPoll::Final(_) = edge.eval(&ctx) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
|
||||
let io = handle.serialize().expect("the eval landed a capture");
|
||||
let io = io.downcast_ref::<IORecord<CtxSnapshot, RecordCapture>>().expect("the capture is the monitor io");
|
||||
assert!(
|
||||
core_types::context::ExtractFootprint::try_footprint(&io.input).is_none(),
|
||||
"the root context has no footprint to capture"
|
||||
);
|
||||
let element = io.output.materialize_element(&arena).expect("the capture materializes inside the window");
|
||||
assert_eq!(*element.downcast_ref::<u32>().unwrap(), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memoize_caches_across_evals() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0))), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memo_invalidates_on_generation_bump() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let source: SourceId = 7;
|
||||
let before = [(source, 1)];
|
||||
let after = [(source, 2)];
|
||||
let scope_before = scope_fixture(&before, &arena);
|
||||
let scope_after = scope_fixture(&after, &arena);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0))), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_after)), GPoll::Final(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memo_replays_partiality_on_hit() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(PartialCountingNode(AtomicU32::new(0))), &layout);
|
||||
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
|
||||
|
||||
assert_eq!(memoized.eval(&ctx), GPoll::Partial(1));
|
||||
assert_eq!(memoized.eval(&ctx), GPoll::Partial(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memoized_edges_stack_and_rewire() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let edge = EdgeHandle::new_record::<u32>(Arc::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0)))) as Arc<ErasedRecordNode>);
|
||||
let memoized = EdgeHandle::new_record::<u32>(Arc::new(MemoizeNode::new(edge.downcast_record::<u32>().unwrap(), &layout)) as Arc<ErasedRecordNode>);
|
||||
let stacked = MemoizeNode::new(memoized.downcast_record::<u32>().unwrap(), &layout);
|
||||
let stacked = core_types::record::RecordExtract::<u32, _>::new(stacked, &layout);
|
||||
|
||||
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
|
||||
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_memo_shares_one_record_copy_per_frame() {
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<String>();
|
||||
let memo = FrameMemoNode::new(core_types::record::RecordLift::<String, _>::new(ValueNode("lent out".to_string())), &layout);
|
||||
|
||||
let GPoll::Final(first) = memo.eval(&ctx) else {
|
||||
panic!("the miss must fill the frame table");
|
||||
};
|
||||
let GPoll::Final(second) = memo.eval(&ctx) else {
|
||||
panic!("the hit must revive the published record");
|
||||
};
|
||||
let first: &String = unsafe { core_types::record::borrow_element(layout.rec(&first)) };
|
||||
let second: &String = unsafe { core_types::record::borrow_element(layout.rec(&second)) };
|
||||
assert_eq!(first, "lent out");
|
||||
assert!(std::ptr::eq(first, second), "the hit shares the parked payload");
|
||||
}
|
||||
io.as_ref().map(|output| output.clone() as Arc<dyn std::any::Any + Send + Sync>)
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
use core_types::ExtractAll;
|
||||
use core_types::runtime::SourceFuture;
|
||||
use core_types::{Ctx, ops::Convert, ops::ConvertAsync, transform::Footprint};
|
||||
use core_types::{Ctx, ExtractFootprint, ops::Convert, transform::Footprint};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
// Re-export TypeNode from core-types for convenience
|
||||
pub use core_types::ops::TypeNode;
|
||||
|
||||
/// Passes-through the input value without changing it. This is useful for rerouting wires for organization purposes.
|
||||
#[node_macro::node(category("General"), skip_impl)]
|
||||
fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T {
|
||||
@@ -10,18 +11,13 @@ fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T {
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), skip_impl)]
|
||||
fn into<T: Send + Into<O>, O: Send>(_: impl Ctx, value: T, #[data] _out_ty: PhantomData<O>) -> O {
|
||||
fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty: PhantomData<O>) -> O {
|
||||
value.into()
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), skip_impl)]
|
||||
fn convert<T: Send + Convert<O, C>, O: Send, C: Send>(ctx: impl Ctx + ExtractAll, value: T, converter: C, #[data] _out_ty: PhantomData<O>) -> O {
|
||||
value.convert(*ctx.try_footprint().unwrap_or(&Footprint::DEFAULT), converter)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), skip_impl)]
|
||||
fn convert_async<T: Send + ConvertAsync<O, C>, O: Send + 'static, C: Send>(ctx: impl Ctx + ExtractAll, value: T, converter: C, #[data] _out_ty: PhantomData<O>) -> SourceFuture<O> {
|
||||
value.convert(*ctx.try_footprint().unwrap_or(&Footprint::DEFAULT), converter)
|
||||
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 {
|
||||
value.convert(*ctx.try_footprint().unwrap_or(&Footprint::DEFAULT), converter).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -30,6 +26,6 @@ mod test {
|
||||
|
||||
#[test]
|
||||
pub fn passthrough_node() {
|
||||
assert_eq!(passthrough(&(), &4), &4);
|
||||
assert_eq!(passthrough((), &4), &4);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,6 @@
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::TransformMut;
|
||||
use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, Color, Context, Ctx, DeriveCtx, ModifyFootprint};
|
||||
use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
@@ -10,8 +9,8 @@ use vector_types::GradientStops;
|
||||
|
||||
/// Constructs a single-element `Artboard[]` with the given content and metadata stored as row attributes.
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn create_artboard<T: IntoGraphicList>(
|
||||
ctx: impl Ctx + DeriveCtx + ModifyFootprint,
|
||||
pub async fn create_artboard<T: IntoGraphicList>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
/// Graphics to include within the artboard.
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
@@ -23,7 +22,7 @@ pub fn create_artboard<T: IntoGraphicList>(
|
||||
Context -> List<GradientStops>,
|
||||
Context -> DAffine2,
|
||||
)]
|
||||
content: impl Node<Context<'_>, Output = T>,
|
||||
content: impl Node<Context<'static>, Output = T>,
|
||||
/// Coordinate of the top-left corner of the artboard within the document.
|
||||
location: DVec2,
|
||||
/// Width and height of the artboard within the document.
|
||||
@@ -33,9 +32,14 @@ pub fn create_artboard<T: IntoGraphicList>(
|
||||
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible.
|
||||
#[default(true)]
|
||||
clip: bool,
|
||||
) -> Result<List<Artboard>, Interrupt> {
|
||||
let translated = ctx.modify_footprint(|footprint| footprint.translate(location));
|
||||
let content = content.eval(&translated.ctx())?.into_graphic_list();
|
||||
) -> List<Artboard> {
|
||||
let footprint = ctx.try_footprint().copied();
|
||||
let mut new_ctx = OwnedContextImpl::from(ctx);
|
||||
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
|
||||
// dimensions to represent dragging from the opposite corner). Compute the corner using the raw signed
|
||||
@@ -46,11 +50,11 @@ pub fn create_artboard<T: IntoGraphicList>(
|
||||
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
|
||||
Ok(List::new_from_item(
|
||||
List::new_from_item(
|
||||
Item::new_from_element(Artboard::new(content))
|
||||
.with_attribute(ATTR_LOCATION, normalized_location)
|
||||
.with_attribute(ATTR_DIMENSIONS, normalized_dimensions)
|
||||
.with_attribute(ATTR_BACKGROUND, background)
|
||||
.with_attribute(ATTR_CLIP, clip),
|
||||
))
|
||||
)
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::{AttributeDyn, AttributeValueDyn, Item, List, ListDyn};
|
||||
use core_types::registry::types::{Angle, SignedInteger};
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, Color, Context, Ctx, DeriveCtx};
|
||||
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
@@ -109,8 +108,8 @@ pub fn extract_element<T: Clone + Default + Send + Sync + 'static>(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("General"))]
|
||||
fn map<Item: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
async fn map<Item: AnyHash + Send + Sync + CacheHash>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
@@ -128,24 +127,23 @@ fn map<Item: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
Context -> List<GradientStops>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
mapped: impl Node<Context<'_>, Output = List<Item>>,
|
||||
) -> Result<List<Item>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
mapped: impl Node<Context<'static>, Output = List<Item>>,
|
||||
) -> List<Item> {
|
||||
let mut rows = List::new();
|
||||
|
||||
for (i, row) in content.into_iter().enumerate() {
|
||||
let item = List::new_from_item(row);
|
||||
let scoped = ctx.push_vararg(&item);
|
||||
let list = mapped.eval(&scoped.ctx().promoted(&spilled, i as u64))?;
|
||||
let owned_ctx = OwnedContextImpl::from(ctx.clone());
|
||||
let owned_ctx = owned_ctx.with_vararg(Box::new(List::new_from_item(row))).with_index(i);
|
||||
let list = mapped.eval(owned_ctx.into_context()).await;
|
||||
|
||||
rows.extend(list);
|
||||
}
|
||||
|
||||
Ok(rows)
|
||||
rows
|
||||
}
|
||||
|
||||
#[node_macro::node(category("General"))]
|
||||
fn mirror<T: Send + Clone>(
|
||||
async fn mirror<T: 'n + Send + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
@@ -231,8 +229,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
|
||||
/// monomorphizes over `T` instead of the cartesian product `(T, U)`.
|
||||
#[node_macro::node(category("Attributes: Write"))]
|
||||
fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
async fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
/// The `List` to set the named attribute on (one value per item).
|
||||
#[implementations(
|
||||
List<Artboard>,
|
||||
@@ -254,17 +252,15 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
name: String,
|
||||
/// The node that produces the attribute value for each item. Called once per item with the item's index in context.
|
||||
#[implementations(Context -> AttributeValueDyn)]
|
||||
value: impl Node<Context<'_>, Output = AttributeValueDyn>,
|
||||
) -> Result<List<T>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
value: impl Node<'n, Context<'static>, Output = AttributeValueDyn>,
|
||||
) -> List<T> {
|
||||
for index in 0..content.len() {
|
||||
let row = content.clone_item(index).expect("index is within bounds");
|
||||
let item = List::new_from_item(row);
|
||||
let scoped = ctx.push_vararg(&item);
|
||||
let v = value.eval(&scoped.ctx().promoted(&spilled, index as u64))?;
|
||||
let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_vararg(Box::new(List::new_from_item(row))).with_index(index);
|
||||
let v = value.eval(owned_ctx.into_context()).await;
|
||||
content.set_attribute_value_dyn(&name, index, v);
|
||||
}
|
||||
Ok(content)
|
||||
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).
|
||||
@@ -501,7 +497,7 @@ fn read_attribute_raster(
|
||||
|
||||
/// Joins two `List`s of the same type, extending the base `List` with the items from the new `List`.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub fn extend<T: Send + Clone>(
|
||||
pub async fn extend<T: 'n + Send + Clone>(
|
||||
_: impl Ctx,
|
||||
/// 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>)]
|
||||
@@ -521,7 +517,7 @@ pub fn extend<T: Send + Clone>(
|
||||
/// 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.
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn legacy_layer_extend<T: Send + Clone>(
|
||||
pub async fn legacy_layer_extend<T: 'n + Send + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)] base: List<T>,
|
||||
#[expose]
|
||||
@@ -548,7 +544,7 @@ pub fn legacy_layer_extend<T: Send + Clone>(
|
||||
/// Nests the input graphical content in a wrapper graphic. This essentially "groups" the input.
|
||||
/// The inverse of this node is 'Flatten Graphic'.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub fn wrap_graphic<T: Into<Graphic>>(
|
||||
pub async fn wrap_graphic<T: Into<Graphic> + 'n>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
@@ -569,7 +565,7 @@ pub fn wrap_graphic<T: Into<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.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub fn to_graphic<T: IntoGraphicList>(
|
||||
pub async fn to_graphic<T: IntoGraphicList>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
@@ -587,7 +583,7 @@ pub fn to_graphic<T: IntoGraphicList>(
|
||||
|
||||
/// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: bool) -> List<Graphic> {
|
||||
pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: bool) -> 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) {
|
||||
for index in 0..current_graphic_list.len() {
|
||||
@@ -624,7 +620,7 @@ pub fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: bool)
|
||||
|
||||
/// 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"))]
|
||||
pub fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
pub async fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
let graphic_list = content.into_graphic_list();
|
||||
let mut output: List<Vector> = graphic_list.clone().into_flattened_list();
|
||||
|
||||
@@ -657,19 +653,19 @@ pub fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Gr
|
||||
|
||||
/// 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"))]
|
||||
pub fn flatten_raster<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Raster<CPU>>)] content: T) -> List<Raster<CPU>> {
|
||||
pub async fn flatten_raster<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Raster<CPU>>)] content: T) -> List<Raster<CPU>> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
/// 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"))]
|
||||
pub fn flatten_color<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] content: T) -> List<Color> {
|
||||
pub async fn flatten_color<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] content: T) -> List<Color> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
/// 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"))]
|
||||
pub fn flatten_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<GradientStops>)] content: T) -> List<GradientStops> {
|
||||
pub async fn flatten_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<GradientStops>)] content: T) -> List<GradientStops> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
use core_types::NodeIO;
|
||||
use core_types::WasmNotSend;
|
||||
pub use core_types::registry::{DowncastBothNode, DynAnyNode, FutureWrapperNode, PanicNode};
|
||||
pub use core_types::{Node, generic, ops};
|
||||
use dyn_any::StaticType;
|
||||
pub use graph_craft::proto::{Any, NodeContainer, TypeErasedBox, TypeErasedNode};
|
||||
use graph_craft::proto::{FutureAny, SharedNodeContainer};
|
||||
|
||||
pub trait IntoTypeErasedNode<'n> {
|
||||
fn into_type_erased(self) -> TypeErasedBox<'n>;
|
||||
}
|
||||
|
||||
impl<'n, N: 'n> IntoTypeErasedNode<'n> for N
|
||||
where
|
||||
N: for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + Sync + WasmNotSend,
|
||||
{
|
||||
fn into_type_erased(self) -> TypeErasedBox<'n> {
|
||||
Box::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn input_node<O: StaticType>(n: SharedNodeContainer) -> DowncastBothNode<(), O> {
|
||||
downcast_node(n)
|
||||
}
|
||||
pub fn downcast_node<I: StaticType, O: StaticType>(n: SharedNodeContainer) -> DowncastBothNode<I, O> {
|
||||
DowncastBothNode::new(n)
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
pub mod any;
|
||||
pub mod platform_application_io;
|
||||
pub mod render_background;
|
||||
pub mod render_cache;
|
||||
pub mod render_node;
|
||||
pub mod render_pixel_preview;
|
||||
pub mod runtime;
|
||||
pub mod text;
|
||||
pub use blending_nodes;
|
||||
pub use brush_nodes as brush;
|
||||
|
||||
@@ -3,11 +3,9 @@ use base64::Engine;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use canvas_utils::{Canvas, CanvasHandle};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::{Item, List};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::runtime::SourceFuture;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::transform::Footprint;
|
||||
#[cfg(target_family = "wasm")]
|
||||
@@ -139,7 +137,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.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
async fn load_resource(_: impl Ctx, _primary: (), #[name("URL")] url: String) -> Arc<[u8]> {
|
||||
async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: String) -> Arc<[u8]> {
|
||||
let placeholder = || -> Arc<[u8]> { Arc::from(Vec::<u8>::new()) };
|
||||
|
||||
let response = match reqwest::Client::new().get(&url).send().await {
|
||||
@@ -187,14 +185,14 @@ fn decode_image(_: impl Ctx, data: Arc<[u8]>) -> List<Raster<CPU>> {
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[node_macro::node(category(""))]
|
||||
fn create_canvas(_: impl Ctx) -> CanvasHandle {
|
||||
async fn create_canvas(_: impl Ctx) -> CanvasHandle {
|
||||
CanvasHandle::new()
|
||||
}
|
||||
|
||||
/// Renders a view of the input graphic within an area defined by the *Footprint*.
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[node_macro::node(category(""))]
|
||||
async fn rasterize<T: WasmNotSend + Clone>(
|
||||
async fn rasterize<T: WasmNotSend + Clone + 'n>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Vector>,
|
||||
@@ -264,37 +262,29 @@ where
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub fn editor_api(_: impl Ctx, #[scope("editor-api")] editor_api: Arc<PlatformEditorApi>) -> Arc<PlatformEditorApi> {
|
||||
pub async fn editor_api<'a: 'n>(_: impl Ctx, #[scope("editor-api")] editor_api: &'a PlatformEditorApi) -> &'a PlatformEditorApi {
|
||||
editor_api
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn resource(_: impl Ctx, hash: ResourceHash, #[scope(editor_api::IDENTIFIER)] editor_api: Arc<PlatformEditorApi>) -> SourceFuture<GPoll<Resource>> {
|
||||
let application_io = editor_api.application_io.clone();
|
||||
Box::pin(async move {
|
||||
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"),
|
||||
}
|
||||
pub async fn resource<'a: 'n>(_: impl Ctx, hash: ResourceHash, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Resource {
|
||||
let application_io = editor_api.application_io.as_ref().expect("ApplicationIo must be available when using resources");
|
||||
application_io.load_resource(hash).await.unwrap_or_else(|| {
|
||||
panic!("Resource {hash} not found");
|
||||
})
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub fn wgpu_executor(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Arc<PlatformEditorApi>) -> ::wgpu_executor::WgpuExecutorHandle {
|
||||
::wgpu_executor::WgpuExecutorHandle(
|
||||
editor_api
|
||||
.application_io
|
||||
.as_ref()
|
||||
.expect("ApplicationIo not not available")
|
||||
.gpu_executor_arc()
|
||||
.expect("GPU executor not available"),
|
||||
)
|
||||
pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> &'a ::wgpu_executor::WgpuExecutor {
|
||||
editor_api
|
||||
.application_io
|
||||
.as_ref()
|
||||
.expect("ApplicationIo not not available")
|
||||
.gpu_executor()
|
||||
.expect("GPU executor not available")
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub fn try_wgpu_executor(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Arc<PlatformEditorApi>) -> Option<::wgpu_executor::WgpuExecutorHandle> {
|
||||
editor_api.application_io.as_ref()?.gpu_executor_arc().map(::wgpu_executor::WgpuExecutorHandle)
|
||||
pub async fn try_wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Option<&'a ::wgpu_executor::WgpuExecutor> {
|
||||
editor_api.application_io.as_ref()?.gpu_executor()
|
||||
}
|
||||
@@ -9,10 +9,14 @@ use graphic_types::raster_types::Texture;
|
||||
use rendering::{RenderParams, SvgRender, SvgRenderOutput};
|
||||
use std::fmt::Write;
|
||||
use wgpu::util::DeviceExt;
|
||||
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
|
||||
use wgpu_executor::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache};
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render_background(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache, data: RenderOutput) -> RenderOutput {
|
||||
async fn render_background<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
|
||||
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
|
||||
data: RenderOutput,
|
||||
) -> RenderOutput {
|
||||
let footprint = ctx.footprint();
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
@@ -31,12 +35,14 @@ fn render_background(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(
|
||||
let data = match foreground_data {
|
||||
RenderOutputType::Texture(foreground_texture) => {
|
||||
let doc_to_screen = render_params.footprint.transform.as_affine2();
|
||||
let blended = pipeline.run::<CompositeBackground>(&CompositeBackgroundArgs {
|
||||
foreground: foreground_texture.as_ref(),
|
||||
backgrounds: &metadata.backgrounds,
|
||||
document_to_screen: doc_to_screen,
|
||||
zoom: render_params.viewport_zoom.to_f32(),
|
||||
});
|
||||
let blended = pipeline
|
||||
.run::<CompositeBackground>(&CompositeBackgroundArgs {
|
||||
foreground: foreground_texture.as_ref(),
|
||||
backgrounds: &metadata.backgrounds,
|
||||
document_to_screen: doc_to_screen,
|
||||
zoom: render_params.viewport_zoom.to_f32(),
|
||||
})
|
||||
.await;
|
||||
|
||||
RenderOutputType::Texture(blended)
|
||||
}
|
||||
@@ -115,9 +121,9 @@ fn render_background(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
fn composite_background_pipeline(
|
||||
async fn composite_background_pipeline<'a: 'n>(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
|
||||
#[data] pipeline: WgpuPipelineCache,
|
||||
) -> WgpuPipelineCache {
|
||||
if let Some(executor) = executor {
|
||||
@@ -142,7 +148,7 @@ pub struct CompositeBackgroundArgs<'a> {
|
||||
zoom: f32,
|
||||
}
|
||||
|
||||
impl WgpuPipeline for CompositeBackground {
|
||||
impl AsyncWgpuPipeline for CompositeBackground {
|
||||
type Args<'a> = CompositeBackgroundArgs<'a>;
|
||||
type Out = Texture;
|
||||
|
||||
@@ -325,7 +331,7 @@ impl WgpuPipeline for CompositeBackground {
|
||||
}
|
||||
}
|
||||
|
||||
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
async fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
let &CompositeBackgroundArgs {
|
||||
foreground,
|
||||
backgrounds,
|
||||
@@ -334,7 +340,7 @@ impl WgpuPipeline for CompositeBackground {
|
||||
} = args;
|
||||
|
||||
let foreground_size = foreground.size();
|
||||
let output = executor.request_texture(UVec2::new(foreground_size.width, foreground_size.height));
|
||||
let output = executor.request_texture(UVec2::new(foreground_size.width, foreground_size.height)).await;
|
||||
|
||||
if zoom <= 0. {
|
||||
return output;
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
//! Tile-based render caching for efficient viewport panning.
|
||||
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::math::bbox::AxisAlignedBbox;
|
||||
use core_types::transform::{Footprint, RenderQuality, Transform};
|
||||
use core_types::{Ctx, DeriveCtx, ExtractAll};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
@@ -12,6 +11,7 @@ use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
|
||||
use std::collections::HashSet;
|
||||
use std::hash::Hash;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
pub const TILE_SIZE: u32 = 256;
|
||||
pub const MAX_CACHE_MEMORY_BYTES: usize = 512 * 1024 * 1024;
|
||||
@@ -321,23 +321,25 @@ fn flood_fill(start: &TileCoord, tile_set: &HashSet<TileCoord>, visited: &mut Ha
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn render_output_cache(
|
||||
ctx: impl Ctx + ExtractAll + DeriveCtx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
|
||||
#[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: std::sync::Arc<PlatformEditorApi>,
|
||||
data: impl Node<Context<'_>, Output = RenderOutput>,
|
||||
pub async fn render_output_cache<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + ExtractRealTime + ExtractAnimationTime + ExtractPointerPosition + Sync,
|
||||
#[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,
|
||||
data: impl Node<Context<'static>, Output = RenderOutput> + Send + Sync,
|
||||
#[data] tile_cache: TileCache,
|
||||
) -> Result<RenderOutput, Interrupt> {
|
||||
let footprint = *ctx.footprint();
|
||||
) -> RenderOutput {
|
||||
let footprint = ctx.footprint();
|
||||
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");
|
||||
return data.eval(&ctx.derived());
|
||||
let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint);
|
||||
return data.eval(context.into_context()).await;
|
||||
};
|
||||
|
||||
// Fall back to direct render for non-Vello or zero-size viewports
|
||||
let physical_resolution = footprint.resolution;
|
||||
if !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || physical_resolution.x == 0 || physical_resolution.y == 0 {
|
||||
return data.eval(&ctx.derived());
|
||||
let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint).with_vararg(Box::new(render_params.clone()));
|
||||
return data.eval(context.into_context()).await;
|
||||
}
|
||||
|
||||
let zoom = footprint.scale_magnitudes().x;
|
||||
@@ -373,38 +375,8 @@ pub fn render_output_cache(
|
||||
if missing_region.tiles.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let min_tile = missing_region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y)));
|
||||
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(®ion_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,
|
||||
});
|
||||
let region = render_missing_region(missing_region, |ctx| data.eval(ctx), ctx.clone(), render_params, &footprint.transform, &device_origin_offset).await;
|
||||
new_regions.push(region);
|
||||
}
|
||||
|
||||
tile_cache.store_regions(new_regions.clone());
|
||||
@@ -413,18 +385,68 @@ pub fn render_output_cache(
|
||||
|
||||
// If no regions, fall back to direct render
|
||||
if all_regions.is_empty() {
|
||||
return data.eval(&ctx.derived());
|
||||
let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint).with_vararg(Box::new(render_params.clone()));
|
||||
return data.eval(context.into_context()).await;
|
||||
}
|
||||
|
||||
let executor = executor.expect("GPU executor not available");
|
||||
let output_texture = executor.request_texture(physical_resolution);
|
||||
let output_texture = executor.request_texture(physical_resolution).await;
|
||||
|
||||
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);
|
||||
|
||||
Ok(RenderOutput {
|
||||
RenderOutput {
|
||||
data: RenderOutputType::Texture(output_texture),
|
||||
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(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::List;
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::{Color, Context, Ctx, DeriveCtx, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots, WasmNotSend};
|
||||
use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs};
|
||||
use core_types::{Color, Context, Ctx, ExtractFootprint, OwnedContextImpl, WasmNotSend};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphene_application_io::{ExportFormat, RenderConfig};
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
@@ -9,7 +9,7 @@ use graphic_types::{Artboard, Graphic, Vector};
|
||||
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
|
||||
use std::sync::Arc;
|
||||
use vector_types::GradientStops;
|
||||
use wgpu_executor::RenderContext;
|
||||
use wgpu_executor::{RenderContext, WgpuExecutor};
|
||||
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
pub enum RenderIntermediateType {
|
||||
@@ -23,8 +23,8 @@ pub struct RenderIntermediate {
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
ctx: impl Ctx + ExtractVarArgs + DeriveCtx,
|
||||
async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
ctx: impl Ctx + ExtractVarArgs + ExtractAll + CloneVarArgs,
|
||||
#[implementations(
|
||||
Context -> List<Artboard>,
|
||||
Context -> List<Graphic>,
|
||||
@@ -34,19 +34,21 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
Context -> List<GradientStops>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
data: impl Node<Context<'_>, Output = T>,
|
||||
) -> Result<RenderIntermediate, Interrupt> {
|
||||
let data = data.eval(&ctx.derived())?;
|
||||
data: impl Node<Context<'static>, Output = T>,
|
||||
) -> RenderIntermediate {
|
||||
let render_params = ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderParams>()
|
||||
.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 mut metadata = RenderMetadata::default();
|
||||
data.collect_metadata(&mut metadata, footprint, None);
|
||||
Ok(match &render_params.render_output_type {
|
||||
match &render_params.render_output_type {
|
||||
RenderOutputTypeRequest::Vello => {
|
||||
let mut scene = vello::Scene::new();
|
||||
|
||||
@@ -68,13 +70,13 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render(
|
||||
async fn render<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
|
||||
data: RenderIntermediate,
|
||||
) -> RenderOutput {
|
||||
let footprint = ctx.footprint();
|
||||
@@ -131,6 +133,7 @@ fn render(
|
||||
let texture = executor
|
||||
.expect("GPU executor not available")
|
||||
.render_vello_scene(&transformed_scene, footprint.resolution, context, None)
|
||||
.await
|
||||
.expect("Failed to render Vello scene");
|
||||
RenderOutputType::Texture(texture)
|
||||
}
|
||||
@@ -141,13 +144,11 @@ fn render(
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn create_context(ctx: impl Ctx + ExtractVarArgs + DeriveCtx, data: impl Node<Context<'_>, Output = RenderOutput>) -> Result<RenderOutput, Interrupt> {
|
||||
let render_config = *ctx
|
||||
.vararg(0)
|
||||
.expect("Did not find var args")
|
||||
.downcast_ref::<RenderConfig>()
|
||||
.expect("Downcasting render config yielded invalid type");
|
||||
|
||||
async fn create_context<'a: 'n>(
|
||||
// Context injections are defined in the wrap_network_in_scope function
|
||||
render_config: RenderConfig,
|
||||
data: impl Node<Context<'static>, Output = RenderOutput>,
|
||||
) -> RenderOutput {
|
||||
let render_output_type = match render_config.export_format {
|
||||
ExportFormat::Svg => RenderOutputTypeRequest::Svg,
|
||||
ExportFormat::Raster => RenderOutputTypeRequest::Vello,
|
||||
@@ -168,89 +169,16 @@ fn create_context(ctx: impl Ctx + ExtractVarArgs + DeriveCtx, data: impl Node<Co
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let scope = ctx
|
||||
.scope()
|
||||
.with_real_time(Some(render_config.time.time))
|
||||
.with_animation_time(Some(render_config.time.animation_time.as_secs_f64()))
|
||||
.with_pointer_position(Some(render_config.pointer));
|
||||
let varargs = VarArgLink {
|
||||
args: VarArgSlots::Single(&render_params),
|
||||
outer: None,
|
||||
};
|
||||
let scoped = ctx.with_scope(&scope);
|
||||
let with_params = scoped.with_varargs(&varargs);
|
||||
let mut result = data.eval(&with_params.with_footprint(&footprint))?;
|
||||
let ctx = OwnedContextImpl::default()
|
||||
.with_footprint(footprint)
|
||||
.with_real_time(render_config.time.time)
|
||||
.with_animation_time(render_config.time.animation_time.as_secs_f64())
|
||||
.with_pointer_position(render_config.pointer)
|
||||
.with_vararg(Box::new(render_params))
|
||||
.into_context();
|
||||
|
||||
let mut result = data.eval(ctx).await;
|
||||
|
||||
result.metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale)));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope, VarArgsResult};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::node::Node;
|
||||
use core_types::{ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
|
||||
use graphene_application_io::TimingInformation;
|
||||
|
||||
struct ProbeNode;
|
||||
|
||||
impl<'a> Node<ContextImpl<'a>> for ProbeNode {
|
||||
type Output = RenderOutput;
|
||||
|
||||
fn eval(&self, ctx: &ContextImpl<'a>) -> GPoll<RenderOutput> {
|
||||
let render_params = ctx.vararg(0).unwrap().downcast_ref::<RenderParams>().expect("the vararg chain must start with RenderParams");
|
||||
assert_eq!(render_params.scale, 2.0);
|
||||
assert!(matches!(ctx.vararg(1), Err(VarArgsResult::IndexOutOfBounds)), "the RenderConfig must not leak downstream");
|
||||
assert_eq!(ctx.footprint().transform, glam::DAffine2::from_scale(glam::DVec2::splat(2.0)) * Footprint::DEFAULT.transform);
|
||||
assert_eq!(ctx.try_real_time(), Some(1.5));
|
||||
assert_eq!(ctx.try_animation_time(), Some(2.0));
|
||||
assert_eq!(ctx.try_pointer_position(), Some(glam::DVec2::new(3.0, 4.0)));
|
||||
GPoll::Final(RenderOutput {
|
||||
data: RenderOutputType::Buffer {
|
||||
data: Vec::new(),
|
||||
width: 0,
|
||||
height: 0,
|
||||
},
|
||||
metadata: RenderMetadata::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_context_builds_the_render_context_from_the_root_vararg() {
|
||||
let arena = Arena::new(256).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
let render_config = RenderConfig {
|
||||
scale: 2.0,
|
||||
time: TimingInformation {
|
||||
time: 1.5,
|
||||
animation_time: std::time::Duration::from_secs(2),
|
||||
},
|
||||
pointer: glam::DVec2::new(3.0, 4.0),
|
||||
..Default::default()
|
||||
};
|
||||
let varargs = VarArgLink {
|
||||
args: VarArgSlots::Single(&render_config),
|
||||
outer: None,
|
||||
};
|
||||
let ctx = root.with_varargs(&varargs);
|
||||
|
||||
let graph = CreateContextNode::new(ProbeNode);
|
||||
let GPoll::Final(result) = <CreateContextNode<ProbeNode> as Node<ContextImpl>>::eval(&graph, &ctx) else {
|
||||
panic!("create_context must complete synchronously");
|
||||
};
|
||||
assert_eq!(
|
||||
result.data,
|
||||
RenderOutputType::Buffer {
|
||||
data: Vec::new(),
|
||||
width: 0,
|
||||
height: 0
|
||||
}
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -1,22 +1,22 @@
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::{Ctx, DeriveCtx, ExtractAll};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2, UVec2, Vec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphic_types::raster_types::Texture;
|
||||
use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
|
||||
use vector_types::vector::style::RenderMode;
|
||||
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
|
||||
use wgpu_executor::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache};
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn render_pixel_preview(
|
||||
ctx: impl Ctx + ExtractAll + DeriveCtx,
|
||||
pub async fn render_pixel_preview<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync,
|
||||
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
|
||||
data: impl Node<Context<'_>, Output = RenderOutput>,
|
||||
) -> Result<RenderOutput, Interrupt> {
|
||||
data: impl Node<Context<'static>, Output = RenderOutput> + Send + Sync,
|
||||
) -> RenderOutput {
|
||||
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");
|
||||
return data.eval(&ctx.derived());
|
||||
let context = OwnedContextImpl::from(ctx).into_context();
|
||||
return data.eval(context).await;
|
||||
};
|
||||
let physical_scale = render_params.scale;
|
||||
|
||||
@@ -24,7 +24,8 @@ pub fn render_pixel_preview(
|
||||
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. {
|
||||
return data.eval(&ctx.derived());
|
||||
let context = OwnedContextImpl::from(ctx).into_context();
|
||||
return data.eval(context).await;
|
||||
}
|
||||
|
||||
let physical_resolution = footprint.resolution;
|
||||
@@ -50,31 +51,33 @@ pub fn render_pixel_preview(
|
||||
quality: footprint.quality,
|
||||
};
|
||||
|
||||
let scoped = ctx.push_vararg(&render_params);
|
||||
let mut result = data.eval(&scoped.ctx().with_footprint(&upstream_footprint))?;
|
||||
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(upstream_footprint).with_vararg(Box::new(render_params)).into_context();
|
||||
let mut result = data.eval(new_ctx).await;
|
||||
|
||||
let RenderOutputType::Texture(ref source_texture) = result.data else { return Ok(result) };
|
||||
let RenderOutputType::Texture(ref source_texture) = result.data else { return result };
|
||||
|
||||
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 resampled = pipeline.run::<PixelPreview>(&PixelPreviewArgs {
|
||||
source: source_texture.as_ref(),
|
||||
transform: &transform,
|
||||
size: physical_resolution,
|
||||
});
|
||||
let resampled = pipeline
|
||||
.run::<PixelPreview>(&PixelPreviewArgs {
|
||||
source: source_texture.as_ref(),
|
||||
transform: &transform,
|
||||
size: physical_resolution,
|
||||
})
|
||||
.await;
|
||||
|
||||
result.data = RenderOutputType::Texture(resampled);
|
||||
|
||||
result.metadata.apply_transform(footprint.transform * DAffine2::from_translation(upstream_min));
|
||||
|
||||
Ok(result)
|
||||
result
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
fn pixel_preview_pipeline(
|
||||
async fn pixel_preview_pipeline<'a: 'n>(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<wgpu_executor::WgpuExecutorHandle>,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
|
||||
#[data] pipeline: WgpuPipelineCache,
|
||||
) -> WgpuPipelineCache {
|
||||
if let Some(executor) = executor {
|
||||
@@ -94,7 +97,7 @@ pub struct PixelPreviewArgs<'a> {
|
||||
size: UVec2,
|
||||
}
|
||||
|
||||
impl WgpuPipeline for PixelPreview {
|
||||
impl AsyncWgpuPipeline for PixelPreview {
|
||||
type Args<'a> = PixelPreviewArgs<'a>;
|
||||
type Out = Texture;
|
||||
|
||||
@@ -166,11 +169,11 @@ impl WgpuPipeline for PixelPreview {
|
||||
PixelPreview { pipeline, bind_group_layout }
|
||||
}
|
||||
|
||||
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
async fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
let context = &executor.context();
|
||||
let &PixelPreviewArgs { source, transform, size } = args;
|
||||
|
||||
let output = executor.request_texture(size);
|
||||
let output = executor.request_texture(size).await;
|
||||
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
pub use core_types::runtime::*;
|
||||
|
||||
use crate::platform_application_io::editor_api;
|
||||
use core_types::Ctx;
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub fn runtime(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Arc<PlatformEditorApi>) -> RuntimeHandle {
|
||||
editor_api.runtime.clone()
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
use core_types::Context;
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::List;
|
||||
use core_types::registry::types::{Fraction, Percentage, PixelSize};
|
||||
use core_types::transform::Footprint;
|
||||
@@ -741,7 +740,7 @@ fn logical_not(
|
||||
|
||||
/// 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"))]
|
||||
fn switch<T, C>(
|
||||
async fn switch<T, C: Send + 'n + Clone>(
|
||||
#[implementations(Context)] ctx: C,
|
||||
condition: bool,
|
||||
#[expose]
|
||||
@@ -782,8 +781,8 @@ fn switch<T, C>(
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
if_false: impl Node<C, Output = T>,
|
||||
) -> GPoll<T> {
|
||||
if condition { if_true.eval(ctx) } else { if_false.eval(ctx) }
|
||||
) -> T {
|
||||
if condition { if_true.eval(ctx).await } else { if_false.eval(ctx).await }
|
||||
}
|
||||
|
||||
/// Constructs a bool value which may be set to true or false.
|
||||
@@ -989,279 +988,74 @@ fn normalize(_: impl Ctx, vector: DVec2) -> DVec2 {
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use core_types::Node;
|
||||
use core_types::generic::FnNode;
|
||||
|
||||
#[test]
|
||||
pub fn dot_product_function() {
|
||||
let vector_a = DVec2::new(1., 2.);
|
||||
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]
|
||||
pub fn length_function() {
|
||||
let vector = DVec2::new(3., 4.);
|
||||
assert_eq!(length(&(), vector), 5.);
|
||||
assert_eq!(length((), vector), 5.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_expression() {
|
||||
let result = math(&(), 0., "0".to_string(), 0.);
|
||||
let result = math((), 0., "0".to_string(), 0.);
|
||||
assert_eq!(result, 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_expression() {
|
||||
let result = math(&(), 0., "invalid".to_string(), 0.);
|
||||
let result = math((), 0., "invalid".to_string(), 0.);
|
||||
assert_eq!(result, 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn foo() {
|
||||
let fnn = FnNode::new(|(a, b)| (b, a));
|
||||
assert_eq!(fnn.eval((1u32, 2u32)), (2, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
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]
|
||||
pub fn subtract_f64() {
|
||||
assert_eq!(super::subtract(&(), 5_f64, 3_f64), 2.);
|
||||
assert_eq!(super::subtract((), 5_f64, 3_f64), 2.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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]
|
||||
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]
|
||||
pub fn modulo_negative() {
|
||||
assert_eq!(super::modulo(&(), -5_f64, 2_f64, false), -1_f64);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod graphene_test {
|
||||
use super::*;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope, ExtractIndex};
|
||||
use core_types::gpoll::{Finality, GPoll};
|
||||
use core_types::node::{BatchStatus, Node};
|
||||
use core_types::registry::{EdgeHandle, ErasedNode, construct};
|
||||
use std::mem::MaybeUninit;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct SourceNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> Node<Input> for SourceNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
struct IndexNode;
|
||||
|
||||
impl<Input: ExtractIndex> Node<Input> for IndexNode {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<f64> {
|
||||
GPoll::Final(input.innermost_index() as f64)
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_fixture(arena: &Arena) -> EvalScope<'_> {
|
||||
EvalScope::new(None, None, None, &[], arena)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_add_evaluates_through_the_node_path() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph = AddNode::new(SourceNode(1.0f64), SourceNode(2.0f64));
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_add_batches_through_the_erased_edge() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let erased: Box<ErasedNode<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.values(), &[12.0, 13.0, 14.0, 15.0]);
|
||||
assert_eq!(finality, Finality::AllFinal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_wire_constructor_resolves_and_wires() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let entries = logical_or_entries();
|
||||
let value = EdgeHandle::new(Arc::new(SourceNode(true)) as Arc<ErasedNode<bool>>);
|
||||
let other_value = EdgeHandle::new(Arc::new(SourceNode(false)) as Arc<ErasedNode<bool>>);
|
||||
let wired = construct(&entries[0], vec![value, other_value]).unwrap().downcast::<bool>().unwrap();
|
||||
|
||||
assert_eq!(Node::eval(&wired, &ctx), GPoll::Final(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctor_registration_populates_the_node_registry() {
|
||||
let registry = core_types::registry::NODE_REGISTRY.lock().unwrap();
|
||||
let rows = registry
|
||||
.iter()
|
||||
.find_map(|(id, rows)| id.as_str().ends_with("::AddNode").then_some(rows))
|
||||
.expect("AddNode rows registered at startup");
|
||||
assert_eq!(rows.len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_add_registers_one_entry_per_implementation() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let entries = 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.return_value, core_types::concrete!(f64));
|
||||
assert_eq!(entries[3].io.inputs, vec![core_types::concrete!(DVec2), core_types::concrete!(DVec2)]);
|
||||
assert_eq!(entries[3].io.return_value, core_types::concrete!(DVec2));
|
||||
|
||||
let augend = EdgeHandle::new(Arc::new(SourceNode(1.5f64)) as Arc<ErasedNode<f64>>);
|
||||
let addend = EdgeHandle::new(Arc::new(SourceNode(2.5f64)) as Arc<ErasedNode<f64>>);
|
||||
let wired = construct(&entries[0], vec![augend, addend]).unwrap().downcast::<f64>().unwrap();
|
||||
|
||||
assert_eq!(Node::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> Node<Input> for CountingSource {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
GPoll::Final(self.1)
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let taken = Arc::new(AtomicU32::new(0));
|
||||
let untaken = Arc::new(AtomicU32::new(0));
|
||||
let graph = SwitchNode::new(SourceNode(true), CountingSource(taken.clone(), 1.0), CountingSource(untaken.clone(), 2.0));
|
||||
|
||||
assert_eq!(Node::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> Node<Input> for PendingSource {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
GPoll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
struct PartialSource;
|
||||
|
||||
impl<Input> Node<Input> for PartialSource {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
GPoll::Partial(7.0)
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let pending = SwitchNode::new(SourceNode(true), PendingSource, PartialSource);
|
||||
assert_eq!(Node::eval(&pending, &ctx), GPoll::Pending);
|
||||
|
||||
let partial = SwitchNode::new(SourceNode(false), PendingSource, PartialSource);
|
||||
assert_eq!(Node::eval(&partial, &ctx), GPoll::Partial(7.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_switch_merges_condition_status_into_the_branch_result() {
|
||||
struct PartialCondition;
|
||||
|
||||
impl<Input> Node<Input> for PartialCondition {
|
||||
type Output = bool;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<bool> {
|
||||
GPoll::Partial(true)
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph = SwitchNode::new(PartialCondition, SourceNode(1.0f64), SourceNode(2.0f64));
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Partial(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_eval_computes_on_stand_in_and_traces_fallback() {
|
||||
struct FallbackNode;
|
||||
|
||||
impl<Input> Node<Input> for FallbackNode {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
GPoll::fallback(0.0, "upstream failed")
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph = AddNode::new(FallbackNode, SourceNode(5.0f64));
|
||||
let GPoll::Fallback(boxed) = Node::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]);
|
||||
assert_eq!(super::modulo((), -5_f64, 2_f64, false), -1_f64);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
#[node_macro::node(category("Vector: Modifier"), memoize)]
|
||||
fn boolean_operation<I: graphic_types::IntoGraphicList>(
|
||||
async fn boolean_operation<I: graphic_types::IntoGraphicList>(
|
||||
_: impl Ctx,
|
||||
/// The `List` of vector paths to perform the boolean operation on. Nested `List`s are automatically flattened.
|
||||
#[implementations(List<Graphic>, List<Vector>)]
|
||||
|
||||
@@ -201,8 +201,8 @@ mod test {
|
||||
use raster_types::Image;
|
||||
use raster_types::Raster;
|
||||
|
||||
#[test]
|
||||
fn color_overlay_multiply() {
|
||||
#[tokio::test]
|
||||
async fn color_overlay_multiply() {
|
||||
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
|
||||
let image = Image::new(1, 1, image_color);
|
||||
|
||||
@@ -212,7 +212,7 @@ mod test {
|
||||
// 100% of the output should come from the multiplied value
|
||||
let opacity = 100.;
|
||||
|
||||
let result = super::color_overlay(&(), List::new_from_element(Raster::new_cpu(image.clone())), overlay_color, BlendMode::Multiply, opacity);
|
||||
let result = super::color_overlay((), List::new_from_element(Raster::new_cpu(image.clone())), overlay_color, BlendMode::Multiply, opacity);
|
||||
let result = result.element(0).unwrap().clone();
|
||||
|
||||
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
|
||||
|
||||
@@ -8,7 +8,7 @@ use raster_types::{CPU, Raster};
|
||||
use std::cmp::{max, min};
|
||||
|
||||
#[node_macro::node(category("Raster: Filter"))]
|
||||
fn dehaze(_: impl Ctx, image_frame: List<Raster<CPU>>, strength: Percentage) -> List<Raster<CPU>> {
|
||||
async fn dehaze(_: impl Ctx, image_frame: List<Raster<CPU>>, strength: Percentage) -> List<Raster<CPU>> {
|
||||
image_frame
|
||||
.into_iter()
|
||||
.map(|mut row| {
|
||||
|
||||
@@ -87,7 +87,7 @@ fn unpremultiply_gamma_to_linear(buffer: Image<PremultipliedGammaPixel>) -> Imag
|
||||
|
||||
/// Blurs the image with a Gaussian or box blur kernel filter.
|
||||
#[node_macro::node(category("Raster: Filter"))]
|
||||
fn blur(
|
||||
async fn blur(
|
||||
_: impl Ctx,
|
||||
/// The image to be blurred.
|
||||
image_frame: List<Raster<CPU>>,
|
||||
@@ -124,7 +124,7 @@ fn blur(
|
||||
|
||||
/// Applies a median filter to reduce noise while preserving edges.
|
||||
#[node_macro::node(category("Raster: Filter"))]
|
||||
fn median_filter(
|
||||
async fn median_filter(
|
||||
_: impl Ctx,
|
||||
/// The image to be filtered.
|
||||
image_frame: List<Raster<CPU>>,
|
||||
|
||||
@@ -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=Gradient%20settings%20(Photoshop%206.0)
|
||||
#[node_macro::node(category("Raster: Adjustment"))]
|
||||
fn gradient_map<T: Adjust<Color>>(
|
||||
async fn gradient_map<T: Adjust<Color>>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Raster<CPU>>,
|
||||
|
||||
@@ -4,9 +4,9 @@ use core_types::list::{Item, List};
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
#[node_macro::node(category("Color"))]
|
||||
fn image_color_palette(
|
||||
async fn image_color_palette(
|
||||
_: impl Ctx,
|
||||
image: &List<Raster<CPU>>,
|
||||
image: List<Raster<CPU>>,
|
||||
#[default(4)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
@@ -68,7 +68,7 @@ mod test {
|
||||
#[test]
|
||||
fn test_image_color_palette() {
|
||||
let result = image_color_palette(
|
||||
&(),
|
||||
(),
|
||||
List::new_from_element(Raster::new_cpu(Image {
|
||||
width: 100,
|
||||
height: 100,
|
||||
@@ -77,6 +77,6 @@ mod test {
|
||||
})),
|
||||
1,
|
||||
);
|
||||
assert_eq!(result, List::new_from_element(Color::from_rgbaf32(0., 0., 0., 1.).unwrap()));
|
||||
assert_eq!(futures::executor::block_on(result), List::new_from_element(Color::from_rgbaf32(0., 0., 0., 1.).unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -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_width, image_height) = (row.element().width, row.element().height);
|
||||
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);
|
||||
@@ -290,7 +290,7 @@ pub fn empty_image(_: impl Ctx, transform: DAffine2, color: List<Color>) -> List
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn image(_: impl Ctx, resource: Resource) -> List<Raster<CPU>> {
|
||||
pub fn image<'a: 'n>(_: impl Ctx, resource: Resource) -> List<Raster<CPU>> {
|
||||
let image_data = resource.as_ref();
|
||||
|
||||
let Some(image) = ::image::load_from_memory(image_data).ok() else {
|
||||
|
||||
@@ -24,3 +24,9 @@ log = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
graphene-core = { workspace = true }
|
||||
vector-nodes = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt"] }
|
||||
kurbo = { workspace = true }
|
||||
@@ -1,17 +1,16 @@
|
||||
use crate::gcore::Context;
|
||||
use core::f64::consts::TAU;
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::List;
|
||||
use core_types::registry::types::{Angle, PixelSize};
|
||||
use core_types::{ATTR_TRANSFORM, Color, Ctx, DeriveCtx, InjectVarArgs};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::{Graphic, Vector};
|
||||
use raster_types::{CPU, Raster};
|
||||
use vector_types::GradientStops;
|
||||
|
||||
#[node_macro::node(category("Repeat"))]
|
||||
fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
async fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
@@ -19,38 +18,35 @@ fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
content: impl Node<Context<'_>, Output = List<T>>,
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
#[default(1)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
reverse: bool,
|
||||
) -> Result<List<T>, Interrupt> {
|
||||
) -> List<T> {
|
||||
// Someday this node can have the option to generate infinitely instead of a fixed count (basically `std::iter::repeat`).
|
||||
|
||||
let count = count as u64;
|
||||
let spilled = ctx.index_head();
|
||||
let count = count as usize;
|
||||
|
||||
let mut result_list = List::new();
|
||||
|
||||
for index in 0..count {
|
||||
let index = if reverse { count - index - 1 } else { index };
|
||||
|
||||
let mark = core_types::record::stack::sp();
|
||||
let generated_content = content.eval(&ctx.promoted(&spilled, index))?;
|
||||
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index);
|
||||
let generated_content = content.eval(new_ctx.into_context()).await;
|
||||
|
||||
for generated_row in generated_content.into_iter() {
|
||||
result_list.push(generated_row);
|
||||
}
|
||||
// SAFETY: generated_content is an owned list fully moved into result_list, so no record borrow into this iteration's frames remains.
|
||||
unsafe { core_types::record::stack::rewind(mark) };
|
||||
}
|
||||
|
||||
Ok(result_list)
|
||||
result_list
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Repeat"))]
|
||||
pub fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
@@ -58,7 +54,7 @@ pub fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
content: impl Node<Context<'_>, Output = List<T>>,
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
#[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.
|
||||
direction: PixelSize,
|
||||
@@ -66,11 +62,10 @@ pub fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
#[default(5)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
) -> Result<List<T>, Interrupt> {
|
||||
) -> List<T> {
|
||||
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
|
||||
let total = (count - 1).max(1) as f64;
|
||||
let spilled = ctx.index_head();
|
||||
|
||||
let mut result_list = List::new();
|
||||
|
||||
@@ -79,8 +74,8 @@ pub fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
let translation = index as f64 * direction / total;
|
||||
let transform = DAffine2::from_angle(angle) * DAffine2::from_translation(translation);
|
||||
|
||||
let mark = core_types::record::stack::sp();
|
||||
let generated_content = content.eval(&ctx.promoted(&spilled, index as u64))?;
|
||||
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index as usize);
|
||||
let generated_content = content.eval(new_ctx.into_context()).await;
|
||||
|
||||
for row_index in 0..generated_content.len() {
|
||||
let Some(mut row) = generated_content.clone_item(row_index) else { continue };
|
||||
@@ -92,16 +87,14 @@ pub fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
|
||||
result_list.push(row);
|
||||
}
|
||||
// SAFETY: rows are cloned into result_list and generated_content is owned, so no record borrow into this iteration's frames remains.
|
||||
unsafe { core_types::record::stack::rewind(mark) };
|
||||
}
|
||||
|
||||
Ok(result_list)
|
||||
result_list
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Repeat"))]
|
||||
fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
@@ -109,7 +102,7 @@ fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
content: impl Node<Context<'_>, Output = List<T>>,
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
start_angle: Angle,
|
||||
#[unit(" px")]
|
||||
#[default(5)]
|
||||
@@ -117,8 +110,7 @@ fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
#[default(5)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
) -> Result<List<T>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
) -> List<T> {
|
||||
let mut result_list = List::new();
|
||||
|
||||
for index in 0..count {
|
||||
@@ -126,8 +118,8 @@ fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
let translation = DAffine2::from_translation(radius * DVec2::Y);
|
||||
let transform = angle * translation;
|
||||
|
||||
let mark = core_types::record::stack::sp();
|
||||
let generated_content = content.eval(&ctx.promoted(&spilled, index as u64))?;
|
||||
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index as usize);
|
||||
let generated_content = content.eval(new_ctx.into_context()).await;
|
||||
|
||||
for row_index in 0..generated_content.len() {
|
||||
let Some(mut row) = generated_content.clone_item(row_index) else { continue };
|
||||
@@ -139,16 +131,14 @@ fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
|
||||
result_list.push(row);
|
||||
}
|
||||
// SAFETY: rows are cloned into result_list and generated_content is owned, so no record borrow into this iteration's frames remains.
|
||||
unsafe { core_types::record::stack::rewind(mark) };
|
||||
}
|
||||
|
||||
Ok(result_list)
|
||||
result_list
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Repeat"), name("Repeat on Points"))]
|
||||
fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl Ctx + DeriveCtx + InjectVarArgs,
|
||||
async fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs,
|
||||
points: List<Vector>,
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
@@ -157,179 +147,178 @@ fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
content: impl Node<Context<'_>, Output = List<T>>,
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
reverse: bool,
|
||||
) -> Result<List<T>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
) -> List<T> {
|
||||
let mut result_list = List::new();
|
||||
|
||||
for points_index in 0..points.len() {
|
||||
let Some(points_element) = points.element(points_index) else { continue };
|
||||
let transform: DAffine2 = points.attribute_cloned_or_default(ATTR_TRANSFORM, points_index);
|
||||
|
||||
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 mut iteration = async |index, point| {
|
||||
let transformed_point = transform.transform_point2(point);
|
||||
|
||||
let scoped = ctx.push_position(transformed_point);
|
||||
let mark = core_types::record::stack::sp();
|
||||
let generated_content = content.eval(&scoped.ctx().promoted(&spilled, index as u64))?;
|
||||
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(transformed_point);
|
||||
let generated_content = content.eval(new_ctx.into_context()).await;
|
||||
|
||||
for mut generated_row in generated_content.into_iter() {
|
||||
generated_row.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM).translation = transformed_point;
|
||||
result_list.push(generated_row);
|
||||
}
|
||||
// SAFETY: generated_content is an owned list fully moved into result_list, so no record borrow into this iteration's frames remains.
|
||||
unsafe { core_types::record::stack::rewind(mark) };
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result_list)
|
||||
result_list
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope, ExtractIndex, ExtractPosition};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::Item;
|
||||
use core_types::node::{LazyInput, Node, StatusCell};
|
||||
use core_types::Ctx;
|
||||
use core_types::Node;
|
||||
use core_types::transform::Footprint;
|
||||
use glam::DVec2;
|
||||
use graphene_core::ReadPositionNode;
|
||||
use graphene_core::extract_xy::{ExtractXyNode, XY};
|
||||
use graphic_types::Vector;
|
||||
use kurbo::Shape;
|
||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Rect};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use vector_nodes::generator_nodes::RectangleNode;
|
||||
use vector_types::subpath::Subpath;
|
||||
|
||||
const TEST_POSITION: &str = "test-position";
|
||||
fn vector_node_from_bezpath(bezpath: BezPath) -> List<Vector> {
|
||||
List::new_from_element(Vector::from_bezpath(bezpath))
|
||||
}
|
||||
|
||||
struct ValueNode<T>(T);
|
||||
#[derive(Clone)]
|
||||
pub struct FutureWrapperNode<T: Clone>(T);
|
||||
|
||||
impl<T: Clone, Input> Node<Input> for ValueNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
impl<'i, I: Ctx, T: 'i + Clone + Send> Node<'i, I> for FutureWrapperNode<T> {
|
||||
type Output = Pin<Box<dyn Future<Output = T> + 'i + Send>>;
|
||||
fn eval(&'i self, _input: I) -> Self::Output {
|
||||
let value = self.0.clone();
|
||||
Box::pin(async move { value })
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns one default `Vector` whose transform records the innermost context index in its x translation.
|
||||
struct IndexProbe;
|
||||
#[tokio::test]
|
||||
async fn repeat_on_points_test() {
|
||||
let context = OwnedContextImpl::default().into_context();
|
||||
let rect = RectangleNode::new(
|
||||
FutureWrapperNode(()),
|
||||
ExtractXyNode::new(ReadPositionNode::new(FutureWrapperNode(()), FutureWrapperNode(0)), FutureWrapperNode(XY::Y)),
|
||||
FutureWrapperNode(2_f64),
|
||||
FutureWrapperNode(false),
|
||||
FutureWrapperNode(0_f64),
|
||||
FutureWrapperNode(false),
|
||||
);
|
||||
|
||||
impl<Input: ExtractIndex> Node<Input> for IndexProbe {
|
||||
type Output = List<Vector>;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<List<Vector>> {
|
||||
let index = input.try_index().and_then(|mut levels| levels.next()).expect("repeat must push an index level");
|
||||
let mut list = List::new();
|
||||
list.push(Item::new_from_element(Vector::default()).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(index as f64, 0.))));
|
||||
GPoll::Final(list)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns one default `Vector` recording the innermost context position under `TEST_POSITION`.
|
||||
struct PositionProbe;
|
||||
|
||||
impl<Input: ExtractPosition> Node<Input> for PositionProbe {
|
||||
type Output = List<Vector>;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<List<Vector>> {
|
||||
let position = input.try_position().and_then(|mut positions| positions.next()).expect("repeat_on_points must push a position level");
|
||||
let mut list = List::new();
|
||||
list.push(Item::new_from_element(Vector::default()).with_attribute(TEST_POSITION, DAffine2::from_translation(position)));
|
||||
GPoll::Final(list)
|
||||
}
|
||||
}
|
||||
|
||||
fn single_default_vector() -> List<Vector> {
|
||||
List::new_from_element(Vector::default())
|
||||
}
|
||||
|
||||
fn row_translations(list: &List<Vector>, key: &str) -> Vec<DVec2> {
|
||||
(0..list.len()).map(|index| list.attribute_cloned_or_default::<DAffine2>(key, index).translation).collect()
|
||||
}
|
||||
|
||||
macro_rules! test_ctx {
|
||||
($ctx:ident, $cell:ident) => {
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let $ctx = ContextImpl::root(&scope);
|
||||
let $cell = StatusCell::default();
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_pushes_the_iteration_index_in_order() {
|
||||
test_ctx!(ctx, cell);
|
||||
|
||||
let x_translations = |values: [f64; 3]| values.map(|x| DVec2::new(x, 0.)).to_vec();
|
||||
|
||||
let forward = super::repeat(&ctx, LazyInput::new(&IndexProbe, &cell, 0), 3, false).unwrap();
|
||||
assert_eq!(row_translations(&forward, ATTR_TRANSFORM), x_translations([0., 1., 2.]));
|
||||
|
||||
let reversed = super::repeat(&ctx, LazyInput::new(&IndexProbe, &cell, 0), 3, true).unwrap();
|
||||
assert_eq!(row_translations(&reversed, ATTR_TRANSFORM), x_translations([2., 1., 0.]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_array_spaces_copies_along_the_direction() {
|
||||
test_ctx!(ctx, cell);
|
||||
let direction = DVec2::new(1.5, 0.);
|
||||
let count = 3;
|
||||
|
||||
let content = ValueNode(single_default_vector());
|
||||
let repeated = super::repeat_array(&ctx, LazyInput::new(&content, &cell, 0), direction, 0., count).unwrap();
|
||||
|
||||
assert_eq!(repeated.len(), count as usize);
|
||||
for (index, translation) in row_translations(&repeated, ATTR_TRANSFORM).into_iter().enumerate() {
|
||||
let expected = index as f64 * direction / (count - 1) as f64;
|
||||
assert!(translation.abs_diff_eq(expected, 1e-10), "copy {index}: {translation:?} != {expected:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_array_single_copy_stays_finite() {
|
||||
test_ctx!(ctx, cell);
|
||||
|
||||
let content = ValueNode(single_default_vector());
|
||||
let repeated = super::repeat_array(&ctx, LazyInput::new(&content, &cell, 0), DVec2::new(12., 10.), 45., 1).unwrap();
|
||||
|
||||
assert_eq!(repeated.len(), 1);
|
||||
let transform: DAffine2 = repeated.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
assert!(transform.abs_diff_eq(DAffine2::IDENTITY, 1e-10), "single copy must not divide by zero: {transform:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_radial_rotates_copies_around_the_center() {
|
||||
test_ctx!(ctx, cell);
|
||||
let (radius, count) = (5., 4);
|
||||
|
||||
let content = ValueNode(single_default_vector());
|
||||
let repeated = super::repeat_radial(&ctx, LazyInput::new(&content, &cell, 0), 0., radius, count).unwrap();
|
||||
|
||||
assert_eq!(repeated.len(), count as usize);
|
||||
for index in 0..count as usize {
|
||||
let transform: DAffine2 = repeated.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let expected = DAffine2::from_angle((TAU / count as f64) * index as f64) * DAffine2::from_translation(radius * DVec2::Y);
|
||||
assert!(transform.abs_diff_eq(expected, 1e-10), "copy {index}: {transform:?} != {expected:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_on_points_pushes_each_point_as_the_position() {
|
||||
test_ctx!(ctx, cell);
|
||||
let positions = [DVec2::new(40., 20.), DVec2::ONE, DVec2::new(-42., 9.), DVec2::new(10., 345.)];
|
||||
let points = List::new_from_element(Vector::from_subpath(Subpath::from_anchors(positions, false)));
|
||||
let generated = super::repeat_on_points(context, points, &rect, false).await;
|
||||
assert_eq!(generated.len(), positions.len());
|
||||
for (position, index) in positions.into_iter().zip(0..generated.len()) {
|
||||
let bounds = generated
|
||||
.element(index)
|
||||
.unwrap()
|
||||
.bounding_box_with_transform(generated.attribute_cloned_or_default(ATTR_TRANSFORM, index))
|
||||
.unwrap();
|
||||
assert!(position.abs_diff_eq((bounds[0] + bounds[1]) / 2., 1e-10));
|
||||
assert_eq!((bounds[1] - bounds[0]).x, position.y);
|
||||
}
|
||||
}
|
||||
|
||||
let generated = super::repeat_on_points(&ctx, points.clone(), LazyInput::new(&PositionProbe, &cell, 0), false).unwrap();
|
||||
assert_eq!(row_translations(&generated, ATTR_TRANSFORM), positions.to_vec());
|
||||
assert_eq!(row_translations(&generated, TEST_POSITION), positions.to_vec());
|
||||
#[tokio::test]
|
||||
async fn repeat() {
|
||||
let direction = DVec2::X * 1.5;
|
||||
let count = 3;
|
||||
let context = OwnedContextImpl::default().into_context();
|
||||
let repeated = super::repeat_array(
|
||||
context,
|
||||
&FutureWrapperNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))),
|
||||
direction,
|
||||
0.,
|
||||
count,
|
||||
)
|
||||
.await;
|
||||
let vector_list = vector_nodes::flatten_path(Footprint::default(), repeated).await;
|
||||
let vector = vector_list.element(0).unwrap();
|
||||
assert_eq!(vector.region_manipulator_groups().count(), 3);
|
||||
for (index, (_, manipulator_groups)) in vector.region_manipulator_groups().enumerate() {
|
||||
assert!((manipulator_groups[0].anchor - direction * index as f64 / (count - 1) as f64).length() < 1e-5);
|
||||
}
|
||||
}
|
||||
|
||||
let reversed = super::repeat_on_points(&ctx, points, LazyInput::new(&PositionProbe, &cell, 0), true).unwrap();
|
||||
let mut expected = positions.to_vec();
|
||||
expected.reverse();
|
||||
assert_eq!(row_translations(&reversed, ATTR_TRANSFORM), expected);
|
||||
#[tokio::test]
|
||||
async fn repeat_single_copy() {
|
||||
let context = OwnedContextImpl::default().into_context();
|
||||
let repeated = super::repeat_array(
|
||||
context,
|
||||
&FutureWrapperNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))),
|
||||
DVec2::new(12., 10.),
|
||||
45.,
|
||||
1,
|
||||
)
|
||||
.await;
|
||||
let vector_list = vector_nodes::flatten_path(Footprint::default(), repeated).await;
|
||||
let vector = vector_list.element(0).unwrap();
|
||||
assert_eq!(vector.region_manipulator_groups().count(), 1);
|
||||
|
||||
let (_, manipulator_groups) = vector.region_manipulator_groups().next().unwrap();
|
||||
let anchor = manipulator_groups[0].anchor;
|
||||
assert!(anchor.length() < 1e-5, "Expected the single copy to be untransformed, found anchor {anchor}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn repeat_transform_position() {
|
||||
let direction = DVec2::new(12., 10.);
|
||||
let count = 8;
|
||||
let context = OwnedContextImpl::default().into_context();
|
||||
let repeated = super::repeat_array(
|
||||
context,
|
||||
&FutureWrapperNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))),
|
||||
direction,
|
||||
0.,
|
||||
count,
|
||||
)
|
||||
.await;
|
||||
let vector_list = vector_nodes::flatten_path(Footprint::default(), repeated).await;
|
||||
let vector = vector_list.element(0).unwrap();
|
||||
assert_eq!(vector.region_manipulator_groups().count(), 8);
|
||||
for (index, (_, manipulator_groups)) in vector.region_manipulator_groups().enumerate() {
|
||||
assert!((manipulator_groups[0].anchor - direction * index as f64 / (count - 1) as f64).length() < 1e-5);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn repeat_radial() {
|
||||
let context = OwnedContextImpl::default().into_context();
|
||||
let repeated = super::repeat_radial(context, &FutureWrapperNode(vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))), 45., 4., 8).await;
|
||||
let vector_list = vector_nodes::flatten_path(Footprint::default(), repeated).await;
|
||||
let vector = vector_list.element(0).unwrap();
|
||||
assert_eq!(vector.region_manipulator_groups().count(), 8);
|
||||
|
||||
for (index, (_, manipulator_groups)) in vector.region_manipulator_groups().enumerate() {
|
||||
let expected_angle = (index as f64 + 1.) * 45.;
|
||||
|
||||
let center = (manipulator_groups[0].anchor + manipulator_groups[2].anchor) / 2.;
|
||||
let actual_angle = DVec2::Y.angle_to(center).to_degrees();
|
||||
|
||||
assert!((actual_angle - expected_angle).abs() % 360. < 1e-5, "Expected {expected_angle} found {actual_angle}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,11 +7,10 @@ mod text_context;
|
||||
mod to_path;
|
||||
|
||||
use convert_case::{Boundary, Converter, pattern};
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::registry::types::{SignedInteger, TextArea};
|
||||
use core_types::{Context, Ctx, DeriveCtx, ExtractVarArgs};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, OwnedContextImpl};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
@@ -769,25 +768,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.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn map_string(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
async fn map_string(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
strings: List<String>,
|
||||
#[expose]
|
||||
#[implementations(Context -> String)]
|
||||
mapped: impl Node<Context<'_>, Output = String>,
|
||||
) -> Result<List<String>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
mapped: impl Node<Context<'static>, Output = String>,
|
||||
) -> List<String> {
|
||||
let mut result = List::new();
|
||||
|
||||
for (i, row) in strings.into_iter().enumerate() {
|
||||
let string = row.into_element();
|
||||
let scoped = ctx.push_vararg(&string);
|
||||
let mapped_string = mapped.eval(&scoped.ctx().promoted(&spilled, i as u64))?;
|
||||
let owned_ctx = OwnedContextImpl::from(ctx.clone());
|
||||
let owned_ctx = owned_ctx.with_vararg(Box::new(string)).with_index(i);
|
||||
let mapped_string = mapped.eval(owned_ctx.into_context()).await;
|
||||
|
||||
result.push(Item::new_from_element(mapped_string));
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads the current string from within a **Map String** node's loop.
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use core::f64;
|
||||
use core_types::color::Color;
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::{List, ListDyn};
|
||||
use core_types::transform::{ApplyTransform, ScaleType, Transform};
|
||||
use core_types::{ATTR_TRANSFORM, Context, Ctx, DeriveCtx, InjectFootprint, ModifyFootprint};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, ModifyFootprint, OwnedContextImpl};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::Vector;
|
||||
@@ -12,8 +11,8 @@ use vector_types::GradientStops;
|
||||
|
||||
/// Applies the specified transform to the input value, which may be a graphic type or another transform.
|
||||
#[node_macro::node(category("Math: Transform"))]
|
||||
fn transform<T: ApplyTransform + 'static>(
|
||||
ctx: impl Ctx + DeriveCtx + ModifyFootprint,
|
||||
async fn transform<T: ApplyTransform + 'n + 'static>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll + ModifyFootprint,
|
||||
#[implementations(
|
||||
Context -> DAffine2,
|
||||
Context -> DVec2,
|
||||
@@ -25,24 +24,31 @@ fn transform<T: ApplyTransform + 'static>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
content: impl Node<Context<'_>, Output = T>,
|
||||
content: impl Node<Context<'static>, Output = T>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: DVec2,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_rotation")] rotation: f64,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_scale")]
|
||||
#[default(1., 1.)]
|
||||
scale: DVec2,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_skew")] skew: DVec2,
|
||||
) -> Result<T, Interrupt> {
|
||||
) -> T {
|
||||
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 matrix = trs * skew;
|
||||
|
||||
let transformed = ctx.modify_footprint(|footprint| footprint.apply_transform(&matrix));
|
||||
let mut transform_target = content.eval(&transformed.ctx())?;
|
||||
let footprint = ctx.try_footprint().copied();
|
||||
|
||||
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);
|
||||
|
||||
Ok(transform_target)
|
||||
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.
|
||||
@@ -108,7 +114,7 @@ fn replace_transform<T>(
|
||||
// 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.
|
||||
#[node_macro::node(category("Math: Transform"), path(core_types::vector))]
|
||||
fn extract_transform(_: impl Ctx, content: ListDyn) -> DAffine2 {
|
||||
async fn extract_transform(_: impl Ctx, content: ListDyn) -> DAffine2 {
|
||||
content.attribute::<DAffine2>(ATTR_TRANSFORM, 0).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
|
||||
@@ -411,11 +411,11 @@ mod tests {
|
||||
#[test]
|
||||
fn isometric_grid_test() {
|
||||
// Doesn't crash with weird angles
|
||||
grid(&(), (), GridType::Isometric, 0., 5, 5, (0., 0.).into());
|
||||
grid(&(), (), GridType::Isometric, 90., 5, 5, (90., 90.).into());
|
||||
grid((), (), GridType::Isometric, 0., 5, 5, (0., 0.).into());
|
||||
grid((), (), GridType::Isometric, 90., 5, 5, (90., 90.).into());
|
||||
|
||||
// Works properly
|
||||
let grid = grid(&(), (), GridType::Isometric, 10., 5, 5, (30., 30.).into());
|
||||
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (30., 30.).into());
|
||||
assert_eq!(grid.element(0).unwrap().point_domain.ids().len(), 5 * 5);
|
||||
assert_eq!(grid.element(0).unwrap().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
|
||||
for (_, bezier, _, _) in grid.element(0).unwrap().segment_bezier_iter() {
|
||||
@@ -430,7 +430,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn skew_isometric_grid_test() {
|
||||
let grid = grid(&(), (), GridType::Isometric, 10., 5, 5, (40., 30.).into());
|
||||
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (40., 30.).into());
|
||||
assert_eq!(grid.element(0).unwrap().point_domain.ids().len(), 5 * 5);
|
||||
assert_eq!(grid.element(0).unwrap().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
|
||||
for (_, bezier, _, _) in grid.element(0).unwrap().segment_bezier_iter() {
|
||||
@@ -443,7 +443,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn qr_code_test() {
|
||||
let qr = qr_code(&(), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
|
||||
let qr = qr_code((), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
|
||||
assert!(qr.element(0).unwrap().point_domain.ids().len() > 0);
|
||||
assert!(qr.element(0).unwrap().segment_domain.ids().len() > 0);
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
#[node_macro::node(category(""))]
|
||||
fn path_modify(_ctx: impl Ctx, mut vector: List<Vector>, modification: Box<VectorModification>, node_path: List<NodeId>) -> List<Vector> {
|
||||
async fn path_modify(_ctx: impl Ctx, mut vector: List<Vector>, modification: Box<VectorModification>, node_path: List<NodeId>) -> List<Vector> {
|
||||
use core_types::list::Item;
|
||||
|
||||
if vector.is_empty() {
|
||||
@@ -35,7 +35,7 @@ fn path_modify(_ctx: impl Ctx, mut vector: List<Vector>, modification: Box<Vecto
|
||||
|
||||
/// Applies the vector path's local transformation to its geometry and resets the transform to the identity.
|
||||
#[node_macro::node(category("Vector"))]
|
||||
fn apply_transform(_ctx: impl Ctx, mut vector: List<Vector>) -> List<Vector> {
|
||||
async fn apply_transform(_ctx: impl Ctx, mut vector: List<Vector>) -> List<Vector> {
|
||||
let (elements, transforms) = vector.element_and_attribute_slices_mut::<DAffine2>(ATTR_TRANSFORM);
|
||||
for (element, transform) in elements.iter_mut().zip(transforms.iter_mut()) {
|
||||
for (_, point) in element.point_domain.positions_mut() {
|
||||
|
||||
@@ -3,14 +3,13 @@ use core::f64::consts::{PI, TAU};
|
||||
use core::hash::{Hash, Hasher};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, ItemAttributeValues, List, ListDyn};
|
||||
use core_types::registry::types::{Angle, Length, Multiplier, Percentage, PixelLength, Progression, SeedValue};
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::uuid::NodeId;
|
||||
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, Color, Ctx,
|
||||
DeriveCtx,
|
||||
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,
|
||||
Color, Context, Ctx, ExtractAll, OwnedContextImpl,
|
||||
};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::Vector;
|
||||
@@ -89,7 +88,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.
|
||||
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector))]
|
||||
fn assign_colors<T>(
|
||||
async fn assign_colors<T>(
|
||||
_: impl Ctx,
|
||||
/// The content with vector paths to apply the fill and/or stroke style to.
|
||||
#[implementations(List<Graphic>, List<Vector>)]
|
||||
@@ -116,7 +115,7 @@ fn assign_colors<T>(
|
||||
repeat_every: u32,
|
||||
) -> T
|
||||
where
|
||||
T: VectorListIterMut + Send,
|
||||
T: VectorListIterMut + 'n + Send,
|
||||
{
|
||||
let Some(row) = gradient.into_iter().next() else { return content };
|
||||
|
||||
@@ -157,7 +156,7 @@ where
|
||||
|
||||
/// 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"))]
|
||||
fn fill<V: VectorListIterMut + Send, F: IntoGraphicList + Send + 'static>(
|
||||
async fn fill<V: VectorListIterMut + 'n + Send, F: IntoGraphicList + 'n + Send + 'static>(
|
||||
_: impl Ctx,
|
||||
/// The content with vector paths to apply the fill style to.
|
||||
#[implementations(
|
||||
@@ -252,7 +251,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.
|
||||
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("stroke_properties"))]
|
||||
fn stroke<V, L: IntoF64Vec, P: IntoGraphicList + Send + 'static>(
|
||||
async fn stroke<V, L: IntoF64Vec, P: IntoGraphicList + 'n + Send + 'static>(
|
||||
_: impl Ctx,
|
||||
/// The content with vector paths to apply the stroke style to.
|
||||
#[implementations(
|
||||
@@ -324,7 +323,7 @@ fn stroke<V, L: IntoF64Vec, P: IntoGraphicList + Send + 'static>(
|
||||
dash_offset: f64,
|
||||
) -> List<V>
|
||||
where
|
||||
List<V>: VectorListIterMut + Send,
|
||||
List<V>: VectorListIterMut + 'n + Send,
|
||||
{
|
||||
let dash_lengths = dash_lengths.into_vec().into_iter().map(|length| length.max(0.)).collect();
|
||||
|
||||
@@ -357,7 +356,7 @@ where
|
||||
}
|
||||
|
||||
#[node_macro::node(name("Copy to Points"), category("Repeat"), path(core_types::vector))]
|
||||
fn copy_to_points<I: Send + Clone>(
|
||||
async fn copy_to_points<I: 'n + Send + Clone>(
|
||||
_: impl Ctx,
|
||||
points: List<Vector>,
|
||||
/// Artwork to be copied and placed at each point.
|
||||
@@ -441,7 +440,7 @@ fn copy_to_points<I: Send + Clone>(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn round_corners(
|
||||
async fn round_corners(
|
||||
_: impl Ctx,
|
||||
source: List<Vector>,
|
||||
#[hard(0..)]
|
||||
@@ -778,7 +777,7 @@ pub mod extrude_algorithms {
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn extrude(_: impl Ctx, mut source: List<Vector>, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) -> List<Vector> {
|
||||
async fn extrude(_: impl Ctx, mut source: List<Vector>, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) -> List<Vector> {
|
||||
for vector in source.iter_element_values_mut() {
|
||||
extrude_algorithms::extrude(vector, direction, joining_algorithm);
|
||||
}
|
||||
@@ -786,7 +785,7 @@ fn extrude(_: impl Ctx, mut source: List<Vector>, direction: DVec2, joining_algo
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn box_warp(_: impl Ctx, content: List<Vector>, #[expose] rectangle: List<Vector>) -> List<Vector> {
|
||||
async 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 target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
|
||||
@@ -871,7 +870,7 @@ fn bilinear_interpolate(t: DVec2, quad: &[DVec2; 4]) -> DVec2 {
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
|
||||
fn pack_strips<T: Send + Clone>(
|
||||
async fn pack_strips<T: 'n + Send + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
@@ -992,7 +991,7 @@ where
|
||||
|
||||
/// 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))]
|
||||
fn auto_tangents(
|
||||
async fn auto_tangents(
|
||||
_: impl Ctx,
|
||||
source: List<Vector>,
|
||||
/// The amount of spread for the auto-tangents, from 0 (sharp corner) to 1 (full spread).
|
||||
@@ -1146,7 +1145,7 @@ fn auto_tangents(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn bounding_box(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
async fn bounding_box(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
content
|
||||
.into_iter()
|
||||
.map(|mut row| {
|
||||
@@ -1171,7 +1170,7 @@ fn bounding_box(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
|
||||
fn dimensions(_: impl Ctx, content: List<Vector>) -> DVec2 {
|
||||
async fn dimensions(_: impl Ctx, content: List<Vector>) -> DVec2 {
|
||||
(0..content.len())
|
||||
.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)])
|
||||
@@ -1187,7 +1186,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.
|
||||
#[node_macro::node(category("Vector"), name("Points to Polyline"), path(core_types::vector))]
|
||||
fn points_to_polyline(_: impl Ctx, mut points: List<Vector>, #[default(true)] closed: bool) -> List<Vector> {
|
||||
async fn points_to_polyline(_: impl Ctx, mut points: List<Vector>, #[default(true)] closed: bool) -> List<Vector> {
|
||||
for vector in points.iter_element_values_mut() {
|
||||
let mut segment_domain = SegmentDomain::new();
|
||||
let mut next_id = SegmentId::ZERO;
|
||||
@@ -1215,7 +1214,7 @@ fn points_to_polyline(_: impl Ctx, mut points: List<Vector>, #[default(true)] cl
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector), properties("offset_path_properties"))]
|
||||
fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: StrokeJoin, #[default(4.)] miter_limit: f64) -> List<Vector> {
|
||||
async fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: StrokeJoin, #[default(4.)] miter_limit: f64) -> List<Vector> {
|
||||
content
|
||||
.into_iter()
|
||||
.map(|mut row| {
|
||||
@@ -1259,7 +1258,7 @@ fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: StrokeJo
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn solidify_stroke<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
async 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
|
||||
|
||||
let graphic_list = content.into_graphic_list();
|
||||
@@ -1367,7 +1366,7 @@ fn solidify_stroke<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graph
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
async fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
content
|
||||
.into_iter()
|
||||
.flat_map(|row| {
|
||||
@@ -1398,7 +1397,7 @@ 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.
|
||||
#[node_macro::node(name("Path is Closed"), category("Vector: Measure"), path(core_types::vector))]
|
||||
fn path_is_closed(
|
||||
async fn path_is_closed(
|
||||
_: impl Ctx,
|
||||
/// The vector content whose subpaths are inspected.
|
||||
content: List<Vector>,
|
||||
@@ -1413,25 +1412,25 @@ fn path_is_closed(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector"), path(graphene_core::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();
|
||||
async fn map_points(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: List<Vector>, mapped: impl Node<Context<'static>, Output = DVec2>) -> List<Vector> {
|
||||
let mut content = content;
|
||||
let mut index = 0;
|
||||
|
||||
for vector in content.iter_element_values_mut() {
|
||||
for (_, position) in vector.point_domain.positions_mut() {
|
||||
let scoped = ctx.push_position(*position);
|
||||
*position = mapped.eval(&scoped.ctx().promoted(&spilled, index))?;
|
||||
let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(*position);
|
||||
index += 1;
|
||||
|
||||
*position = mapped.eval(owned_ctx.into_context()).await;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(content)
|
||||
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.
|
||||
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
|
||||
pub fn flatten_path<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
pub async fn flatten_path<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
let graphic_list = content.into_graphic_list();
|
||||
let flattened = graphic_list.clone().into_flattened_list::<Vector>();
|
||||
|
||||
@@ -1487,7 +1486,7 @@ pub fn flatten_path<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Grap
|
||||
|
||||
/// 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)]
|
||||
fn sample_polyline(
|
||||
async fn sample_polyline(
|
||||
_: impl Ctx,
|
||||
content: List<Vector>,
|
||||
spacing: PointSpacingType,
|
||||
@@ -1573,7 +1572,7 @@ fn sample_polyline(
|
||||
|
||||
/// 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))]
|
||||
fn simplify(
|
||||
async fn simplify(
|
||||
_: impl Ctx,
|
||||
/// The vector paths to simplify.
|
||||
content: List<Vector>,
|
||||
@@ -1617,7 +1616,7 @@ 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.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn decimate(
|
||||
async fn decimate(
|
||||
_: impl Ctx,
|
||||
/// The vector paths to decimate.
|
||||
content: List<Vector>,
|
||||
@@ -1745,7 +1744,7 @@ 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.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(graphene_core::vector))]
|
||||
fn cut_path(
|
||||
async fn cut_path(
|
||||
_: impl Ctx,
|
||||
/// The path to insert a cut into.
|
||||
mut content: List<Vector>,
|
||||
@@ -1796,7 +1795,7 @@ fn cut_path(
|
||||
|
||||
/// Cuts path segments into separate disconnected pieces where each is a distinct subpath.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn cut_segments(_: impl Ctx, mut content: List<Vector>) -> List<Vector> {
|
||||
async 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
|
||||
for vector in content.iter_element_values_mut() {
|
||||
let points_count = vector.point_domain.ids().len();
|
||||
@@ -1855,7 +1854,7 @@ 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.
|
||||
#[node_macro::node(name("Position on Path"), category("Vector: Measure"), path(graphene_core::vector))]
|
||||
fn position_on_path(
|
||||
async fn position_on_path(
|
||||
_: impl Ctx,
|
||||
/// The path to traverse.
|
||||
content: List<Vector>,
|
||||
@@ -1893,7 +1892,7 @@ 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.
|
||||
#[node_macro::node(name("Tangent on Path"), category("Vector: Measure"), path(graphene_core::vector))]
|
||||
fn tangent_on_path(
|
||||
async fn tangent_on_path(
|
||||
_: impl Ctx,
|
||||
/// The path to traverse.
|
||||
content: List<Vector>,
|
||||
@@ -1941,7 +1940,7 @@ fn tangent_on_path(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector), memoize)]
|
||||
fn scatter_points(
|
||||
async fn scatter_points(
|
||||
_: impl Ctx,
|
||||
content: List<Vector>,
|
||||
#[unit(" px")]
|
||||
@@ -1991,7 +1990,7 @@ fn scatter_points(
|
||||
}
|
||||
|
||||
#[node_macro::node(name("Spline"), category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn spline(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
async fn spline(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
content
|
||||
.into_iter()
|
||||
.filter_map(|mut row| {
|
||||
@@ -2091,7 +2090,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.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn jitter_points(
|
||||
async fn jitter_points(
|
||||
_: impl Ctx,
|
||||
/// The vector geometry with points to be jittered.
|
||||
content: List<Vector>,
|
||||
@@ -2141,7 +2140,7 @@ fn jitter_points(
|
||||
/// 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.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn offset_points(
|
||||
async fn offset_points(
|
||||
_: impl Ctx,
|
||||
/// The vector geometry with points to be offset.
|
||||
content: List<Vector>,
|
||||
@@ -2178,7 +2177,7 @@ 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.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn morph<I: IntoGraphicList>(
|
||||
async fn morph<I: IntoGraphicList>(
|
||||
_: impl Ctx,
|
||||
/// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements.
|
||||
#[implementations(List<Graphic>, List<Vector>)]
|
||||
@@ -3125,19 +3124,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: (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))]
|
||||
fn count_elements(_: impl Ctx, content: ListDyn) -> f64 {
|
||||
async fn count_elements(_: impl Ctx, content: ListDyn) -> f64 {
|
||||
content.len() as f64
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), path(graphene_core::vector))]
|
||||
fn count_points(_: impl Ctx, content: List<Vector>) -> f64 {
|
||||
async fn count_points(_: impl Ctx, content: List<Vector>) -> f64 {
|
||||
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.
|
||||
/// If no value exists at that index, the position (0, 0) is returned.
|
||||
#[node_macro::node(category("Vector: Measure"), path(graphene_core::vector))]
|
||||
fn index_points(
|
||||
async fn index_points(
|
||||
_: impl Ctx,
|
||||
/// The vector element or elements containing the anchor points to be retrieved.
|
||||
content: List<Vector>,
|
||||
@@ -3171,7 +3170,7 @@ fn index_points(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
|
||||
fn path_length(_: impl Ctx, source: List<Vector>) -> f64 {
|
||||
async fn path_length(_: impl Ctx, source: List<Vector>) -> f64 {
|
||||
(0..source.len())
|
||||
.map(|index| {
|
||||
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
@@ -3190,24 +3189,26 @@ fn path_length(_: impl Ctx, source: List<Vector>) -> f64 {
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
|
||||
fn area(ctx: impl Ctx + DeriveCtx, content: impl Node<Context<'_>, Output = List<Vector>>) -> Result<f64, Interrupt> {
|
||||
let vector = content.eval(&ctx.with_footprint(&Footprint::DEFAULT))?;
|
||||
async fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Context<'static>, Output = List<Vector>>) -> f64 {
|
||||
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
|
||||
let vector = content.eval(new_ctx).await;
|
||||
|
||||
Ok((0..vector.len())
|
||||
(0..vector.len())
|
||||
.map(|index| {
|
||||
let transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let area_scale = transform.matrix2.determinant().abs();
|
||||
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))]
|
||||
fn centroid(ctx: impl Ctx + DeriveCtx, content: impl Node<Context<'_>, Output = List<Vector>>, centroid_type: CentroidType) -> Result<DVec2, Interrupt> {
|
||||
let vector = content.eval(&ctx.with_footprint(&Footprint::DEFAULT))?;
|
||||
async fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Context<'static>, Output = List<Vector>>, centroid_type: CentroidType) -> DVec2 {
|
||||
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
|
||||
let vector = content.eval(new_ctx).await;
|
||||
|
||||
if vector.is_empty() {
|
||||
return Ok(DVec2::ZERO);
|
||||
return DVec2::ZERO;
|
||||
}
|
||||
|
||||
// All subpath centroid positions added together as if they were vectors from the origin.
|
||||
@@ -3233,7 +3234,7 @@ fn centroid(ctx: impl Ctx + DeriveCtx, content: impl Node<Context<'_>, Output =
|
||||
}
|
||||
|
||||
if sum > 0. {
|
||||
Ok(centroid / sum)
|
||||
centroid / sum
|
||||
}
|
||||
// Without a summed denominator, return the average of all positions instead
|
||||
else {
|
||||
@@ -3254,17 +3255,31 @@ fn centroid(ctx: impl Ctx + DeriveCtx, content: impl Node<Context<'_>, Output =
|
||||
.inspect(|_| count += 1)
|
||||
.sum::<DVec2>();
|
||||
|
||||
if count != 0 { Ok(summed_positions / (count as f64)) } else { Ok(DVec2::ZERO) }
|
||||
if count != 0 { summed_positions / (count as f64) } else { DVec2::ZERO }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use core_types::Node;
|
||||
use kurbo::{CubicBez, Ellipse, Point, Rect};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use vector_types::vector::algorithms::bezpath_algorithms::{TValue, trim_pathseg};
|
||||
use vector_types::vector::misc::pathseg_abs_diff_eq;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FutureWrapperNode<T: Clone>(T);
|
||||
|
||||
impl<'i, T: 'i + Clone + Send> Node<'i, Footprint> for FutureWrapperNode<T> {
|
||||
type Output = Pin<Box<dyn Future<Output = T> + 'i + Send>>;
|
||||
fn eval(&'i self, _input: Footprint) -> Self::Output {
|
||||
let value = self.0.clone();
|
||||
Box::pin(async move { value })
|
||||
}
|
||||
}
|
||||
|
||||
fn vector_node_from_bezpath(bezpath: BezPath) -> List<Vector> {
|
||||
List::new_from_element(Vector::from_bezpath(bezpath))
|
||||
}
|
||||
@@ -3275,9 +3290,9 @@ mod test {
|
||||
Item::new_from_element(row).with_attribute(ATTR_TRANSFORM, transform)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounding_box() {
|
||||
let bounding_box = super::bounding_box(&(), vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY)));
|
||||
#[tokio::test]
|
||||
async fn bounding_box() {
|
||||
let bounding_box = super::bounding_box((), vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))).await;
|
||||
let bounding_box = bounding_box.element(0).unwrap();
|
||||
assert_eq!(bounding_box.region_manipulator_groups().count(), 1);
|
||||
let manipulator_groups_anchors = bounding_box
|
||||
@@ -3295,7 +3310,7 @@ mod test {
|
||||
let square = Vector::from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY));
|
||||
let mut square = List::new_from_element(square);
|
||||
square.with_attribute_mut_or_default(ATTR_TRANSFORM, 0, |t: &mut DAffine2| *t *= DAffine2::from_angle(std::f64::consts::FRAC_PI_4));
|
||||
let bounding_box = super::bounding_box(&(), square);
|
||||
let bounding_box = BoundingBoxNode { content: FutureWrapperNode(square) }.eval(Footprint::default()).await;
|
||||
let bounding_box = bounding_box.element(0).unwrap();
|
||||
assert_eq!(bounding_box.region_manipulator_groups().count(), 1);
|
||||
let manipulator_groups_anchors = bounding_box
|
||||
@@ -3312,15 +3327,15 @@ mod test {
|
||||
assert_eq!(manipulator_groups_anchors[i], expected_bounding_box[i]);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn copy_to_points() {
|
||||
#[tokio::test]
|
||||
async fn copy_to_points() {
|
||||
let points = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY);
|
||||
let element = Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY);
|
||||
|
||||
let expected_points = Vector::from_bezpath(points.clone()).point_domain.positions().to_vec();
|
||||
|
||||
let copy_to_points = super::copy_to_points(&Footprint::default(), vector_node_from_bezpath(points), vector_node_from_bezpath(element), 1., 1., 0., 0, 0., 0);
|
||||
let flatten_path = super::flatten_path(&Footprint::default(), copy_to_points);
|
||||
let copy_to_points = super::copy_to_points(Footprint::default(), vector_node_from_bezpath(points), vector_node_from_bezpath(element), 1., 1., 0., 0, 0., 0).await;
|
||||
let flatten_path = super::flatten_path(Footprint::default(), copy_to_points).await;
|
||||
let flattened_copy_to_points = flatten_path.element(0).unwrap();
|
||||
|
||||
assert_eq!(flattened_copy_to_points.region_manipulator_groups().count(), expected_points.len());
|
||||
@@ -3335,34 +3350,35 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_polyline() {
|
||||
#[tokio::test]
|
||||
async fn sample_polyline() {
|
||||
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
|
||||
let sample_polyline = super::sample_polyline(&Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 30., 0, 0., 0., false);
|
||||
let sample_polyline = super::sample_polyline(Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 30., 0, 0., 0., false).await;
|
||||
let sample_polyline = sample_polyline.element(0).unwrap();
|
||||
assert_eq!(sample_polyline.point_domain.positions().len(), 4);
|
||||
for (pos, expected) in sample_polyline.point_domain.positions().iter().zip([DVec2::X * 0., DVec2::X * 30., DVec2::X * 60., DVec2::X * 90.]) {
|
||||
assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn sample_polyline_adaptive_spacing() {
|
||||
#[tokio::test]
|
||||
async fn sample_polyline_adaptive_spacing() {
|
||||
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
|
||||
let sample_polyline = super::sample_polyline(&Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 18., 0, 45., 10., true);
|
||||
let sample_polyline = super::sample_polyline(Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 18., 0, 45., 10., true).await;
|
||||
let sample_polyline = sample_polyline.element(0).unwrap();
|
||||
assert_eq!(sample_polyline.point_domain.positions().len(), 4);
|
||||
for (pos, expected) in sample_polyline.point_domain.positions().iter().zip([DVec2::X * 45., DVec2::X * 60., DVec2::X * 75., DVec2::X * 90.]) {
|
||||
assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn poisson() {
|
||||
#[tokio::test]
|
||||
async fn poisson() {
|
||||
let poisson_points = super::scatter_points(
|
||||
&Footprint::default(),
|
||||
Footprint::default(),
|
||||
vector_node_from_bezpath(Ellipse::from_rect(Rect::new(-50., -50., 50., 50.)).to_path(DEFAULT_ACCURACY)),
|
||||
10. * std::f64::consts::SQRT_2,
|
||||
0,
|
||||
);
|
||||
)
|
||||
.await;
|
||||
let poisson_points = poisson_points.element(0).unwrap();
|
||||
assert!(
|
||||
(20..=40).contains(&poisson_points.point_domain.positions().len()),
|
||||
@@ -3373,33 +3389,33 @@ mod test {
|
||||
assert!(point.length() < 50. + 1., "Expected point in circle {point}")
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn path_length() {
|
||||
#[tokio::test]
|
||||
async fn path_length() {
|
||||
let bezpath = Rect::new(100., 100., 201., 201.).to_path(DEFAULT_ACCURACY);
|
||||
let transform = DAffine2::from_scale(DVec2::new(2., 2.));
|
||||
let row = create_vector_item(bezpath, transform);
|
||||
let list = (0..5).map(|_| row.clone()).collect::<List<Vector>>();
|
||||
|
||||
let length = super::path_length(&Footprint::default(), list);
|
||||
let length = super::path_length(Footprint::default(), list).await;
|
||||
|
||||
// 101 (each rectangle edge length) * 4 (rectangle perimeter) * 2 (scale) * 5 (number of rows)
|
||||
assert_eq!(length, 101. * 4. * 2. * 5.);
|
||||
}
|
||||
#[test]
|
||||
fn spline() {
|
||||
let spline = super::spline(&Footprint::default(), vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)));
|
||||
#[tokio::test]
|
||||
async fn spline() {
|
||||
let spline = super::spline(Footprint::default(), vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY))).await;
|
||||
let spline = spline.element(0).unwrap();
|
||||
assert_eq!(spline.stroke_bezpath_iter().count(), 1);
|
||||
assert_eq!(spline.point_domain.positions(), &[DVec2::ZERO, DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)]);
|
||||
}
|
||||
#[test]
|
||||
fn morph() {
|
||||
#[tokio::test]
|
||||
async fn morph() {
|
||||
let mut rectangles = vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
|
||||
let mut second_rectangle = rectangles.clone_item(0).unwrap();
|
||||
*second_rectangle.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM) *= DAffine2::from_translation((-100., -100.).into());
|
||||
rectangles.push(second_rectangle);
|
||||
|
||||
let morphed = super::morph(&Footprint::default(), rectangles, 0.5, false, InterpolationDistribution::default(), List::default());
|
||||
let morphed = super::morph(Footprint::default(), rectangles, 0.5, false, InterpolationDistribution::default(), List::default()).await;
|
||||
let morphed_element = morphed.element(0).unwrap();
|
||||
// Geometry stays in local space (original rectangle coordinates)
|
||||
assert_eq!(
|
||||
@@ -3410,8 +3426,8 @@ mod test {
|
||||
assert!((morphed.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0).translation - DVec2::new(-50., -50.)).length() < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn morph_interpolates_fill() {
|
||||
#[tokio::test]
|
||||
async fn morph_interpolates_fill() {
|
||||
let rect = || {
|
||||
let mut v = Vector::default();
|
||||
v.append_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
|
||||
@@ -3428,7 +3444,7 @@ mod test {
|
||||
let mut content = List::new_from_item(item_a);
|
||||
content.push(item_b);
|
||||
|
||||
let morphed = super::morph(&Footprint::default(), content, 0.5, false, InterpolationDistribution::default(), List::default());
|
||||
let morphed = super::morph(Footprint::default(), content, 0.5, false, InterpolationDistribution::default(), List::default()).await;
|
||||
|
||||
let fill = graphic_list_at(&morphed, 0, ATTR_FILL).expect("Morph should keep the fill paint at the midpoint");
|
||||
|
||||
@@ -3455,10 +3471,10 @@ mod test {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bevel_rect() {
|
||||
#[tokio::test]
|
||||
async fn bevel_rect() {
|
||||
let source = Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY);
|
||||
let beveled = super::bevel(&Footprint::default(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
|
||||
let beveled = super::bevel(Footprint::default(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
|
||||
let beveled = beveled.element(0).unwrap();
|
||||
|
||||
assert_eq!(beveled.point_domain.positions().len(), 8);
|
||||
@@ -3477,8 +3493,8 @@ mod test {
|
||||
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(0., 90.))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bevel_open_curve() {
|
||||
#[tokio::test]
|
||||
async fn bevel_open_curve() {
|
||||
let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.)));
|
||||
|
||||
let mut source = BezPath::new();
|
||||
@@ -3486,7 +3502,7 @@ mod test {
|
||||
source.line_to(Point::ZERO);
|
||||
source.push(curve.as_path_el());
|
||||
|
||||
let beveled = super::bevel(&(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
|
||||
let beveled = super::bevel((), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
|
||||
let beveled = beveled.element(0).unwrap();
|
||||
|
||||
assert_eq!(beveled.point_domain.positions().len(), 4);
|
||||
@@ -3501,8 +3517,8 @@ mod test {
|
||||
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bevel_with_transform() {
|
||||
#[tokio::test]
|
||||
async fn bevel_with_transform() {
|
||||
let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.)));
|
||||
|
||||
let mut source = BezPath::new();
|
||||
@@ -3515,7 +3531,7 @@ mod test {
|
||||
|
||||
vector_list.set_attribute(ATTR_TRANSFORM, 0, DAffine2::from_scale_angle_translation(DVec2::splat(10.), 1., DVec2::new(99., 77.)));
|
||||
|
||||
let beveled = super::bevel(&(), List::new_from_element(vector), 2_f64.sqrt() * 10.);
|
||||
let beveled = super::bevel((), List::new_from_element(vector), 2_f64.sqrt() * 10.);
|
||||
let beveled = beveled.element(0).unwrap();
|
||||
|
||||
assert_eq!(beveled.point_domain.positions().len(), 4);
|
||||
@@ -3530,15 +3546,15 @@ mod test {
|
||||
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bevel_too_high() {
|
||||
#[tokio::test]
|
||||
async fn bevel_too_high() {
|
||||
let mut source = BezPath::new();
|
||||
source.move_to(Point::ZERO);
|
||||
source.line_to(Point::new(100., 0.));
|
||||
source.line_to(Point::new(100., 100.));
|
||||
source.line_to(Point::new(0., 100.));
|
||||
|
||||
let beveled = super::bevel(&Footprint::default(), vector_node_from_bezpath(source), 999.);
|
||||
let beveled = super::bevel(Footprint::default(), vector_node_from_bezpath(source), 999.);
|
||||
let beveled = beveled.element(0).unwrap();
|
||||
|
||||
assert_eq!(beveled.point_domain.positions().len(), 6);
|
||||
@@ -3554,15 +3570,15 @@ mod test {
|
||||
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bevel_repeated_point() {
|
||||
#[tokio::test]
|
||||
async fn bevel_repeated_point() {
|
||||
let line = PathSeg::Line(Line::new(Point::ZERO, Point::new(100., 0.)));
|
||||
let point = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::ZERO, Point::ZERO, Point::new(100., 0.)));
|
||||
let curve = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::new(110., 0.), Point::new(110., 200.), Point::new(200., 0.)));
|
||||
|
||||
let subpath = BezPath::from_path_segments([line, point, curve].into_iter());
|
||||
|
||||
let beveled_list = super::bevel(&Footprint::default(), vector_node_from_bezpath(subpath), 5.);
|
||||
let beveled_list = super::bevel(Footprint::default(), vector_node_from_bezpath(subpath), 5.);
|
||||
let beveled = beveled_list.element(0).unwrap();
|
||||
|
||||
assert_eq!(beveled.point_domain.positions().len(), 6);
|
||||
|
||||
@@ -116,19 +116,13 @@ impl Preprocessor {
|
||||
for (id, metadata) in core_types::registry::NODE_METADATA.lock().unwrap().iter() {
|
||||
let id = id.clone();
|
||||
|
||||
let NodeMetadata {
|
||||
fields,
|
||||
memoize,
|
||||
inject_scope,
|
||||
async_source_fields,
|
||||
..
|
||||
} = metadata;
|
||||
let NodeMetadata { fields, memoize, inject_scope, .. } = metadata;
|
||||
let Some(implementations) = node_registry.get(&id) else { continue };
|
||||
let valid_call_args: HashSet<_> = implementations.iter().map(|entry| entry.io.call_argument.clone()).collect();
|
||||
let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
|
||||
let valid_call_args: HashSet<_> = implementations.iter().map(|(_, node_io)| node_io.call_argument.clone()).collect();
|
||||
let first_node_io = implementations.first().map(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() });
|
||||
let mut node_io_types = vec![HashSet::new(); fields.len()];
|
||||
for entry in implementations.iter() {
|
||||
for (i, ty) in entry.io.inputs.iter().enumerate() {
|
||||
for (_, node_io) in implementations.iter() {
|
||||
for (i, ty) in node_io.inputs.iter().enumerate() {
|
||||
node_io_types[i].insert(ty.clone());
|
||||
}
|
||||
}
|
||||
@@ -137,20 +131,16 @@ impl Preprocessor {
|
||||
input_type = &const { generic!(D) };
|
||||
}
|
||||
|
||||
let mut inputs: Vec<_> = node_inputs(fields, first_node_io);
|
||||
let wrapper_input_count = inputs.len() - if *async_source_fields { 2 } else { 0 };
|
||||
|
||||
// The injected fields must not surface as wrapper inputs, and the `_source` reflection must sit on
|
||||
// the kernel itself so the source id lands on a node that survives flattening.
|
||||
let injected_inputs = inputs.split_off(wrapper_input_count);
|
||||
let network_inputs = (0..wrapper_input_count).map(|i| NodeInput::node(NodeId(i as u64), 0)).chain(injected_inputs).collect();
|
||||
let inputs: Vec<_> = node_inputs(fields, first_node_io);
|
||||
let input_count = inputs.len();
|
||||
let network_inputs = (0..input_count).map(|i| NodeInput::node(NodeId(i as u64), 0)).collect();
|
||||
|
||||
let passthrough_node = ops::passthrough::IDENTIFIER;
|
||||
|
||||
let mut generated_nodes = 0;
|
||||
let mut nodes: HashMap<_, _, _> = node_io_types
|
||||
.iter()
|
||||
.take(wrapper_input_count)
|
||||
.take(input_count)
|
||||
.enumerate()
|
||||
.map(|(i, inputs)| {
|
||||
(
|
||||
@@ -195,7 +185,7 @@ impl Preprocessor {
|
||||
})
|
||||
.collect();
|
||||
|
||||
if generated_nodes == 0 && !memoize && !inject_scope && !async_source_fields {
|
||||
if generated_nodes == 0 && !memoize && !inject_scope {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -209,14 +199,13 @@ impl Preprocessor {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let main_node_id = NodeId(wrapper_input_count as u64);
|
||||
nodes.insert(main_node_id, document_node);
|
||||
nodes.insert(NodeId(input_count as u64), document_node);
|
||||
|
||||
// If memoize is requested, append a Memoize node after the main node and redirect the export through it
|
||||
let export_node_id = if *memoize {
|
||||
let memoize_node_id = NodeId(wrapper_input_count as u64 + 1);
|
||||
let memoize_node_id = NodeId(input_count as u64 + 1);
|
||||
let memoize_node = DocumentNode {
|
||||
inputs: vec![NodeInput::node(main_node_id, 0)],
|
||||
inputs: vec![NodeInput::node(NodeId(input_count as u64), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::memo::memoize::IDENTIFIER.clone()),
|
||||
visible: true,
|
||||
..Default::default()
|
||||
@@ -224,7 +213,7 @@ impl Preprocessor {
|
||||
nodes.insert(memoize_node_id, memoize_node);
|
||||
memoize_node_id
|
||||
} else {
|
||||
main_node_id
|
||||
NodeId(input_count as u64)
|
||||
};
|
||||
|
||||
let node = DocumentNode {
|
||||
@@ -249,7 +238,7 @@ impl Preprocessor {
|
||||
// If `inject_scope` is requested, prepare the proto node template and type info needed
|
||||
if *inject_scope
|
||||
&& let Some(implementations) = node_registry.get(&id)
|
||||
&& let Some(node_io) = implementations.first().map(|entry| &entry.io)
|
||||
&& let Some((_, node_io)) = implementations.first()
|
||||
{
|
||||
let template = DocumentNode {
|
||||
inputs: node_inputs(fields, node_io),
|
||||
@@ -290,7 +279,6 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp
|
||||
}
|
||||
}
|
||||
RegistryValueSource::Scope(data) => return NodeInput::scope(*data),
|
||||
RegistryValueSource::SourceId => return NodeInput::Reflection(DocumentNodeMetadata::SourceId),
|
||||
};
|
||||
|
||||
if let Some(type_default) = TaggedValue::from_type(ty) {
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
# Summary
|
||||
|
||||
Replace the boxed-future execution model with synchronous, poll-based evaluation. Nodes return a `GPoll<T>` state instead of futures. Async work runs to completion on an executor outside the graph; completion bumps a per-source generation counter which is injected into the context and hashed by memo nodes, so cache invalidation along the downstream cone is an ordinary cache miss. Asynchrony is modeled as a context feature, reusing the fine-grained context nullification pass to scope invalidation. All mechanisms described here have been validated in a standalone prototype; figures quoted below are measurements from it.
|
||||
|
||||
# Motivation
|
||||
|
||||
In the current model every node's `eval` returns a `DynFuture` (`Pin<Box<dyn Future>>`), even for trivial arithmetic, and the whole graph evaluation is one large future driven per render request. Costs:
|
||||
|
||||
- **Allocation per edge**: every eval boxes a future; pure nodes pay async machinery they never use.
|
||||
- **No progressive rendering**: one slow async operation stalls the entire evaluation; there is no placeholder or partial result.
|
||||
- **Wasted evaluations**: driving async work through graph re-evaluation costs a full traversal per poll.
|
||||
- **Poor error semantics**: errors propagate as panics caught with `catch_unwind` at the root.
|
||||
- **Blocks the precompiled future**: emitting the graph as Rust source running against a minimal runtime cannot be built on a box per edge.
|
||||
|
||||
# Guide-level explanation
|
||||
|
||||
## Evaluation states
|
||||
|
||||
Node evaluation is synchronous and always returns immediately:
|
||||
|
||||
```rs
|
||||
enum GPoll<T> {
|
||||
/// Waiting on at least one future, with no placeholder to compute with.
|
||||
Pending,
|
||||
Final(T),
|
||||
/// Computed from provisional data; recomputed once the source generation bumps.
|
||||
Partial(T),
|
||||
/// An error occurred; the boxed value is a stand-in, downstream keeps computing.
|
||||
Fallback(Box<(T, GraphError)>),
|
||||
/// An error occurred and no stand-in exists; the cone cannot compute this frame.
|
||||
Error(Box<GraphError>),
|
||||
}
|
||||
```
|
||||
|
||||
The variants split into "has a value" (`Final`, `Partial`, `Fallback`) and "has no value" (`Pending`, `Error`). Value-carrying statuses flow through computation: a node receiving `Partial` computes normally and downgrades its own output; a node receiving `Fallback` computes on the stand-in and forwards the error. Valueless statuses stop the cone for this frame. Statuses combine with a meet (`Final ∧ Final = Final`, anything else drags the result down; `Error` dominates `Pending`).
|
||||
|
||||
`meet(Partial, Fallback)` collapses to `Fallback`, which alone would make an error from a still-incomplete source indistinguishable from a final document error. Finality therefore rides a separate `Finality` (`AllFinal ∧ Partial`) tracked beside the status rather than a sixth variant, so the executor can withhold provisional errors from the document without widening `GPoll`.
|
||||
|
||||
Layout: one tag plus one payload word for pointer-sized values (`GPoll<Arc<T>>` is 16 bytes); the stand-in and its error share a box, and `Error` boxes the error alone, so it crosses node boundaries without reallocating. Progress percentages are deliberately not part of the value: they change at high frequency and must not invalidate the dataflow, so they ride the monitor side channel.
|
||||
|
||||
`GraphError` records the path from the error source upward as a list of input indices (names are ambiguous; a node can have two inputs of the same type). Its kind is structured: `ErrorKind::Node(&'static str)` for node-declared failures versus operational failures such as `ErrorKind::ArenaExhausted`, which the executor answers by resetting or growing the arena and re-rendering, never by reporting a document error.
|
||||
|
||||
## Writing nodes
|
||||
|
||||
Node authors write plain Rust functions; the macro generates the node struct, the trait impl, and all status plumbing. The function must compile standalone; the generated eval calls it. Four return tiers:
|
||||
|
||||
- `-> T`: pure kernel over evaluated inputs. The macro meets input statuses; the author never sees them.
|
||||
- `-> Result<T, Interrupt>`: for kernels that evaluate lazy inputs themselves or fail. `Interrupt = Pending | Error(Box<GraphError>)`, with `From<GraphError>`, so semantic errors and input bail-outs share the `?` operator.
|
||||
- `-> Result<T, (T, GraphError)>`: an error with an explicit stand-in value.
|
||||
- `-> GPoll<T>`: full manual control (memo-class nodes).
|
||||
|
||||
Lazy inputs (`content: impl Node<Output = T>`) expose `eval(ctx) -> Result<T, Interrupt>`. The status mapping is the meet in imperative form: `Final(v)` is `Ok(v)`; `Partial(v)` and `Fallback(v, e)` are also `Ok(v)`, recording partiality or the first error in a status cell owned by the generated eval (a stack-local threaded by reference into the input handles); `Pending` and `Error` are `Err(Interrupt::...)`, and the kernel bails with `?`, the only thing it could do without a value. After the kernel returns, the generated eval folds the cell into the result, and converts `Err(Interrupt)` back into `GPoll::Pending`/`Error`. Trace indices are pushed by the handles, which know their input position, never by author code.
|
||||
|
||||
Because only actually-evaluated inputs touch the cell, an untaken `switch` branch does not drag the status down. `#[node(no_partial)]`, for nodes where placeholder data is semantically nonsense, is a one-line change in the handle mapping: `Partial` maps to `Interrupt::Pending`. Errors produced while any input was non-`Final` are provisional and must not be reported as document errors.
|
||||
|
||||
A migrated node body changes mechanically: delete `async`, replace `.eval(ctx).await` with `.eval(ctx)?`, return `Result<T, Interrupt>`.
|
||||
|
||||
## Async nodes
|
||||
|
||||
An `async fn` node is an external source. It extracts and clones everything it needs, spawns a `'static` future onto the runtime, and immediately returns a placeholder:
|
||||
|
||||
```rs
|
||||
#[node(placeholder = get_placeholder)]
|
||||
async fn get(url: String) -> String { ... }
|
||||
|
||||
fn get_placeholder(url: &str) -> String {
|
||||
format!("Waiting for response on GET {url}")
|
||||
}
|
||||
```
|
||||
|
||||
The generated struct holds a slot map keyed by the context hash. On eval: completed slot, return `Final`; in-flight slot, return `Partial(placeholder)`; no slot, insert a marker, spawn, return the placeholder. The graph never suspends; every evaluation runs to completion and produces a frame. Async bodies cannot touch the context (the future must be `'static`); the generated code checks input statuses before spawning, so no request is issued from provisional data.
|
||||
|
||||
## Invalidation by generation
|
||||
|
||||
Each async node is a source identified by its stable node id (injected like monitor paths, so identity survives recompiles and deduplicated nodes share a source). The runtime maps source id to a shared generation counter; the spawn wrapper captures its own counter:
|
||||
|
||||
```rs
|
||||
future.await; // write result into the node's slot
|
||||
*generations.lock() // bump under the table lock; absent means the
|
||||
.get_mut(&source)? += 1; // source was dropped, so the epilogue is inert
|
||||
dirty.store(true, Release); // request a re-render (coalesced)
|
||||
```
|
||||
|
||||
The slot map is `Arc<Mutex<HashMap<ContextHash, Option<GPoll<T>>>>>`, cloned into the spawned future rather than borrowed from the node, so a task still in flight when `BorrowTree` rebuilds the node writes into live storage. `Option` carries the in-flight marker: absent is "never spawned", `None` is "spawned, not landed", `Some` is the landed value. The same mutex that guards the map publishes the write to the next `eval`, so neither the slot nor the generation needs a separate release/acquire protocol.
|
||||
|
||||
At the start of each evaluation the runtime injects a snapshot of `(SourceId, generation)` pairs into the root context, sorted by id so hashing is deterministic. Memos hash the context as usual, generations included, so after a bump exactly the memos downstream of that source miss, and every other branch hits. No cache-tracking logic, no runtime graph walking, identical behavior in the interpreter and a precompiled DAG.
|
||||
|
||||
The re-render typically runs with the same context except the bumped generation, so the async node finds its completed slot: a source's own generation must not be part of its slot key, which the compiler pass below guarantees.
|
||||
|
||||
## Asynchrony as a context feature
|
||||
|
||||
Which generations a subgraph observes is determined at compile time by the same branch analysis as context nullification; the feature domain is the set of upstream `SourceId`s instead of a fixed bitflag. Requirements propagate rootward (a node's set is the union of its children's, minus what it injects). At branch convergence a dependency mismatch inserts a context modification node whose payload carries a generation retain set alongside the feature bitflags: no new node kind, no separate pass. The edge into an async node retains only sources strictly upstream of it, which excludes its own generation from its slot key by construction.
|
||||
|
||||
## Caching
|
||||
|
||||
Memo nodes hash the (retain-filtered) context, generations included. `Final` and `Partial` are both cached; partials are safe because the finalizing bump changes the key. `Pending` and `Error` are never cached. Two memo nodes exist with different contracts. The frame memo is the cheap one the compiler inserts at nullification boundaries: it publishes a promoted span into the persistent arena region keyed on the lane-normalized context, hits serve straight out of the region until the region's epoch flush, and a flush makes an entry unreachable, never wrong, so compiler-inserted caching costs a re-publish rather than a deep copy. The explicit memoize node is two-tier: the same span fast path over deep copies that survive flushes, for content whose recomputation is what the author is paying to avoid. The arena split, promotion, and the laws they rest on are covered in the attribute RFC's arena section.
|
||||
|
||||
## Runtime
|
||||
|
||||
Two layers, so the runtime stays minimal and the executor swappable:
|
||||
|
||||
```rs
|
||||
/// Node-facing scope input.
|
||||
trait Runtime { fn spawn(&self, source: SourceId, future: BoxFuture); }
|
||||
|
||||
/// Host-provided task executor with no graph knowledge.
|
||||
trait Spawner { fn spawn(&self, task: BoxFuture); }
|
||||
|
||||
struct GraphRuntime<S: Spawner> {
|
||||
generations: Arc<Mutex<HashMap<SourceId, u64>>>,
|
||||
dirty: Arc<AtomicBool>,
|
||||
spawner: S,
|
||||
}
|
||||
```
|
||||
|
||||
`GraphRuntime` wraps each task with the completion epilogue. The `Spawner` is tokio or a thread pool on desktop, `spawn_local` on wasm, or the host polling a task list in the precompiled case. The runtime reaches async nodes as a scope input (construction-time, not part of the context); a graph with zero async sources compiles to no runtime at all.
|
||||
|
||||
The execution path itself is synchronous: executor construction, update, and `execute` are plain fns, and hosts compile and evaluate without an async runtime of their own. All asynchrony lives in source kernels behind the spawner; `execute` surfaces the poll state (`GPoll`) and each host maps it at its boundary. The one genuine await is the GPU readback, which wasm cannot block on; sync hosts block on that future, with a dedicated device-poll thread driving completion.
|
||||
|
||||
Wakers are deliberately not the graph-level notification mechanism: wakers resume suspended computations and this graph never suspends; a re-evaluation is a fresh call. Wake also does not mean completion, and wakers do not survive composition across host executors. The host avoids busy-waiting with one coarse notification (park/unpark or event-loop message) shared by task wakes and the dirty epilogue.
|
||||
|
||||
Scheduling semantics: generations are read once per evaluation (completions landing mid-frame affect the next one); the dirty flag is drained once per frame (N completions, one re-render); on recompile, `retain_sources` drops removed sources from the table, so their epilogue still runs but finds no entry and bumps nothing, neither invalidating nor waking the host. Tasks are not cancelled; they are made inert.
|
||||
|
||||
# Reference-level explanation
|
||||
|
||||
## Node trait
|
||||
|
||||
```rs
|
||||
pub trait Node<Input> {
|
||||
/// Serves the node's record through the caller's claim; the proof is
|
||||
/// mintable only by the claim's closing methods.
|
||||
fn serve<'e, 'l>(&self, input: &Input, slot: FrameClaim<'e, 'l>) -> GPoll<Served<'e>>;
|
||||
/// Rank polymorphism extension point, scalar (`Free`) by default.
|
||||
fn extent(&self, input: &Input, level: Level) -> GPoll<Extent> { ... }
|
||||
/// Batched evaluation; the default body is the per-lane spec loop.
|
||||
fn eval_batch<'a, 'e>(&'a self, input: &'a Input, range: Range<u64>,
|
||||
scratch: Option<&'a mut [MaybeUninit<u64>]>,
|
||||
frames: &Frames<'e>) -> BatchStatus<'a>
|
||||
where Input: InjectIndex + Copy + ExtractArena<ArenaRef = &'e Arena> { ... }
|
||||
}
|
||||
```
|
||||
|
||||
With the record model there is no `Output` associated type: every node
|
||||
serves a record whose layout is wiring state, the element at offset 0,
|
||||
and `serve` is the one required method. The caller mints the claim out
|
||||
of its own frame space at the node's declared layout, so a served
|
||||
record is of that layout by construction, and kernels evaluate their
|
||||
inputs through generated handles that own the claims (the `eval` name
|
||||
survives on those handles and on the batch path).
|
||||
|
||||
Three load-bearing shape decisions:
|
||||
|
||||
- **Plain `&self` receiver.** An `&'i self` receiver forces the forwarding impl `impl Node for &'i N`, tying the node borrow to the eval lifetime, which makes shared references unable to satisfy higher-ranked bounds. With `&self`, sharing, erasure, and stack-scoped derived contexts compose. The price: nodes cannot lend their own storage; all lending rides the eval lifetime through the arena carried in the context (a node-resident value costs one clone into the arena per arena generation).
|
||||
- **No lifetime parameter on the trait.** With `&self`, any lifetime in the output can only come from the input type, so lending impls quantify over it: `impl<'e> Node<Context<'e>> for Lend { type Output = &'e T; }`. `GPoll` is fixed in the signature the way `Poll` is fixed in `Future`.
|
||||
- **Input by reference.** `Input` is the owned context type; calls pass `&Context`. A modifying node keeps one mutable local, mutates it between calls (per-lane index stepping is one u64 store), and lends `&local` down; sound because inputs are second-class (never stored). This halved erased-edge cost versus by-value contexts (48 bytes of ABI traffic became one pointer).
|
||||
|
||||
The batching law: `serve` is the sole semantic interface, and any `eval_batch` override must be indistinguishable from the default per-lane loop; overrides are optimization, never semantics. `extent` reports a node's domain (`Free` for index-invariant, `Exactly(n)` for bounded), with uncertainty riding the `GPoll` status axis like any other value.
|
||||
|
||||
## Context
|
||||
|
||||
Contexts are borrow-based `Copy` values. Eval is synchronous, so context lifetime is strictly stack-shaped, and every axis lives where its modification frequency is natural. The production shape (48 bytes, built 2026-07-25 in `core-types/src/context.rs`):
|
||||
|
||||
```rs
|
||||
struct ContextImpl<'e> {
|
||||
index: IndexLink<'e>, // per lane: inline head, mutable in place
|
||||
position: Option<&'e PositionLink<'e>>, // per push: frame-resident cons cell
|
||||
varargs: Option<&'e VarArgLink<'e>>, // per scope: chain of &[DynSlot] links
|
||||
footprint: Option<&'e Footprint>, // per transform: borrowed from the modifier's frame
|
||||
scope: &'e EvalScope<'e>, // per frame/scope: timing, generations, arena, cached hash
|
||||
}
|
||||
|
||||
struct IndexLink<'e> { index: u64, outer: Option<&'e IndexLink<'e>> }
|
||||
```
|
||||
|
||||
Leveled axes are cons cells: the field holds the innermost level, `outer` chains through the frames of the structure nodes that pushed the enclosing levels. Only the index keeps its head inline (and non-optional; an unindexed evaluation reads as canonical lane 0), because it is the one per-lane-mutable axis: `set_index` is a branchless u64 store, which is what lets the trait's generic default `eval_batch` run without per-lane context rebuilds. Measured against a by-ref head, where every lane must materialize a fresh context because an erased callee may legally retain the pointer: 1.5 vs 3.6 ns/lane on the erased per-lane path, and an identical 0.11 ns/lane once the batch body is visible to the compiler (`benches/context_shape.rs`).
|
||||
|
||||
Derivation has exactly two moves. Replace copies the context and overwrites a field; the original leaves the chain, so its contribution vanishes with the copy standing in (no masking machinery). Push spills the current head to the pusher's frame and chains a new head onto it. Mixing both stacks a shadowed copy and a push, two frame values.
|
||||
|
||||
`EvalScope` groups everything scope-constant (timing, pointer position, the generation table, the arena) behind one pointer, together with a hash computed at construction. Modifiers of scope axes spill a new scope to their frame with the hash recomputed; in particular the retain filter stores only the filtered-generations hash, so contexts carry no retain slice and memo visits stop walking the generation list. The general discipline: hash at write time, mix at read time. Replace-not-compose remains sound because the nullification pass computes each edge's set absolutely. Context hashing must use a seeded fast hasher (zero-initialized fx absorbs leading zero words, which produced a real wrong-value memo hit in the prototype; hash-only memo keys make collisions correctness bugs). Hash values owe no compatibility to the owned context; the invariants are pinned by the property suite in `context.rs` (axis sensitivity, level order, axis-boundary disambiguation, retain scoping).
|
||||
|
||||
Varargs are frame-lent references (`DynSlot = &dyn AnyHash`), never boxes: the injecting node owns the values and lends a slice from its frame, and nested scope injections chain, concatenating innermost-first.
|
||||
|
||||
The trait never names this type. Capabilities are extract-style bounds on the generic input (`Ctx`, `ExtractIndex`, `InjectIndex`, `ExtractArena`), matching production's context traits. Borrow-returning extracts carry the eval lifetime through an associated type (`ExtractArena<ArenaRef = &'e Arena>`, written `ExtractArena<'e>` in the macro's sugar): a lifetime in an associated-type equality is a constrained impl parameter, while a trait lifetime parameter in a plain predicate is rejected (E0207), so generated impls stay generic over the input type even for lending nodes. The authoring rule is one sentence: a named lifetime in a node fn is the eval lifetime; it enters through an extract bound and exits through `&'e` in the signature. Everything else, including "nodes cannot lend their own storage", is ordinary borrow checking of the author's standalone function.
|
||||
|
||||
## Compiler pass
|
||||
|
||||
Extends `find_context_dependencies`. Per node, alongside the `ContextFeatures` bitflags, track the set of upstream source ids. The existing convergence rule triggers insertion of a retain filter (a `context_modification` node with a generation-retain payload) exactly as nullification nodes are inserted today. Infrastructure (memo, lend, clone_out, monitor) is inserted as ordinary proto nodes, exactly as main inserts memo and nullification nodes; their registry rows are generated from a central type census (one macro invocation over the supported-type list, TaggedValue-derived plus a hand-maintained remainder) rather than written per type by hand. The wire itself carries no behavior: an edge handle is a typed erased node plus its `Type`, and every constructor is an ordinary registry row.
|
||||
|
||||
## Generated code and overhead
|
||||
|
||||
Codegen requirements: the stand-in and error share a box, the status axis is flattened into `GPoll` (together: `GPoll<u32>` is 16 bytes instead of 48), and the status plumbing is `#[inline(always)]` (a plain hint loses to the inliner cost model on the error drop-glue branches). With these, a fused pure region compiles to native arithmetic plus a final tag store; a nine-node add/mul graph evaluates behind `#[inline(never)]` as four adds and two stores, with all `Pending` checks and status meets const-folded away. A fixed-output type-erased edge (`dyn for<'a> Node<Context<'a>, Output = u32>`) is one indirect tail-call with values unboxed; lending edges erase the same way. Measured on the wired prototype: erased edges 1.8ns versus ~9ns for the per-eval box-and-downcast model; batch lend paths reach the memory bandwidth floor; steady-state interpreted frames are allocation-free (nodes in a graph arena, contexts on the stack, values and scratch in the eval arena, memo hits lending).
|
||||
|
||||
# Drawbacks
|
||||
|
||||
- **Double computation on the provisional path**: the cone downstream of an async node computes once on the placeholder and again on the real value. Inherent to progressive rendering; `#[node(no_partial)]` is the escape hatch.
|
||||
- **`'static` futures cannot lazily evaluate their inputs**: everything a future needs is evaluated and cloned before spawning.
|
||||
- **Migration is a cutover**: the macro, registry, and executor flip together (see the integration plan); node bodies migrate mechanically but the landing is one large reviewed unit.
|
||||
- **Slot and cache memory**: slot maps and LRU caches hold completed values per context hash; eviction policy needs tuning.
|
||||
|
||||
# Rationale and alternatives
|
||||
|
||||
- **Inline pinned futures** (store each node's future unboxed, poll once per graph evaluation): rejected; `Pin`-through-`Mutex` soundness arguments, a trait bifurcation, conflicts with `BorrowTree` moving nodes, and graph evaluations as polling iterations.
|
||||
- **Poll-once compatibility shims** for existing `async fn` bodies: rejected in favor of the mechanical `?` edit; genuine IO must move to the source tier anyway (a poll-once body would silently re-issue requests every frame), and the cosmetic sites are few.
|
||||
- **Bail on `Partial`/`Fallback`** (all statuses through `Err`): rejected as the default; it kills progressive rendering and stand-in propagation, and a value-carrying error type does not typecheck across inputs. It survives as the `no_partial` mapping.
|
||||
- **`Cow`-shaped wire values** (each edge carries owned-or-borrowed): rejected by measurement, 2.27 to 5.08 ns/edge on the cheapest chain, a graph-wide tax versus coercion adapters that cost only where inserted.
|
||||
- **Waker as completion signal**: wake does not mean completion, wakers do not compose across host executors, and there is no suspended continuation to resume.
|
||||
- **Manual downstream cache clearing on completion**: needs runtime topology introspection and cache-tracking logic; generation-in-hash gets the same effect through the compiler pass and works unchanged precompiled.
|
||||
- **Per-evaluation scope mutation for memo GC**: scope inputs are construction-time and must not be per-frame channels; bounded LRU needs no external signal.
|
||||
|
||||
# Unresolved questions
|
||||
|
||||
- Partial epochs: futures that publish intermediate data (streams, progressive decode) want a weaker invalidation than completion.
|
||||
- Arena sizing and growth on exhaustion (grow-and-retry across frames); ownership and the reset policy landed with the two-arena split, transient reset per evaluation and persistent epoch flush after a refused reservation.
|
||||
- Exact policy for provisional errors.
|
||||
- `Send`/wasm: spawned futures need `Send` on native only; the arena's concurrency claims need loom before any multi-threaded executor.
|
||||
|
||||
# Future possibilities
|
||||
|
||||
- **Rank polymorphism via extents**: lists as index-functions with the index carried in the context, domains reported by `extent`, batching as the interpreter's amortization; reserved here by the defaulted `extent` method. One `Add` implementation then covers scalar-scalar, scalar-list, and list-list with no monomorphization, and broadcasting is cheap because index-nullification lets the scalar branch memoize once per domain.
|
||||
- **Precompiled DAG emission**: node structs in topological order as Rust source; the runtime shrinks to the generation table, a spawner hook, and a dirty flag.
|
||||
- **JIT of graph regions**: the remaining gap between chunked interpretation and monomorphized code is unfused loop passes, the JIT's job, not the ABI's.
|
||||
@@ -0,0 +1,882 @@
|
||||
# Summary
|
||||
|
||||
Give every item flowing through the graph a set of named, typed attributes
|
||||
next to its primary `element` value. Attributes are stored as a packed
|
||||
record whose layout the compiler computes at graph compile time. Nodes
|
||||
declare their attribute reads and writes in their signatures, and the
|
||||
compiler resolves every access to a byte offset during wiring, so there is
|
||||
no name lookup at runtime. Storage and batch results are per-attribute
|
||||
columns. The contiguous record only exists as a per-lane view, assembled
|
||||
into frames claimed from the evaluation's frame space. All of the machinery that could
|
||||
corrupt a layout is generated code, so getting it wrong is a type error or
|
||||
a graph compile error rather than undefined behavior.
|
||||
|
||||
# Motivation
|
||||
|
||||
Attributes currently exist as a string-keyed store of type-erased
|
||||
columns beside the elements:
|
||||
|
||||
```rs
|
||||
pub struct List<T> {
|
||||
element: Vec<T>,
|
||||
attributes: Attributes,
|
||||
}
|
||||
|
||||
struct Attributes {
|
||||
attributes: Vec<(String, Box<dyn AnyAttribute>)>,
|
||||
len: usize,
|
||||
}
|
||||
```
|
||||
|
||||
So the storage is already columnar: one boxed column per name, each
|
||||
holding `len` values. What it is not is resolved. Every access searches
|
||||
the key list by string comparison and downcasts the column, and merging
|
||||
eagerly pads missing attributes with materialized defaults. Scalar
|
||||
access boxes per value at the item boundary, where the same store
|
||||
appears as `ItemAttributeValues(Vec<(String, Box<dyn AnyAttributeValue>)>)`.
|
||||
On a ten-node chain with eight attributes over 64k items this costs us
|
||||
around 500ns per item. The design described here measures between 3.5
|
||||
and 47ns on the same workload, depending on the execution mode, and the
|
||||
cost is mostly independent of the attribute count.
|
||||
|
||||
There is also a cost at compile time and in the node catalog. Because
|
||||
attributes ride inside `List<T>`, a node that touches a property carries
|
||||
an implementations list enumerating every carrier type: the opacity and
|
||||
blend-mode nodes each name seven. Each row monomorphizes, adding a new
|
||||
carrier type means editing every one of these lists, and the duplicated
|
||||
instantiations show up in the build size, measured at 6.16 MB and about
|
||||
4% of frame rate when the rank work landed. An escape hatch exists for
|
||||
the narrow case of reading an attribute without the element (`ListDyn`,
|
||||
which erases the carrier), but it does not extend to nodes that write.
|
||||
Separately, opacity on a group and opacity on each member composite
|
||||
differently once members overlap, so the two are semantically distinct
|
||||
and the representation has nowhere to record which one a node meant.
|
||||
|
||||
The requirements, briefly. Attributes are named with strings and work
|
||||
for all types, and users can author read/write nodes with custom names.
|
||||
A node placed before vs. after a structure node affects different
|
||||
nesting levels. Items whose element types agree can merge regardless of
|
||||
their attribute sets, with missing values filled from name-specific
|
||||
defaults. Names resolve at graph compile time, with a dynamic escape
|
||||
hatch for runtime-shaped data. A wire without attributes costs what a
|
||||
plain wire costs, and an attribute that is constant across a domain
|
||||
costs one slot rather than one per element. Batch access is the case to
|
||||
optimize, and scalar access should not require a second representation
|
||||
with conversions between the two.
|
||||
|
||||
# Guide-level explanation
|
||||
|
||||
## What an attribute is
|
||||
|
||||
An item is a primary value (the `element`, which determines the wire's
|
||||
type and colour) plus a set of named attributes that flow along with it.
|
||||
A node can read, add, or overwrite one attribute without touching the
|
||||
element and without knowing which other attributes exist. Lists carry
|
||||
attributes at every nesting level, so an attribute on a group is a
|
||||
different thing from the same attribute on the group's members.
|
||||
|
||||
## Declaring an attribute
|
||||
|
||||
An attribute name is declared once, as a marker type:
|
||||
|
||||
```rs
|
||||
attribute! {
|
||||
/// How visible the content is.
|
||||
pub Opacity("opacity"): f64 = 1.;
|
||||
/// The item's label, parked in the arena by the writer.
|
||||
pub Label("label"): &str;
|
||||
}
|
||||
```
|
||||
|
||||
Each entry expands to the marker struct, its `Attribute` impl, and the
|
||||
census registration. This fixes the name, the value type, and the
|
||||
name-specific default
|
||||
(opacity should default to fully opaque, not to `f64::default()`). The
|
||||
registry collects the declarations into a census, and a misspelled name
|
||||
in a document can be diagnosed with a nearest-match suggestion. For
|
||||
names declared in code, one name belongs to one marker, so a name can
|
||||
never mean two different types. For user-supplied names, the marker
|
||||
fixes the value type and the default in code, while the name itself
|
||||
arrives as a constant text input on the document node. It joins the name
|
||||
table at graph compile time, which is where every resolution happens
|
||||
anyway, and two user-supplied names colliding at different value types
|
||||
is a graph compile error naming both nodes.
|
||||
|
||||
A write can also be generic over the name. The shape is settled but not
|
||||
yet built: the marker is `Generic<X, T>` with the value type declared
|
||||
concretely in the signature, so `Attr<Generic<X, f64>>` and
|
||||
`Attr<Generic<Y, f64>>` are two independently named f64 writes and no
|
||||
runtime type dispatch exists. The name itself arrives as a constant
|
||||
text input on the document node and joins the name table at graph
|
||||
compile time, which is where every resolution happens anyway; two
|
||||
user-supplied names colliding at different value types is a graph
|
||||
compile error naming both nodes, the same one-name-one-type check that
|
||||
covers declared markers. A generic read resolves only when the binding
|
||||
is unique, and anything else is a validation error. The node is one
|
||||
compiled instance per concrete value type; the name never enters
|
||||
monomorphization. The build is sequenced after the current cleanup,
|
||||
and its editor-facing access has to be design-checked against the
|
||||
typed attribute key API (#4352) before it lands.
|
||||
|
||||
## Reading and writing attributes
|
||||
|
||||
A node declares its attribute io in its signature. A parameter that
|
||||
reads attributes destructures its input into the wired value and the
|
||||
reads taken from that input's wire. The opacity node becomes:
|
||||
|
||||
```rs
|
||||
/// Modifies the opacity of the input by multiplying the existing value by this percentage.
|
||||
#[node_macro::node(category("Blending"))]
|
||||
fn opacity<T>(
|
||||
_: impl Ctx,
|
||||
(element, opacity): (T, Attr<Opacity>),
|
||||
/// How visible the content should be, from 100% (fully opaque) to 0% (fully transparent).
|
||||
#[default(100.)]
|
||||
factor: Percentage,
|
||||
) -> (T, Attr<Opacity>) {
|
||||
(element, Attr(*opacity * factor / 100.))
|
||||
}
|
||||
```
|
||||
|
||||
An `Attr<A>` inside a parameter tuple is a read from that parameter's
|
||||
wire (it yields the declared default if nothing upstream wrote the
|
||||
attribute), an `Attr<A>` in the return tuple is a write, and the same
|
||||
marker on both sides is a modify. A `RemoveAttr<A>` in the return
|
||||
tuple is a delete: the name leaves the output layout, downstream reads
|
||||
yield the default again, and the column leaves the Data panel. A read
|
||||
binds to the input it is destructured from, so which wire an attribute
|
||||
comes from is always explicit in the signature, and secondary inputs
|
||||
declare reads the same way:
|
||||
|
||||
```rs
|
||||
(factor, out_of_100): (Percentage, Attr<OutOf100>),
|
||||
```
|
||||
|
||||
There is no implicit attribute flow between inputs. The primary
|
||||
input's attributes pass through to the output, overwritten where the
|
||||
node writes; a secondary input contributes exactly the reads its tuple
|
||||
names. An input without reads stays a plain parameter. Parameter
|
||||
attributes (`#[default]`, `#[implementations]`, doc comments) apply to
|
||||
the value component; attribute markers are concrete types and never
|
||||
enter monomorphization.
|
||||
|
||||
The first parameter after the context is the primary input, with or
|
||||
without a read tuple, and an unbounded generic `element: T` in its
|
||||
value position that is returned in the first tuple position means
|
||||
"I pass the element through unchanged". The compiler lowers this to a
|
||||
byte copy (often to nothing, see below), and a single compiled instance
|
||||
covers every element type, with no trait bounds and no implementations
|
||||
list. A node that actually computes on the element uses a concrete type
|
||||
or a bound instead and monomorphizes per its implementations list.
|
||||
`_: ()` means "no primary input".
|
||||
|
||||
## Levels: before vs. after a structure node
|
||||
|
||||
This part of the design is not settled, and the first implementation
|
||||
resolves every attribute at a single level. It is written up here
|
||||
because the requirement is real and the rest of the model has to leave
|
||||
room for it; see the open question at the end.
|
||||
|
||||
Where a node sits in the chain should decide which nesting level it
|
||||
affects. Applying the opacity node to a shape and then repeating it
|
||||
would give every copy its own opacity. Repeating first and then applying
|
||||
opacity would set one value on the whole group, which composites
|
||||
differently where copies overlap. The node's code is identical in both
|
||||
cases. Reads and writes bind to the top level of the wire at the node's
|
||||
position in the chain, and Repeat pushed a level in one of the two
|
||||
arrangements. Reaching an inner level from outside is an explicit
|
||||
map/enter construct, so "set on the parent" and "map over the children"
|
||||
are visibly different graphs.
|
||||
|
||||
## Structure nodes
|
||||
|
||||
A node that produces a list declares the new level's extent and writes
|
||||
per-copy values. The body is one lane of that list. There are two
|
||||
shapes, and which one applies is decided by whether the copies have to
|
||||
re-evaluate the content.
|
||||
|
||||
The general shape takes the content lazily and evaluates it once per
|
||||
copy, at that copy's index:
|
||||
|
||||
```rs
|
||||
/// Instances the content a number of times, spaced by the direction vector.
|
||||
#[node_macro::node(category("Repeat"), extent(repeat_extent))]
|
||||
fn repeat<T>(
|
||||
ctx: impl Ctx + DeriveCtx + ExtractIndex,
|
||||
content: impl Node<Context<'_>, Output = (T, Attr<Transform>)>,
|
||||
#[default(1)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
#[default(100., 100.)]
|
||||
direction: DVec2,
|
||||
) -> Result<IList<(T, Attr<Transform>)>, Interrupt> {
|
||||
let inner = content.inner_extent(ctx)?;
|
||||
let (copy, rest) = ctx.split_innermost(inner);
|
||||
if copy >= count as u64 {
|
||||
return Err(GraphError::past_end().into());
|
||||
}
|
||||
let offset = direction * copy as f64;
|
||||
let mut frame = IndexLink { index: 0, outer: None };
|
||||
let (element, transform) = content.eval(&ctx.push_level(&mut frame, copy, rest))?;
|
||||
Ok((element, Attr(DAffine2::from_translation(offset) * *transform)))
|
||||
}
|
||||
```
|
||||
|
||||
The kernel splits the flat index into its own copy index and the index
|
||||
below it, then evaluates the content at a context with the copy pushed
|
||||
as a level. `DeriveCtx` is what admits the push, and only a lazy input
|
||||
can receive a derived context, so this shape is exactly the one where
|
||||
the copies are allowed to differ: anything upstream that reads the index
|
||||
sees the copy it is being evaluated for.
|
||||
|
||||
Where the copies do not re-derive the content, the input stays an
|
||||
ordinary carrier and the kernel only computes the copy's own attributes:
|
||||
|
||||
```rs
|
||||
#[node_macro::node(category("Repeat"), extent(repeat_opacity_extent))]
|
||||
fn repeat_opacity(ctx: impl Ctx + ExtractIndex, element: f64, count: u32) -> IList<(f64, Attr<Opacity>)> {
|
||||
emit(element, Attr(ctx.index() as f64))
|
||||
}
|
||||
```
|
||||
|
||||
A carrier is evaluated once for the whole run rather than per lane, so
|
||||
every copy sees the same element and the variation lives entirely in the
|
||||
attributes. The `emit(...)` tail marks the one-lane form and doubles as
|
||||
the tuple constructor, and it is optional.
|
||||
|
||||
## Merging
|
||||
|
||||
Merging concatenates. The merged attribute set is the union of the
|
||||
inputs', and an attribute missing on one side is filled with its declared
|
||||
default for that side's items, so the result is rectangular in every
|
||||
attribute. A scalar input contributes one item. When lists are combined,
|
||||
each input's own top-level attributes are pushed down onto that input's
|
||||
items (composing by the attribute's declared rule where one exists;
|
||||
otherwise the pushed value fills the items that never wrote the name
|
||||
and the inner value wins where they did, resolved from the write sets
|
||||
at graph compile time), and the merged list starts with an empty
|
||||
top level. If the user wants to keep the groups as groups, they wrap
|
||||
explicitly instead.
|
||||
|
||||
## Selecting
|
||||
|
||||
Switch takes two lazy inputs and returns one of them, for any carrier,
|
||||
without an implementations list:
|
||||
|
||||
```rs
|
||||
/// Evaluates either the "If True" or "If False" input branch based on the condition.
|
||||
#[node_macro::node(category("Math: Logic"))]
|
||||
fn switch<T>(
|
||||
ctx: impl Ctx,
|
||||
_: (),
|
||||
condition: bool,
|
||||
#[expose]
|
||||
if_true: impl Node<Context<'_>, Output = T>,
|
||||
#[expose]
|
||||
if_false: impl Node<Context<'_>, Output = T>,
|
||||
) -> T {
|
||||
if condition { if_true.eval(ctx) } else { if_false.eval(ctx) }
|
||||
}
|
||||
```
|
||||
|
||||
An unbounded generic on a lazy input means the whole record flows
|
||||
through. Evaluating a branch yields an opaque value carrying its record,
|
||||
and whatever value the kernel returns is the output, element and
|
||||
attributes together. Kernels can evaluate several inputs, hold the
|
||||
results side by side, and pick among them with any logic, so fallback,
|
||||
N-way multiplexers, and per-lane data-driven selection are the same
|
||||
two-line pattern rather than new node kinds. The branches may carry
|
||||
different attribute sets. The output carries their union, filled with
|
||||
defaults per branch. A lazy input with a concrete output type is an
|
||||
ordinary value input: its value flows, the attributes on its wire do
|
||||
not. The tuple form composes with laziness: a lazy input declared
|
||||
`Output = (T, Attr<A>)` yields the element and the declared reads at
|
||||
each evaluation, so a kernel can branch on another input's attribute
|
||||
without evaluating the branch it rejects. It is a read declaration
|
||||
only: the lazy input's fields do not pass through to the output, since
|
||||
the kernel controls whether and how often the input is evaluated;
|
||||
forwarding a lazy input's attributes is routing.
|
||||
|
||||
The rest of the authoring surface composes. Categories, per-parameter
|
||||
doc comments, `#[default]`, `#[hard]`, `#[expose]`, widget overrides, and
|
||||
the kernel dialects (`Result<_, Interrupt>` with `?`, `GPoll` returns,
|
||||
async sources) all compose with the forms above. An async source writes
|
||||
its attributes through its claim like any other node; a reference-valued
|
||||
attribute crosses the future boundary as an owned deep copy, covered in
|
||||
the reference section.
|
||||
|
||||
# Reference-level explanation
|
||||
|
||||
## Records and layouts
|
||||
|
||||
A record is the element at offset 0 plus one field per written attribute,
|
||||
aligned to the widest field. Since the element comes first, a pointer to
|
||||
the record is also a valid pointer to the element. Element-only
|
||||
consumers are wired without adaptation, the wire keeps the element's type
|
||||
and colour, and the registry stays keyed on element types.
|
||||
|
||||
```
|
||||
byte 0 4 8 12 16 20 24 28 31
|
||||
┌───────────────┐
|
||||
f64 │ element │
|
||||
└───────────────┘
|
||||
|
||||
┌───────────────┬───────────────────────────────┬───────┬─┬───┐
|
||||
+3 │ element │ Attr<&str> (ptr, len) │ u32 │b│pad│
|
||||
└───────────────┴───────────────────────────────┴───────┴─┴───┘
|
||||
|
||||
Canonical order (descending alignment, then size) leaves no interior
|
||||
padding here; 3 bytes of tail round the record up to align 8.
|
||||
```
|
||||
|
||||
A wire's layout is the set of all attributes written in its upstream
|
||||
cone and not removed since, in a canonical order (descending alignment,
|
||||
then size, then name and level), computed at graph compile time. Some
|
||||
consequences:
|
||||
|
||||
- Layout identity is captured by stable node ids, because the write set
|
||||
is part of the hashed upstream cone. An instance that survives an
|
||||
incremental recompile cannot meet a changed layout.
|
||||
- Reads resolve to `Option<offset>` at wiring, each against the layout
|
||||
of the input wire its tuple destructures. Present means a field
|
||||
access, and absent means the macro emits the default constant. Writes
|
||||
always resolve. The runtime does no name lookup, no hashing, and no
|
||||
downcasting. A resolved read costs the same as a native struct field
|
||||
access (0.43ns).
|
||||
- Writes that are never read are diagnosed. Eliding them is a permitted
|
||||
whole-graph optimization but not required. Keeping them in the layout
|
||||
is what keeps the layout a pure function of the upstream cone.
|
||||
- Layouts are derived data. The document stores only user-visible
|
||||
structure, no attribute data is serialized, and representation changes
|
||||
never require a document migration.
|
||||
- Semantically a wire value has every attribute at all times: a read of
|
||||
a name nobody wrote yields the declared default, so a written default
|
||||
and an absent name are indistinguishable at runtime. Presence
|
||||
(membership in the layout) is representation, consulted only by merge
|
||||
push-down's fallback and the Data panel, which presents the layout:
|
||||
column presence is a pure function of the graph, stable across frames
|
||||
and across the branches a selector takes.
|
||||
- Writes are unconditional: presence never depends on a value, so a
|
||||
conditionally relevant attribute is written at its default, and a
|
||||
runtime `Option` around a value buys nothing (`None` could only mean
|
||||
the default). A name that wants a distinguished unset declares an
|
||||
`Option` value type on its marker.
|
||||
|
||||
Fields are `Copy`, and larger payloads go behind a pointer-sized field.
|
||||
Runtime-shaped data (CSV columns, arbitrary JSON) is a single dynamic
|
||||
attribute holding a map in a fixed-size slot. It is the intended slow
|
||||
path and puts no constraints on the fast one. Layouts are always static.
|
||||
|
||||
A name's type is unique by construction. For declared markers the census
|
||||
admits one marker per name, checked when the registry is built. For
|
||||
user-supplied names the binding forms at graph compile time, carrying the
|
||||
marker's declared value type, and two names colliding at different types
|
||||
is a graph compile error that names both nodes. Generic-named writes
|
||||
join the same table, carrying the name and value type their bindings
|
||||
resolve to, so the check runs over declared markers, user-supplied
|
||||
names, and generic instantiations together. We do not attempt
|
||||
coercion.
|
||||
|
||||
## Levels and residency
|
||||
|
||||
Layout keys carry a level, and levels are numbered from the innermost
|
||||
out, which keeps them stable when a structure node pushes a level
|
||||
(nothing renumbers) and matches how indices are already numbered. Only
|
||||
level 0 is populated today: the packed-record tier is flat, so the
|
||||
binding rules below and the residency analysis that follows them are the
|
||||
intended design rather than the implemented one. The level in the key is
|
||||
what leaves room for both. Keying is frozen at level 0 for the parity
|
||||
landing: no re-leveling exists, a level other than 0 is unsupported,
|
||||
and catalog nodes assume level 0.
|
||||
|
||||
The binding rules are:
|
||||
|
||||
- A read binds to the top level of the input wire it is destructured
|
||||
from at the node's chain position; a write binds to the top level of
|
||||
the output wire.
|
||||
- A structure node pushes a level and then writes its per-copy
|
||||
attributes into the former top row, and the new top row starts empty.
|
||||
- A node that reads the element (concrete type or bound) is pinned to
|
||||
level 0. An element-agnostic node binds to whatever the top currently
|
||||
is, which is also what allows a pure attribute node to run at a level
|
||||
where no element is materialized at all.
|
||||
|
||||
An attribute at level j ignores indices deeper than j by definition, so
|
||||
the level a value's storage actually varies with (its residency) lies
|
||||
somewhere between its binding level and the root. The compiler computes
|
||||
residency with the same index-invariance analysis used for context
|
||||
nullification. Constant-everywhere is residency at the root: one slot.
|
||||
A per-item attribute that only varies per group is bound at level 0 but
|
||||
resident at level 1, so it gets one slot per group rather than one per
|
||||
item.
|
||||
|
||||
Storage is meant to be level-resident and columnar, with the contiguous
|
||||
record as a view. Per-lane consumers get the view assembled across
|
||||
levels and columns into their activation frames. Reads across a level
|
||||
boundary use the same index decomposition the structure nodes already
|
||||
perform, and in batches that decomposition is hoisted per run. Neither
|
||||
the residency analysis nor the multi-level storage exists yet; a single
|
||||
level with resolved offsets is the base case both are built on.
|
||||
|
||||
## Runtime representation
|
||||
|
||||
- Every node's per-lane output lands in a frame claimed from the
|
||||
evaluation's frame space: a grow-only buffer the executor owns and
|
||||
lends down, sized at wiring by folding each path's frame need, so
|
||||
exhaustion is an accounting failure a debug assertion catches rather
|
||||
than a hot-path branch, and frame bytes carry no drop glue. A node's
|
||||
caller mints the node's frame claim out of its own free space; the
|
||||
node writes through the claim and closes it through `serve`, the
|
||||
`Node` trait's one required method, whose `Served` proof is mintable
|
||||
only by the claim's closing methods, so a served record is of the
|
||||
claimed layout by construction. The claim carries the free space
|
||||
beyond the frame, the node's inputs claim past it one after another,
|
||||
and a claim's space is free again when the claim dies, on value,
|
||||
error, and pending exits alike, with no per-exit ritual. "Allocating"
|
||||
a result is cursor arithmetic; a droppable payload parks in the arena
|
||||
once and the record carries the reference.
|
||||
- No global slot assignment exists: a node's wiring state is its own
|
||||
frame size, so incremental recompiles and instance reuse cannot
|
||||
invalidate storage. The frame space belongs to the evaluation rather
|
||||
than to a thread, so worker counts never enter wiring. The reserve is
|
||||
the peak of a per-path fold over the graph (a node's need is its own
|
||||
frame plus its inputs' frames plus the deepest input's peak), computed
|
||||
once at wiring; it exceeds the plain sum of node frames because
|
||||
fan-out re-evaluation keeps several copies of a shared node's frame
|
||||
live at once.
|
||||
- Held record values are safe without a guard: a claim keeps its record
|
||||
until it dies, so no input is released while a later sibling
|
||||
evaluates. Shared subtrees additionally rely on single consumption.
|
||||
The compiler's boundary frame memos provide it where the
|
||||
nullification pass inserts them; automatic insertion at every fan-out
|
||||
is designed but not built, and until it lands it gates the
|
||||
stack-return optimization for shared un-memoized subtrees.
|
||||
- Batch results are a run of lanes behind a resolved offset per field,
|
||||
and the target form is per-field columns, each statically Varying (an
|
||||
array) or Uniform (a single value) per the residency analysis. A node
|
||||
that does not touch a column then forwards the pointer, so bypass
|
||||
costs nothing, and uniform columns give constant attributes their
|
||||
one-slot cost regardless of lane count. Both execution forms share one
|
||||
layout descriptor, and crossing from a batched producer to a per-lane
|
||||
consumer costs about 1.5ns per lane through a lane-view adapter. The
|
||||
first implementation lays the run out as an array of records and
|
||||
resolves each marker to an offset within a lane; moving that to
|
||||
struct-of-arrays, and then to flat tables, happens behind the same
|
||||
accessors. A batched producer serves lanes in place over the caller's
|
||||
scratch through a claimed run of same-layout slots, so a lane serves
|
||||
with no staging copy.
|
||||
- A materialized level carries its lane count beside its layout and its
|
||||
storage, which is either an arena-resident run or an owned copy.
|
||||
Erased consumers (the Data panel, capture, deep copy) read the count
|
||||
and the fields off that handle without reaching into the element type,
|
||||
and Varying vs Uniform is meant to stay static in the layout, a
|
||||
Uniform column addressing a single value. This is the same picture as
|
||||
a batch result, so materializing a level and returning a batch are one
|
||||
format. A record value is one pointer wide, and only a record whose
|
||||
layout is empty rides inside the value itself; everything else spills
|
||||
to claimed frame space.
|
||||
- Alignment padding is what the column form buys. In a row, a `u8`
|
||||
element costs the same as a `u64`, while packed columns keep the cost
|
||||
proportional to the element size (2x cheaper than rows when
|
||||
cache-resident, around 8x when memory-bound). Once columns are the
|
||||
storage format, the proportional cost holds wherever data accumulates
|
||||
and the padding survives only in transient view slots, whose number is
|
||||
bounded by graph depth. Until then a run pays a row's padding on every
|
||||
lane, which is the cost the struct-of-arrays step removes.
|
||||
|
||||
## Arenas, promotion, and memos
|
||||
|
||||
Droppable payloads and every borrow a record lends live in two arena
|
||||
regions per executor. The transient arena is reset at the end of every
|
||||
evaluation: allocation is a bump, a parked payload registers a drop
|
||||
obligation, and the reset is a cursor rewind plus the registered drops.
|
||||
The persistent region holds what must outlive an evaluation (published
|
||||
memo spans, moved payloads) and flushes as a whole epoch, only between
|
||||
evaluations and only after a refused reservation. Every crossing from
|
||||
outside storage into a region is generation-checked, so a stale handle
|
||||
is a cache miss, never a dangle.
|
||||
|
||||
Two rules the split rests on, both bought with measurements:
|
||||
|
||||
- The retention law: arena occupancy is not a proxy for retained heap.
|
||||
A park costs one pointer in the region while owning arbitrary heap
|
||||
outside it (a 52x gap was measured), so a single region cannot
|
||||
decouple transient droppable heap from span lifetime; the one-arena
|
||||
epoch design this replaced ran a real document to a 12.3 GiB OOM.
|
||||
The split, plus a per-park retained-heap hint kept as a lower bound,
|
||||
is the answer.
|
||||
- The sharing law: sharing a payload between persistent entries is
|
||||
sound because persistent invalidation is epochal, every entry dying
|
||||
at one flush; per-entry eviction would need the refcounts this design
|
||||
avoids. One level down, a reference-valued attribute field's header
|
||||
is never provenance-shared: it clones, or moves where the payload
|
||||
owns all of its content and the transient arena confirms the
|
||||
reference is its own park keyed by the payload's static type. The
|
||||
move is a header memcpy with the drop obligation and its heap hint
|
||||
transferred, the source entry tombstoned in place, and a
|
||||
per-generation forwarding map so a payload two records share moves
|
||||
once.
|
||||
|
||||
Promotion into the persistent region is copy-on-write over provenance:
|
||||
a reference already persistent or `'static` is shared pointer for
|
||||
pointer, a transient leaf payload moves its header, and region bytes
|
||||
memcpy. Types with arena-resident interiors register promote glue in
|
||||
element- and field-keyed registries, so nested content takes the same
|
||||
dispatch instead of a deep copy through an owned intermediate.
|
||||
|
||||
Two memo nodes ride this, with different contracts. The frame memo is
|
||||
the cheap span-only memo the compiler inserts at nullification
|
||||
boundaries: it publishes a promoted level into the persistent region
|
||||
keyed on the lane-normalized context, a hit before the next flush
|
||||
serves straight out of the region, and a flush makes an entry
|
||||
unreachable, never wrong. The explicit memoize node is two-tier: the
|
||||
same span fast path over deep copies that survive flushes, so
|
||||
author-marked expensive content never pays recomputation for a flush.
|
||||
|
||||
An async source's future outlives the evaluation that spawns it and may
|
||||
outlive a persistent epoch, so a reference-valued attribute cannot
|
||||
cross into it as a region handle: a flush would invalidate the handle
|
||||
mid-flight, and pinning the park would need the refcounts the sharing
|
||||
law avoids. It crosses as an owned deep copy instead (`OwnedAttr`),
|
||||
taken through the field glue before the first await while the spawning
|
||||
evaluation's storage is live, and parked into the serving arena at
|
||||
every lift, one copy per invocation.
|
||||
|
||||
## Kernel io lowering
|
||||
|
||||
| Signature form | Meaning | Lowering |
|
||||
| --- | --- | --- |
|
||||
| first non-context param | primary input | carrier record |
|
||||
| `_: ()` | no primary input | no carrier input |
|
||||
| `element: T` (unbounded, returned first) | explicit passthrough | erased byte carry, where `T` is instantiated with a zero-sized token, so the routing is checked by the type system and costs nothing |
|
||||
| `element: Concrete` / bound | element read | field read at offset 0, monomorphized per implementations list, binds level 0 |
|
||||
| `(x, a): (X, Attr<A>)` | input with attribute reads | the value as its ordinary lowering; each `Attr` an offset read into that input's record, or the default constant |
|
||||
| `(_, a): ((), Attr<A>)` | attribute-only input | a wired record input with unit element; the attribute is the payload |
|
||||
| `Attr<A>` in the return tuple | attribute write | offset write into the output record |
|
||||
| `RemoveAttr<A>` in the return tuple | attribute delete | the name leaves the output layout; functionally a write of the default |
|
||||
| `OwnedAttr<A>` in an async source's return tuple | owned attribute write | the value crosses the future boundary as a deep copy taken before the first await, and parks into the serving arena at every lift; exhaustion surfaces as a poll |
|
||||
| `keys: IList<K>` | whole-extent input | a wired input, evaluated over its extent into a view |
|
||||
| plain parameters | wired value inputs | ordinary wired value inputs; attributes on their wires do not flow |
|
||||
| `impl Node<Context<'_>, Output = Concrete>` | lazy value input | the value flows, attributes do not |
|
||||
| `impl Node<Context<'_>, Output = (T, Attr<A>, ..)>` | lazy input with attribute reads | each eval yields the element plus the declared reads, offsets resolved against that input's layout; a read declaration only, and no field pass-through |
|
||||
| `impl Node<Context<'_>, Output = T>` (unbounded) | source of an opaque record family | routing, see below |
|
||||
| `-> IList<W>` with a lazy subject and `DeriveCtx` | per-copy level production | the kernel splits the index and evaluates the subject at the pushed level |
|
||||
| `-> IList<W>` with a carrier subject | per-lane level production | the carrier binds once for the run; the kernel computes each lane's own fields |
|
||||
| `-> IList<W>` without `extent(fn)` | store form | whole-level body, node owns storage |
|
||||
|
||||
`extent(fn)` names a function over the node's inputs and the queried level
|
||||
(author code never receives the node struct); `extent_raw(fn)` is the
|
||||
escape hatch for anything that vocabulary cannot say. The declaration
|
||||
answers what the level's counts are; the kernel performs the matching
|
||||
index decomposition itself. The two are written separately and have to
|
||||
agree, which is why the split and push go through shared helpers rather
|
||||
than open-coded arithmetic. `emit(...)` is an optional tail marker for
|
||||
the carrier form whose parentheses double as the tuple's, so multi-write
|
||||
lanes pay no extra nesting.
|
||||
|
||||
The rule behind all the lazy forms: kernels control whether, when, and
|
||||
at which index their inputs are evaluated, but never how the records
|
||||
move. Attributes travel inside record values or
|
||||
through generated machinery, so kernel-controlled evaluation cannot
|
||||
misalign them, and domain declarations stay with the extent system.
|
||||
|
||||
## Structure shapes
|
||||
|
||||
A structure node pairs an extent composition with an index
|
||||
decomposition. The extent composition is an ordinary extent override:
|
||||
the node macro's `extent(fn)` attribute names a function over the node's
|
||||
inputs and the queried level to `GPoll<Extent>`, with `extent_raw(fn)` as
|
||||
the escape hatch keeping the raw node, context, and level form, so
|
||||
multiplicative, additive, and data-dependent extents are one mechanism
|
||||
rather than a macro taxonomy, and the default stays the meet over the
|
||||
value inputs.
|
||||
|
||||
- Multiplicative (Repeat, map/enter): the extent override answers the
|
||||
pushed level with the copy count and forwards inner levels to the
|
||||
content. The kernel splits the flat index into the copy index and the
|
||||
index below it through the shared split helper, and pushes the copy as
|
||||
a level on a derived context before evaluating the content there. The
|
||||
extent declaration and the split are written separately and have to
|
||||
agree; the helpers are shared so that they can. Batches split into
|
||||
maximal per-copy runs.
|
||||
- Additive (Merge): an ordinary routing kernel whose selector condition
|
||||
is the index. The kernel range-splits the flat index into a segment
|
||||
and a local index through the shared split helper and evaluates that
|
||||
input at the shifted index via the derived-context lowering; the
|
||||
extent override sums the inputs' extents through `Extent::sum`. An
|
||||
input with unbounded (Free) extent counts as exactly one item in the
|
||||
sum, so merge is an extent-forcing boundary, which is the scalar base
|
||||
case. Item rows union with per-segment default fill. Each input's top
|
||||
row is pushed down one level onto that input's items via entries in
|
||||
the translation plan (a level remap computed at wiring; no values are
|
||||
needed at compile time), composing by the declared combine rule; the
|
||||
fallback is inner wins iff the inner level wrote the name, resolved
|
||||
from the write sets at wiring. The merged top row starts empty. An
|
||||
explicit Wrap node is how the user nests instead; a marker on the
|
||||
merge node enables the push-down plan variant. Batched merge forwards
|
||||
per-segment sub-ranges derived from the same split helper, so column
|
||||
uniformity survives concatenation per segment, default
|
||||
materialization is only paid on the per-lane and store paths, and
|
||||
per-lane vs batched agreement is law-bound.
|
||||
|
||||
## Opaque record values
|
||||
|
||||
An unbounded generic names a family of opaque record values. Its
|
||||
sources are the lazy inputs whose `Output` is the generic; the element
|
||||
passthrough is the same mechanism with the carrier as the family's only
|
||||
source. Wiring computes the union of the sources' layouts and a
|
||||
translation plan per source (field moves plus default fills). The
|
||||
kernel-facing handles wrap the inputs the same way the error dialect
|
||||
wraps status plumbing: evaluating a source evaluates its input at the
|
||||
unchanged context and yields a value carrying the resulting record,
|
||||
either through the plan into a claim of that source's own, or, when the
|
||||
source's layout already equals the union, by forwarding the record
|
||||
pointer untouched. The forwarding case compiles to a conditional move
|
||||
plus a tail call; the +4.7ns per lane of a two-branch switch is the
|
||||
condition and ordinary branch misprediction, and a translating source
|
||||
costs +6.5ns per lane at eight attributes.
|
||||
|
||||
The kernel routes these values as ordinary Rust values. It can evaluate
|
||||
any source any number of times, hold several results at once (per-source
|
||||
claims keep them valid side by side), pass them through helper
|
||||
functions, and return any of them. The returned value's record is the
|
||||
node's output, so provenance is carried by the value itself: element and
|
||||
attributes travel together, and returning a result obtained before some
|
||||
later evaluation is well-defined. A value is live until its own source
|
||||
is evaluated again, which reclaims that source's claim; a kernel that
|
||||
needs two results of one input side by side declares the input twice.
|
||||
The values are opaque and unforgeable, and inspecting one requires
|
||||
bounds on the generic, which is element access and monomorphization as
|
||||
usual.
|
||||
|
||||
This is the general form of selection: switch, fallback, N-way
|
||||
multiplexers, and per-lane data-driven choice among inputs are all plain
|
||||
kernels over the same mechanism, and none of them needs anything from
|
||||
the macro beyond the family lowering. Whole-list switching vs. per-item
|
||||
zip is just the residency of the condition: an invariant condition
|
||||
collapses through nullification, a varying one selects per lane.
|
||||
|
||||
The one-source shape also covers the registry's infrastructure rows.
|
||||
Monitor, context modification, memoize, and the lend and clone adapters
|
||||
are all `T -> T` passthroughs with a side effect. Over the record family
|
||||
each is a single generic node: the record forwards, and the side effect
|
||||
is orthogonal to the type (a reflective snapshot through the layout
|
||||
descriptor, a derived context, or a persistence copy sized by the
|
||||
layout). Persisting a non-Copy element needs a clone and drop function
|
||||
per element type, registered once beside the type itself rather than
|
||||
once per infrastructure node, so the per-type surface is types plus
|
||||
nodes rather than types times nodes, and compiler-inserted
|
||||
infrastructure splices one generic proto node without naming value
|
||||
types. The genuine conversion rows (the Into and Convert matrix)
|
||||
remain, because those do real per-type work.
|
||||
|
||||
A kernel that modifies the index on the context evaluates an input at a
|
||||
lane other than its own, which makes index-computable reorders plain
|
||||
kernels:
|
||||
|
||||
```rs
|
||||
/// Reverses the order of the input list.
|
||||
#[node_macro::node(category("General"))]
|
||||
fn reverse<T>(
|
||||
ctx: impl Ctx + ModifyIndex + Copy,
|
||||
_: (),
|
||||
content: impl Node<Context<'_>, Output = T>,
|
||||
) -> Result<T, Interrupt> {
|
||||
let total = match content.extent(ctx, Level::Total) {
|
||||
GPoll::Final(Extent::Exactly(count)) => count as u64,
|
||||
GPoll::Pending => return Err(Interrupt::Pending),
|
||||
_ => return Err(GraphError::new("reverse over a non-exact extent").into()),
|
||||
};
|
||||
let mut shifted = *ctx;
|
||||
shifted.set_index(total - 1 - ctx.innermost_index());
|
||||
content.eval(&shifted)
|
||||
}
|
||||
```
|
||||
|
||||
Shift, slice, and read-item-at-index are the same shape. Sort and
|
||||
shuffle still compute a whole-extent permutation once per sweep, which a
|
||||
pure per-lane kernel cannot hold, so they keep the remap-returning
|
||||
kernel. Applying a remap has a spec: per lane, evaluate the input at the
|
||||
permuted index. The generated batch kernel is the law-bound override of
|
||||
that spec, materializing the input's columns once
|
||||
and gathering each index-varying column through the wiring-resolved
|
||||
table with index-invariant columns skipped (about 1.4ns per varying
|
||||
column per lane; the comparison work of the sort itself does not depend
|
||||
on the representation). For a bijective permutation the per-lane spec
|
||||
already costs the same number of upstream evaluations as direct
|
||||
consumption, so the batch form buys cache locality and run coherence
|
||||
rather than correctness.
|
||||
|
||||
## Compiler passes
|
||||
|
||||
Everything happens at graph compile time. The census is assembled from
|
||||
the marker declarations (names, types, defaults, combine rules). Each
|
||||
wire's layout is constructed from its upstream write set, and residency
|
||||
comes from the index-invariance analysis. Offsets are resolved into node
|
||||
state, the stack bound is folded from the layouts, and union and
|
||||
translation plans are built at selectors and merges. A per-name
|
||||
dependency analysis feeds the cache keys. The diagnostics produced along
|
||||
the way are unknown or misspelled names (checked against the census,
|
||||
with nearest-match suggestions), custom-name collisions, reads that some
|
||||
evaluation path cannot satisfy, and layout conflicts. The runtime does
|
||||
no name lookup. Layout construction and the safe record builders check
|
||||
field type identity and panic on a mismatch, which is what guards the
|
||||
generated code against itself at wiring boundaries.
|
||||
|
||||
## Soundness
|
||||
|
||||
Attributes only move through generated machinery. Kernels receive
|
||||
dereferenced values and opaque handles, and the translation and carry
|
||||
plans behind them are emitted from wiring-resolved layouts. Layout
|
||||
identity is captured by stable node ids, so an instance that survives a
|
||||
recompile can never meet a changed layout. Because layouts are functions
|
||||
of wires rather than of anything a kernel controls, safe kernel code can
|
||||
make semantic mistakes (evaluating an input it did not need to) but
|
||||
cannot misalign an offset. Kernels see contexts only as an opaque
|
||||
`impl Ctx + ...` they cannot construct, and lifetimes keep them from
|
||||
stashing handles in node state.
|
||||
|
||||
That is the property the design is for, and the enforcement now rests
|
||||
on construction at the seams that used to be open. Type identity is
|
||||
stamped on every layout field and on the element write, and both
|
||||
participate in layout equality, so the union's shared-element assertion
|
||||
and the identity-forwarding decision distinguish same-shape
|
||||
different-type layouts. Retiring the inline register-return path in
|
||||
favor of always-spill removed the one producer that wrote without an
|
||||
installed layout. Serving closes only through a frame claim's own
|
||||
methods, whose proof cannot be minted elsewhere, and assertion reads go
|
||||
through an owned capture at the node's declared layout rather than raw
|
||||
frame reads. Serving lifetimes make an arena-resident value
|
||||
inexpressible beyond its evaluation in safe code, and an arena move is
|
||||
keyed by the park's static type, so a mistyped or unkeyed reference
|
||||
declines into the clone path instead of moving foreign bytes. What
|
||||
remains unsafe is the irreducible core, the erased glue and the
|
||||
wiring-computed byte plans, plus a small tracked set of open seams of
|
||||
which the hoist mask's positional contract is the last
|
||||
soundness-relevant survivor; an adversarial audit round over every
|
||||
safety contract is scheduled before this lands upstream.
|
||||
|
||||
# Drawbacks
|
||||
|
||||
- The node macro absorbs real complexity: io classification, layout
|
||||
bookkeeping, the structural skeletons, and the record-family lowering are all
|
||||
generated code. That is the point (authors stay simple, the privileged
|
||||
surface stays auditable), but macro diagnostics will need work to stay
|
||||
better than raw trait-solver errors.
|
||||
- Changing a document's attribute set changes layouts, which recompiles
|
||||
the affected cone and reconstructs its instances. This is the same
|
||||
cost class as editing node parameters today, but a runtime-map design
|
||||
would absorb attribute renames without recompiling.
|
||||
- Until an elision pass exists, attributes that are written but never
|
||||
read occupy slots and copies.
|
||||
- Per-lane views pad small elements up to the record alignment, and so
|
||||
does a run of records until the columnar storage arrives; only the
|
||||
column form is footprint-proportional.
|
||||
- Two execution forms (per-lane views and batches) are more
|
||||
machinery than one representation. They share a single layout
|
||||
descriptor, and the measured seam between them is about 1.5ns per
|
||||
lane, but the machinery still has to exist.
|
||||
|
||||
# Rationale and alternatives
|
||||
|
||||
- Keep runtime maps (the current implementation): roughly 500ns per item
|
||||
on the reference chain and ~57ns marginal per attribute, an allocation
|
||||
per column, and no compile-time name checking. Interning the keys
|
||||
improves the constant (about 1.9ns per access vs. 0.43 for a resolved
|
||||
offset) but keeps a per-access search and rules out the structural
|
||||
optimizations that need static layouts: bypass, uniform columns, and
|
||||
packing a level's fields to their resolved offsets.
|
||||
- Attributes as separate graph edges, one channel per attribute: bypass
|
||||
and per-channel caching become graph structure. We prototyped and
|
||||
measured this. Without caching at fan-outs, every channel re-evaluates
|
||||
the shared upstream work (2-4x slower on realistic chains), and the
|
||||
cache that fixes it stores a multi-channel result, which is a record,
|
||||
so the fixed version converges on this design while keeping the extra
|
||||
edges, dispatch, and graph inflation. The two structural insights of
|
||||
the channel model survive here as the column structure of batch
|
||||
results.
|
||||
- Typed attribute tuples in the wire type: layouts become
|
||||
document-dependent types, which the registry's precompiled constructor
|
||||
rows cannot cover, and row polymorphism leaks into type resolution.
|
||||
Keeping layouts as side metadata means attribute sets never gate
|
||||
convergence (merge unions them, defaults answer switch mismatches) and
|
||||
the resolver is untouched.
|
||||
- The numbers cited throughout come from a reference prototype with
|
||||
type-erased node inputs (the indirect calls were verified in the
|
||||
disassembly), thin LTO, 64k-lane workloads, and best-of-nine timing.
|
||||
Chain results use ten nodes and eight f64 attributes.
|
||||
|
||||
# Prior art
|
||||
|
||||
Attributes were specified in issue #3779 and first implemented by the
|
||||
Item and List wire types work, which remains the behavioral reference
|
||||
for this design: name-specific defaults, merge with default fill, and
|
||||
the Data panel's presentation of items all carry over, and the wire
|
||||
rank display and Data panel belong to the editor and are unaffected
|
||||
here. One behavior is refined rather than kept: flat merge
|
||||
has to drop one input's top-level attributes, which the push-down rule
|
||||
is meant to preserve. The present representation (string-keyed storage inside
|
||||
`List<T>`, with per-carrier implementations rows) is what the Motivation
|
||||
section measures. This RFC keeps its observable behavior while replacing
|
||||
the storage and registration strategy underneath.
|
||||
|
||||
Outside Graphite, the nearest prior art is row polymorphism in records
|
||||
(Rémy; PureScript and Elm) for the layout unions, ECS archetype storage
|
||||
for resolved column handles, and the uniform vs. varying distinction
|
||||
from shading languages for residency.
|
||||
|
||||
# Unresolved questions
|
||||
|
||||
- Leveled attributes, the largest open area. Attributes at more than one
|
||||
nesting level are designed but not built, and the keying is frozen at
|
||||
level 0 for this landing, which parity does not need. Open within the
|
||||
area are the binding rules as stated (does a read really bind to the
|
||||
top level of the wire it is destructured from, and is pinning
|
||||
element-reading nodes to level 0 the right rule), how a structure
|
||||
node's per-copy write lands in the former top row, whether residency
|
||||
is worth its analysis or whether the extent machinery already answers
|
||||
it (an attribute whose index function ignores the index is `Free`),
|
||||
and what the storage for a level above 0 looks like given that the
|
||||
record tier is flat. The UX half of the same question is the
|
||||
map/enter construct: how "set on the parent" and "map over the
|
||||
children" read differently in the graph. Until this is settled, the
|
||||
Repeat-around-Opacity requirement is unmet.
|
||||
- Where and how the combine rule is declared on the attribute marker.
|
||||
Merge push-down and flatten both consume it, and inner-wins is the
|
||||
intended fallback.
|
||||
- The spelling of the push-down marker on the merge node, the one part
|
||||
of the additive shape the extent override cannot express.
|
||||
- Naming: the authoring list type is spelled `IList` here, as in the
|
||||
implementation, to keep it clear of the legacy wire type's `List`; a
|
||||
rename to `List` is planned once that type retires.
|
||||
- Generic-named writes: the shape is settled (`Generic<X, T>`, concrete
|
||||
value type, name as a constant text input resolved at graph compile
|
||||
time), and what remains open is where the default for a generically
|
||||
written name comes from (a `Default` bound on the value vs. an input
|
||||
on the name source) and the graph UX of the name source node, to be
|
||||
design-checked against the typed attribute key API (#4352).
|
||||
- Whether evaluating at a lane outside the input's extent is clamped,
|
||||
wrapped, or a debug assertion.
|
||||
- `IList<IList<W>>` outputs, i.e. one node pushing two levels.
|
||||
- How chatty the editor boundary becomes per frame, given that tools
|
||||
consume materialized views today.
|
||||
|
||||
# Future possibilities
|
||||
|
||||
- Scope variables: varargs with graph-compile-time-known names, the
|
||||
context-side mirror of this design. The same census and marker
|
||||
machinery, reads resolved to a hop count into a stack-allocated chain
|
||||
(0.43ns through two hops in our measurements), pushes that are free of
|
||||
allocation (0.56ns), and injection handles that make a missing or
|
||||
doubled push unrepresentable. This shrinks the context to a hot core
|
||||
and replaces coarse context features with per-name dependencies in
|
||||
cache keys.
|
||||
- Write elision for never-read attributes, once the whole-graph analysis
|
||||
pass exists.
|
||||
- Mask-run decomposition in the selector's batch kernel: dense
|
||||
sub-ranges for uniform condition runs, and optionally
|
||||
compute-both-and-select speculation, which purity makes legal.
|
||||
- GPU consumption: uniform vs. varying columns map directly onto
|
||||
constant buffers vs. vertex attributes.
|
||||
- A user-routable remap value (shuffle, manual orderings, an apply-remap
|
||||
node) built on the sort machinery.
|
||||
@@ -126,12 +126,6 @@ pub trait ModifyIndex: ExtractIndex + InjectIndex {}
|
||||
pub trait ModifyVarArgs: ExtractVarArgs + InjectVarArgs {}
|
||||
```
|
||||
|
||||
### Authoring rule: forward with Modify*, consume with Extract*
|
||||
|
||||
Declare a feature via `Modify*` when the node only reads it to compute a new value it injects for its children (a "forward"), and via `Extract*` only when the node genuinely consumes the value for its own output (a "sink").
|
||||
|
||||
The analysis skips `Modify*` bounds but treats every `Extract*` bound as an *unconditional* requirement. Because `Modify*` is a supertrait of `Extract*`, a `Modify*` bound already grants the read capability (e.g. `modify_footprint`, which is `where Self: ExtractFootprint`), so it is a mistake to list both. Writing `impl Ctx + ExtractFootprint + ModifyFootprint` on a forwarding node re-introduces the feature as a hard dependency at every such node, which propagates up the whole tree and pins upstream memos to a value the node never actually consumes (e.g. a viewport pan invalidating a render cache that renders in local space). Use `impl Ctx + ModifyFootprint` alone.
|
||||
|
||||
### Conditional Context Dependencies
|
||||
|
||||
Modify* traits represent a special case in context analysis:
|
||||
|
||||
@@ -76,16 +76,15 @@ fn write_nodes_table_rows(page: &mut std::fs::File, nodes: &[(&core_types::Proto
|
||||
let implementations = node_registry.get(id)?;
|
||||
let valid_primary_inputs_to_outputs = implementations
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
let input = entry
|
||||
.io
|
||||
.map(|(_, node_io)| {
|
||||
let input = node_io
|
||||
.inputs
|
||||
.first()
|
||||
.map(|ty| ty.nested_type())
|
||||
.filter(|&ty| ty != &concrete!(()))
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_default();
|
||||
let output = entry.io.return_value.nested_type().to_string();
|
||||
let output = node_io.return_value.nested_type().to_string();
|
||||
format!("`{input} → {output}`")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -23,8 +23,8 @@ pub fn write_node_page(index: usize, id: &core_types::ProtoNodeIdentifier, metad
|
||||
|
||||
// Input types
|
||||
let mut valid_input_types = vec![Vec::new(); metadata.fields.len()];
|
||||
for entry in implementations.iter() {
|
||||
for (i, ty) in entry.io.inputs.iter().enumerate() {
|
||||
for (_, node_io) in implementations.iter() {
|
||||
for (i, ty) in node_io.inputs.iter().enumerate() {
|
||||
valid_input_types[i].push(ty.nested_type().clone());
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ pub fn write_node_page(index: usize, id: &core_types::ProtoNodeIdentifier, metad
|
||||
}
|
||||
|
||||
// Primary output types
|
||||
let valid_primary_outputs = implementations.iter().map(|entry| entry.io.return_value.nested_type().clone()).collect::<Vec<_>>();
|
||||
let valid_primary_outputs = implementations.iter().map(|(_, node_io)| node_io.return_value.nested_type().clone()).collect::<Vec<_>>();
|
||||
|
||||
// Write sections to the file
|
||||
write_frontmatter(&mut page, metadata, index + 1);
|
||||
|
||||
Reference in new issue
Block a user