mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3fdc97f81 | ||
|
|
3d17fa0f0c | ||
|
|
9e83632647 | ||
|
|
6392c02dee | ||
|
|
470ffdab43 | ||
|
|
28d9e3cbe3 | ||
|
|
28d37d30d0 | ||
|
|
cf66f8396b | ||
|
|
be5c78421a | ||
|
|
f0f7d6a5d7 | ||
|
|
44277c9636 | ||
|
|
99f94503c3 | ||
|
|
925075337b | ||
|
|
df70222d61 | ||
|
|
1f9e0cc37b |
No files matched your search
Generated
+1
@@ -2038,6 +2038,7 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"log",
|
||||
"raster-types",
|
||||
|
||||
@@ -2406,7 +2406,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
&& let Some(reference) = document.network_interface.reference(node_id, network_path).clone()
|
||||
&& let Some(node_definition) = resolve_document_node_type(&reference)
|
||||
{
|
||||
let context_features = node_definition.node_template.document_node.context_features.clone();
|
||||
let context_features = node_definition.node_template.document_node.context_features;
|
||||
document.network_interface.set_context_features(node_id, network_path, context_features);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ pub use graphene_application_io::ApplicationIo;
|
||||
#[derive(Default)]
|
||||
pub struct PlatformApplicationIo {
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu_executor: Option<WgpuExecutor>,
|
||||
gpu_executor: Option<std::sync::Arc<WgpuExecutor>>,
|
||||
resources: Option<Box<dyn resource::LoadResource>>,
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ impl PlatformApplicationIo {
|
||||
|
||||
Self {
|
||||
#[cfg(feature = "wgpu")]
|
||||
gpu_executor: executor,
|
||||
gpu_executor: executor.map(std::sync::Arc::new),
|
||||
resources: None,
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ impl PlatformApplicationIo {
|
||||
set_wgpu_available(wgpu_available);
|
||||
|
||||
Self {
|
||||
gpu_executor: executor,
|
||||
gpu_executor: executor.map(std::sync::Arc::new),
|
||||
resources: None,
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,12 @@ impl ApplicationIo for PlatformApplicationIo {
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
fn gpu_executor(&self) -> Option<&Self::Executor> {
|
||||
self.gpu_executor.as_ref()
|
||||
self.gpu_executor.as_deref()
|
||||
}
|
||||
|
||||
#[cfg(feature = "wgpu")]
|
||||
fn gpu_executor_arc(&self) -> Option<std::sync::Arc<Self::Executor>> {
|
||||
self.gpu_executor.clone()
|
||||
}
|
||||
|
||||
fn load_resource(&self, hash: resource::ResourceHash) -> resource::ResourceFuture<'_> {
|
||||
|
||||
@@ -370,16 +370,13 @@ impl ProtoNetwork {
|
||||
let mut combined_deps = ContextFeatures::default();
|
||||
let node_index = id.0 as usize;
|
||||
|
||||
let (extract, inject) = {
|
||||
let dependencies = &self.nodes[node_index].1.context_features;
|
||||
(dependencies.extract, dependencies.inject)
|
||||
};
|
||||
let context_features = self.nodes[node_index].1.context_features;
|
||||
|
||||
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 (extract, Some(id)),
|
||||
ConstructionArgs::Value(_) => return (context_features.extract, Some(id)),
|
||||
ConstructionArgs::Nodes(items) => items.clone(),
|
||||
ConstructionArgs::Inline(_) => return (extract, Some(id)),
|
||||
ConstructionArgs::Inline(_) => return (context_features.extract, Some(id)),
|
||||
};
|
||||
|
||||
// Compute the dependencies for each branch and combine all of them
|
||||
@@ -392,9 +389,9 @@ impl ProtoNetwork {
|
||||
let mut new_deps = combined_deps;
|
||||
|
||||
// Remove requirements which this node provides
|
||||
new_deps &= !inject;
|
||||
new_deps &= !context_features.inject;
|
||||
// Add requirements we have
|
||||
new_deps |= extract;
|
||||
new_deps |= context_features.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);
|
||||
@@ -410,7 +407,7 @@ impl ProtoNetwork {
|
||||
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
|
||||
|
||||
// Which dependencies do we supply (and don't need ourselves)?
|
||||
let net_injections = inject.difference(extract);
|
||||
let net_injections = context_features.inject.difference(context_features.extract);
|
||||
|
||||
// Which dependencies still need to be met after this node?
|
||||
let remaining_deps_from_children = combined_deps.difference(net_injections);
|
||||
|
||||
@@ -30,14 +30,20 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::INDEX,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::empty(),
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
@@ -48,14 +54,20 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::VARARGS),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::VARARGS,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
@@ -65,18 +77,21 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
NodeInput::node(NodeId(3), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::empty(),
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(graphene_std::application_io::RenderConfig),
|
||||
call_argument: concrete!(Context),
|
||||
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::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
|
||||
extract: ContextFeatures::INDEX | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
use std::any::Any;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::ops::Add;
|
||||
|
||||
use core_types::arena::{Arena, ArenaCell};
|
||||
use core_types::context::{ContextImpl, Ctx, EvalScope, ExtractArena, InjectIndex};
|
||||
use core_types::gnode::{BatchStatus, GNode, StatusCell};
|
||||
use core_types::gpoll::{ErrorKind, Finality, GPoll, Interrupt};
|
||||
|
||||
fn add<A: Add<B>, B, C: Ctx>(_ctx: &C, augend: A, addend: B) -> <A as Add<B>>::Output {
|
||||
augend + addend
|
||||
}
|
||||
|
||||
struct AddNode<Node0, Node1> {
|
||||
augend: Node0,
|
||||
addend: Node1,
|
||||
}
|
||||
|
||||
impl<Node0, Node1> AddNode<Node0, Node1> {
|
||||
fn new(augend: Node0, addend: Node1) -> Self {
|
||||
Self { augend, addend }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, Input, Node0, Node1> GNode<Input> for AddNode<Node0, Node1>
|
||||
where
|
||||
A: Add<B>,
|
||||
Input: Ctx,
|
||||
Node0: GNode<Input, Output = A>,
|
||||
Node1: GNode<Input, Output = B>,
|
||||
{
|
||||
type Output = <A as Add<B>>::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
|
||||
let cell = StatusCell::new();
|
||||
let augend = match cell.eval_input(0, &self.augend, input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
let addend = match cell.eval_input(1, &self.addend, input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
cell.finish(add(input, augend, addend))
|
||||
}
|
||||
}
|
||||
|
||||
struct ValueNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> GNode<Input> for ValueNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
struct ReadIndexNode;
|
||||
|
||||
impl<Input: InjectIndex + Copy + ExtractIndexValue> GNode<Input> for ReadIndexNode {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<f64> {
|
||||
GPoll::Final(input.index_value() as f64)
|
||||
}
|
||||
}
|
||||
|
||||
trait ExtractIndexValue {
|
||||
fn index_value(&self) -> u64;
|
||||
}
|
||||
|
||||
impl ExtractIndexValue for ContextImpl<'_> {
|
||||
fn index_value(&self) -> u64 {
|
||||
self.index_head().index
|
||||
}
|
||||
}
|
||||
|
||||
fn string_length<C: Ctx>(_ctx: &C, value: &String) -> f64 {
|
||||
value.len() as f64
|
||||
}
|
||||
|
||||
struct LendStringNode {
|
||||
value: String,
|
||||
cell: ArenaCell<String>,
|
||||
}
|
||||
|
||||
impl LendStringNode {
|
||||
fn new(value: String) -> Self {
|
||||
Self {
|
||||
value,
|
||||
cell: ArenaCell::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e, Input> GNode<Input> for LendStringNode
|
||||
where
|
||||
Input: Ctx + ExtractArena<ArenaRef = &'e Arena>,
|
||||
{
|
||||
type Output = &'e String;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<&'e String> {
|
||||
let arena = input.arena();
|
||||
if let Some(value) = self.cell.load(arena) {
|
||||
return GPoll::Final(value);
|
||||
}
|
||||
match arena.alloc(self.value.clone()) {
|
||||
Some((value, weak)) => {
|
||||
self.cell.store(weak);
|
||||
GPoll::Final(value)
|
||||
}
|
||||
None => GPoll::arena_exhausted(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct StringLengthNode<Node0> {
|
||||
value: Node0,
|
||||
}
|
||||
|
||||
impl<Node0> StringLengthNode<Node0> {
|
||||
fn new(value: Node0) -> Self {
|
||||
Self { value }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e, Input, Node0> GNode<Input> for StringLengthNode<Node0>
|
||||
where
|
||||
Input: Ctx,
|
||||
Node0: GNode<Input, Output = &'e String>,
|
||||
{
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<f64> {
|
||||
let cell = StatusCell::new();
|
||||
let value = match cell.eval_input(0, &self.value, input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
cell.finish(string_length(input, value))
|
||||
}
|
||||
}
|
||||
|
||||
type ErasedGNode<T> = dyn for<'c> GNode<ContextImpl<'c>, Output = T>;
|
||||
type ErasedLendEdge = dyn for<'c> GNode<ContextImpl<'c>, Output = &'c String>;
|
||||
|
||||
fn string_length_constructor(args: Vec<Box<dyn Any>>) -> Result<Box<ErasedGNode<f64>>, &'static str> {
|
||||
let mut args = args.into_iter();
|
||||
let value = *args.next().ok_or("arity")?.downcast::<Box<ErasedLendEdge>>().map_err(|_| "type")?;
|
||||
Ok(Box::new(StringLengthNode::new(value)))
|
||||
}
|
||||
|
||||
fn add_constructor_f64(args: Vec<Box<dyn Any>>) -> Result<Box<ErasedGNode<f64>>, &'static str> {
|
||||
let mut args = args.into_iter();
|
||||
let augend = *args.next().ok_or("arity")?.downcast::<Box<ErasedGNode<f64>>>().map_err(|_| "type")?;
|
||||
let addend = *args.next().ok_or("arity")?.downcast::<Box<ErasedGNode<f64>>>().map_err(|_| "type")?;
|
||||
Ok(Box::new(AddNode::new(augend, addend)))
|
||||
}
|
||||
|
||||
fn scope_fixture<'a>(generations: &'a [(u64, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(Some(0.5), None, None, generations, arena)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_expansion_evaluates_through_typed_erased_edges() {
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let augend: Box<dyn Any> = Box::new(Box::new(ValueNode(1.0f64)) as Box<ErasedGNode<f64>>);
|
||||
let addend: Box<dyn Any> = Box::new(Box::new(ValueNode(2.0f64)) as Box<ErasedGNode<f64>>);
|
||||
let wired = add_constructor_f64(vec![augend, addend]).unwrap();
|
||||
|
||||
assert_eq!(wired.eval(&ctx), GPoll::Final(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wiring_rejects_type_and_arity_mismatches() {
|
||||
let augend: Box<dyn Any> = Box::new(Box::new(ValueNode(1.0f64)) as Box<ErasedGNode<f64>>);
|
||||
let addend: Box<dyn Any> = Box::new(Box::new(ValueNode(2u32)) as Box<ErasedGNode<u32>>);
|
||||
assert_eq!(add_constructor_f64(vec![augend, addend]).map(|_| ()), Err("type"));
|
||||
|
||||
let augend: Box<dyn Any> = Box::new(Box::new(ValueNode(1.0f64)) as Box<ErasedGNode<f64>>);
|
||||
assert_eq!(add_constructor_f64(vec![augend]).map(|_| ()), Err("arity"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spec_loop_batches_through_the_erased_edge() {
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph: Box<ErasedGNode<f64>> = Box::new(AddNode::new(ReadIndexNode, ValueNode(10.0f64)));
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 4];
|
||||
let status = graph.eval_batch(&ctx, 2..6, Some(&mut scratch));
|
||||
let BatchStatus::Filled(lanes, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
assert_eq!(lanes, &[12.0, 13.0, 14.0, 15.0]);
|
||||
assert_eq!(finality, Finality::AllFinal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lending_kernel_clones_once_per_generation_and_lends_after() {
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let node = LendStringNode::new("lend me".to_string());
|
||||
let GPoll::Final(first) = node.eval(&ctx) else {
|
||||
panic!("first eval must clone into the arena and lend");
|
||||
};
|
||||
let GPoll::Final(second) = node.eval(&ctx) else {
|
||||
panic!("second eval must hit the cell");
|
||||
};
|
||||
assert_eq!(first, "lend me");
|
||||
assert!(std::ptr::eq(first, second));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exhausted_arena_reports_the_operational_error() {
|
||||
let arena = Arena::new(0);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let node = LendStringNode::new("too big".to_string());
|
||||
let GPoll::Error(error) = node.eval(&ctx) else {
|
||||
panic!("exhaustion must surface as an operational error");
|
||||
};
|
||||
assert_eq!(error.kind, ErrorKind::ArenaExhausted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lending_edges_erase_and_wire_like_owned_edges() {
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let value: Box<dyn Any> = Box::new(Box::new(LendStringNode::new("across the boundary".to_string())) as Box<ErasedLendEdge>);
|
||||
let wired = string_length_constructor(vec![value]).unwrap();
|
||||
|
||||
assert_eq!(wired.eval(&ctx), GPoll::Final(19.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spec_loop_batches_through_the_erased_lending_edge() {
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph: Box<ErasedLendEdge> = Box::new(LendStringNode::new("batched".to_string()));
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 3];
|
||||
let status = graph.eval_batch(&ctx, 0..3, Some(&mut scratch));
|
||||
let BatchStatus::Filled(lanes, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
assert_eq!(lanes.len(), 3);
|
||||
assert!(lanes.iter().all(|lane| std::ptr::eq(*lane, lanes[0])));
|
||||
assert_eq!(*lanes[0], "batched");
|
||||
assert_eq!(finality, Finality::AllFinal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_input_records_partiality_invisibly() {
|
||||
struct FallbackNode;
|
||||
impl<Input> GNode<Input> for FallbackNode {
|
||||
type Output = f64;
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
GPoll::fallback(0.0, "upstream failed")
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph = AddNode::new(FallbackNode, ValueNode(5.0f64));
|
||||
let GPoll::Fallback(boxed) = graph.eval(&ctx) else {
|
||||
panic!("fallback must propagate with the computed stand-in");
|
||||
};
|
||||
assert_eq!(boxed.0, 5.0);
|
||||
assert!(boxed.1.kind == "upstream failed");
|
||||
assert_eq!(boxed.1.trace, vec![0]);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ wgpu = ["dep:raster-types", "raster-types/wgpu"]
|
||||
# Local dependencies
|
||||
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,6 +21,9 @@ 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<'_>;
|
||||
}
|
||||
|
||||
@@ -31,6 +34,10 @@ 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)
|
||||
}
|
||||
@@ -54,7 +61,7 @@ pub trait GetEditorPreferences {
|
||||
fn max_render_region_area(&self) -> u32;
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum ExportFormat {
|
||||
#[default]
|
||||
@@ -62,14 +69,14 @@ pub enum ExportFormat {
|
||||
Raster,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct TimingInformation {
|
||||
pub time: f64,
|
||||
pub animation_time: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, graphene_hash::CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct RenderConfig {
|
||||
pub viewport: Footprint,
|
||||
|
||||
@@ -4,15 +4,6 @@ use std::mem::MaybeUninit;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||
|
||||
/// Handle word layout: 24 generation bits above 40 offset bits, so a 1 TiB arena is
|
||||
/// addressable and generations run out after ~3 days of 60fps resets.
|
||||
const OFFSET_BITS: u32 = 40;
|
||||
const OFFSET_MASK: u64 = (1 << OFFSET_BITS) - 1;
|
||||
const GENERATION_MASK: u64 = (1 << (64 - OFFSET_BITS)) - 1;
|
||||
|
||||
/// Out of the encodable range, so no handle, including `NULL`, matches it.
|
||||
const PARKED_GENERATION: u64 = GENERATION_MASK + 1;
|
||||
|
||||
pub struct Arena {
|
||||
generation: AtomicU64,
|
||||
offset: AtomicUsize,
|
||||
@@ -20,12 +11,6 @@ pub struct Arena {
|
||||
drops: Mutex<Vec<DropEntry>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Arena {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Arena").field("generation", &self.generation).field("size", &self.buf.len()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
struct DropEntry {
|
||||
offset: usize,
|
||||
drop_fn: unsafe fn(*mut u8),
|
||||
@@ -33,55 +18,23 @@ struct DropEntry {
|
||||
|
||||
// SAFETY: disjoint regions are handed out by an atomic bump; a region is written
|
||||
// only by its allocating caller before publication, and cross-thread hand-off is
|
||||
// ordered by the Release/Acquire pair on the published handle word. Payloads are
|
||||
// `Send + Sync` by the bound on every allocating method.
|
||||
// ordered by the Release/Acquire pair on the published handle word.
|
||||
unsafe impl Sync for Arena {}
|
||||
unsafe impl Send for Arena {}
|
||||
|
||||
impl std::panic::UnwindSafe for Arena {}
|
||||
impl std::panic::RefUnwindSafe for Arena {}
|
||||
|
||||
/// Shared by all arenas, so a foreign handle misses like a stale one.
|
||||
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
static LIVE_ARENAS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// `None` past [`GENERATION_MASK`], where a reissued generation would let an ancient
|
||||
/// handle upgrade against a current arena. Recovered by `reset_generation_counter`.
|
||||
fn next_generation() -> Option<u64> {
|
||||
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
(generation <= GENERATION_MASK).then_some(generation)
|
||||
}
|
||||
|
||||
/// Rewinds the shared generation counter so previously issued values are reused.
|
||||
/// Returns `false` without rewinding when an [`Arena`] is live at the time of the
|
||||
/// check, which is a debugging aid rather than a guarantee.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No [`ArenaWeak`] minted before this call may be upgraded afterwards. Dropping
|
||||
/// every [`Arena`] is not sufficient, since nodes also hold handles in
|
||||
/// [`ArenaCell`]s; those nodes must be dropped too. No arena may be constructed
|
||||
/// concurrently either, since the live check and the rewind are separate steps.
|
||||
pub unsafe fn reset_generation_counter() -> bool {
|
||||
if LIVE_ARENAS.load(Ordering::Acquire) != 0 {
|
||||
return false;
|
||||
}
|
||||
NEXT_GENERATION.store(1, Ordering::Release);
|
||||
true
|
||||
}
|
||||
|
||||
impl Arena {
|
||||
pub fn new(capacity: usize) -> Option<Self> {
|
||||
let generation = next_generation()?;
|
||||
pub fn new(capacity: usize) -> Self {
|
||||
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
|
||||
LIVE_ARENAS.fetch_add(1, Ordering::Release);
|
||||
Some(Self {
|
||||
generation: AtomicU64::new(generation),
|
||||
Self {
|
||||
// Starts at 1 so the null handle word (0) can never upgrade.
|
||||
generation: AtomicU64::new(1),
|
||||
offset: AtomicUsize::new(0),
|
||||
buf,
|
||||
drops: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generation(&self) -> u64 {
|
||||
@@ -109,11 +62,8 @@ impl Arena {
|
||||
Some(start)
|
||||
}
|
||||
|
||||
pub fn alloc<T: Send + Sync>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
|
||||
pub fn alloc<T>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
|
||||
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
|
||||
// Built before the write so an unencodable offset drops `value` here
|
||||
// rather than stranding it in the arena without drop glue.
|
||||
let weak = ArenaWeak::new(self.generation(), offset)?;
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
|
||||
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
|
||||
unsafe { ptr.write(value) };
|
||||
@@ -124,10 +74,10 @@ impl Arena {
|
||||
self.drops.lock().unwrap().push(DropEntry { offset, drop_fn: glue::<T> });
|
||||
}
|
||||
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
|
||||
Some((unsafe { &*ptr }, weak))
|
||||
Some((unsafe { &*ptr }, ArenaWeak::new(self.generation(), offset)))
|
||||
}
|
||||
|
||||
pub fn alloc_slice_copy<T: Copy + Send + Sync>(&self, src: &[T]) -> Option<&[T]> {
|
||||
pub fn alloc_slice_copy<T: Copy>(&self, src: &[T]) -> Option<&[T]> {
|
||||
let buf = self.alloc_scratch::<T>(src.len())?;
|
||||
for (slot, &value) in buf.iter_mut().zip(src) {
|
||||
slot.write(value);
|
||||
@@ -139,7 +89,7 @@ impl Arena {
|
||||
// Not drop-tracked: callers must either consume every written lane or
|
||||
// restrict themselves to `Copy` payloads (leak, not UB, otherwise).
|
||||
#[allow(clippy::mut_from_ref)]
|
||||
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
|
||||
pub fn alloc_scratch<T>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
|
||||
let size = size_of::<T>().checked_mul(len)?;
|
||||
let offset = self.reserve(size, align_of::<T>())?;
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
|
||||
@@ -148,28 +98,21 @@ impl Arena {
|
||||
Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
|
||||
}
|
||||
|
||||
/// `false` once generations are exhausted, parking the arena on [`PARKED_GENERATION`]
|
||||
/// where every handle misses and further allocation is refused.
|
||||
pub fn reset(&mut self) -> bool {
|
||||
pub fn reset(&mut self) {
|
||||
let base = self.base();
|
||||
let entries = std::mem::take(self.drops.get_mut().unwrap());
|
||||
self.generation.store(PARKED_GENERATION, Ordering::Release);
|
||||
for entry in entries.into_iter().rev() {
|
||||
for entry in self.drops.get_mut().unwrap().drain(..) {
|
||||
// SAFETY: registered at alloc time; insert-only means the region was
|
||||
// never overwritten within this generation.
|
||||
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
|
||||
}
|
||||
*self.offset.get_mut() = 0;
|
||||
let Some(generation) = next_generation() else { return false };
|
||||
self.generation.store(generation, Ordering::Release);
|
||||
true
|
||||
self.generation.fetch_add(1, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Arena {
|
||||
fn drop(&mut self) {
|
||||
self.reset();
|
||||
LIVE_ARENAS.fetch_sub(1, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,22 +131,20 @@ impl<T> Copy for ArenaWeak<T> {}
|
||||
impl<T> ArenaWeak<T> {
|
||||
pub const NULL: Self = ArenaWeak { word: 0, _marker: PhantomData };
|
||||
|
||||
/// `None` once either field leaves its encodable range, so an oversized or parked
|
||||
/// arena refuses to hand out a handle rather than truncating it to a live address.
|
||||
fn new(generation: u64, offset: usize) -> Option<Self> {
|
||||
let offset = u64::try_from(offset).ok().filter(|offset| *offset <= OFFSET_MASK)?;
|
||||
(generation <= GENERATION_MASK).then_some(Self {
|
||||
word: (generation << OFFSET_BITS) | offset,
|
||||
fn new(generation: u64, offset: usize) -> Self {
|
||||
debug_assert!(offset < u32::MAX as usize);
|
||||
Self {
|
||||
word: ((generation & 0xFFFF_FFFF) << 32) | offset as u64,
|
||||
_marker: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub fn upgrade(self, arena: &Arena) -> Option<&T> {
|
||||
let generation = self.word >> OFFSET_BITS;
|
||||
if generation != arena.generation() {
|
||||
let generation = self.word >> 32;
|
||||
if generation != arena.generation() & 0xFFFF_FFFF {
|
||||
return None;
|
||||
}
|
||||
let offset = (self.word & OFFSET_MASK) as usize;
|
||||
let offset = (self.word & 0xFFFF_FFFF) as usize;
|
||||
// SAFETY: same generation means the entry was fully written before its
|
||||
// word was published (Release) and cannot move or be overwritten within
|
||||
// a generation (insert-only); the Acquire load that produced this word
|
||||
@@ -217,21 +158,6 @@ pub struct ArenaCell<T> {
|
||||
_marker: PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T> Clone for ArenaCell<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
word: AtomicU64::new(self.word.load(Ordering::Acquire)),
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for ArenaCell<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ArenaCell").field("word", &self.word.load(Ordering::Relaxed)).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for ArenaCell<T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -262,13 +188,11 @@ impl<T> ArenaCell<T> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
#[test]
|
||||
fn alloc_upgrade_reset_miss() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let mut arena = Arena::new(1024);
|
||||
let cell = ArenaCell::new();
|
||||
let (value, weak) = arena.alloc(41u32).unwrap();
|
||||
assert_eq!(*value, 41);
|
||||
@@ -280,8 +204,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn capacity_survives_reset() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut arena = Arena::new(64 + align_of::<u32>() - 1).unwrap();
|
||||
let mut arena = Arena::new(64 + align_of::<u32>() - 1);
|
||||
for _ in 0..10 {
|
||||
for _ in 0..16 {
|
||||
assert!(arena.alloc(0u32).is_some());
|
||||
@@ -293,7 +216,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn panics_leave_the_arena_coherent() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
fn assert_ref_unwind_safe<T: std::panic::RefUnwindSafe>() {}
|
||||
assert_ref_unwind_safe::<Arena>();
|
||||
|
||||
@@ -304,7 +226,7 @@ mod tests {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let mut arena = Arena::new(1024);
|
||||
let cell = ArenaCell::new();
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
let (_, weak) = arena.alloc(Probe("pre-panic".into())).unwrap();
|
||||
@@ -319,84 +241,8 @@ mod tests {
|
||||
assert!(arena.alloc(0u32).is_some(), "the arena stays usable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panicking_destructor_leaves_no_resolvable_handle() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
struct Bomb;
|
||||
impl Drop for Bomb {
|
||||
fn drop(&mut self) {
|
||||
panic!("payload destructor");
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let cell = ArenaCell::new();
|
||||
let (_, weak) = arena.alloc(Bomb).unwrap();
|
||||
cell.store(weak);
|
||||
|
||||
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
|
||||
assert!(unwound.is_err(), "the panic must propagate out of reset");
|
||||
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
|
||||
}
|
||||
|
||||
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
|
||||
/// is never observed by a concurrently constructing test.
|
||||
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[test]
|
||||
fn an_exhausted_reset_parks_the_arena_and_refuses_handles() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let (_, weak) = arena.alloc(41u32).unwrap();
|
||||
|
||||
let restore = NEXT_GENERATION.swap(GENERATION_MASK + 1, Ordering::Relaxed);
|
||||
assert!(!arena.reset(), "an exhausted counter must report failure");
|
||||
NEXT_GENERATION.store(restore, Ordering::Relaxed);
|
||||
|
||||
assert_eq!(weak.upgrade(&arena), None, "a parked arena resolves no handle");
|
||||
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&arena), None, "not even the null handle");
|
||||
assert!(arena.alloc(0u32).is_none(), "a parked arena refuses allocation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_generation_counter_rewinds_only_without_live_arenas() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
assert!(!unsafe { reset_generation_counter() }, "a live arena must block the rewind");
|
||||
drop(arena);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_do_not_upgrade_against_a_foreign_arena() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let first = Arena::new(1024).unwrap();
|
||||
let second = Arena::new(1024).unwrap();
|
||||
let (_, weak) = first.alloc(41u32).unwrap();
|
||||
assert_eq!(weak.upgrade(&first), Some(&41));
|
||||
assert_eq!(weak.upgrade(&second), None, "a handle must not resolve against another arena");
|
||||
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&second), None, "the null handle never upgrades");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_drops_dependents_before_their_dependencies() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
static ORDER: Mutex<Vec<u32>> = Mutex::new(Vec::new());
|
||||
struct Probe(u32);
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
ORDER.lock().unwrap().push(self.0);
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
for id in 0..3 {
|
||||
arena.alloc(Probe(id)).unwrap();
|
||||
}
|
||||
arena.reset();
|
||||
assert_eq!(*ORDER.lock().unwrap(), vec![2, 1, 0], "later allocations may borrow earlier ones, so they drop first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_glue_runs_on_reset() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
struct Probe(#[allow(dead_code)] String);
|
||||
impl Drop for Probe {
|
||||
@@ -404,7 +250,7 @@ mod tests {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let mut arena = Arena::new(1024);
|
||||
arena.alloc(Probe("owns heap".into())).unwrap();
|
||||
arena.alloc(Probe("me too".into())).unwrap();
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 0);
|
||||
|
||||
@@ -194,120 +194,11 @@ impl ContextFeatures {
|
||||
// CONTEXT DEPENDENCIES
|
||||
// ====================
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, graphene_hash::CacheHash, dyn_any::DynAny, Default)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, graphene_hash::CacheHash, dyn_any::DynAny, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ContextDependencies {
|
||||
pub extract: ContextFeatures,
|
||||
pub inject: ContextFeatures,
|
||||
#[cfg_attr(feature = "serde", serde(default, deserialize_with = "deserialize_sorted_sources"))]
|
||||
sources: Vec<SourceId>,
|
||||
}
|
||||
|
||||
impl ContextDependencies {
|
||||
pub fn new(extract: ContextFeatures, inject: ContextFeatures) -> Self {
|
||||
Self { extract, inject, sources: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn sources(&self) -> &[SourceId] {
|
||||
&self.sources
|
||||
}
|
||||
|
||||
pub fn add_sources(&mut self, sources: &[SourceId]) {
|
||||
merge_sorted_sources(&mut self.sources, sources);
|
||||
}
|
||||
|
||||
pub fn from_sources(sources: &[SourceId]) -> Self {
|
||||
let mut dependencies = Self::default();
|
||||
dependencies.add_sources(sources);
|
||||
dependencies
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, graphene_hash::CacheHash, dyn_any::DynAny, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ContextModification {
|
||||
pub features: ContextFeatures,
|
||||
#[cfg_attr(feature = "serde", serde(deserialize_with = "deserialize_sorted_sources"))]
|
||||
sources: Vec<SourceId>,
|
||||
}
|
||||
|
||||
impl ContextModification {
|
||||
pub fn sources(&self) -> &[SourceId] {
|
||||
&self.sources
|
||||
}
|
||||
|
||||
pub fn add_sources(&mut self, sources: &[SourceId]) {
|
||||
merge_sorted_sources(&mut self.sources, sources);
|
||||
}
|
||||
|
||||
pub fn from_sources(features: ContextFeatures, sources: &[SourceId]) -> Self {
|
||||
let mut modification = Self { features, sources: Vec::new() };
|
||||
modification.add_sources(sources);
|
||||
modification
|
||||
}
|
||||
}
|
||||
|
||||
/// Restores the sorted-and-deduplicated invariant that `contains` and `difference`
|
||||
/// rely on for binary search, which arbitrary serialized input can violate.
|
||||
#[cfg(feature = "serde")]
|
||||
fn deserialize_sorted_sources<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<SourceId>, D::Error> {
|
||||
use serde::Deserialize;
|
||||
let mut sources = Vec::deserialize(deserializer)?;
|
||||
sources.sort_unstable();
|
||||
sources.dedup();
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
impl core::ops::BitOrAssign<&ContextModification> for ContextModification {
|
||||
fn bitor_assign(&mut self, other: &Self) {
|
||||
self.features |= other.features;
|
||||
merge_sorted_sources(&mut self.sources, &other.sources);
|
||||
}
|
||||
}
|
||||
|
||||
impl core::ops::BitOrAssign for ContextModification {
|
||||
fn bitor_assign(&mut self, other: Self) {
|
||||
*self |= &other;
|
||||
}
|
||||
}
|
||||
|
||||
impl core::ops::BitOrAssign<ContextFeatures> for ContextModification {
|
||||
fn bitor_assign(&mut self, features: ContextFeatures) {
|
||||
self.features |= features;
|
||||
}
|
||||
}
|
||||
|
||||
impl core::ops::BitAndAssign<ContextFeatures> for ContextModification {
|
||||
fn bitand_assign(&mut self, features: ContextFeatures) {
|
||||
self.features &= features;
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextModification {
|
||||
pub fn contains(&self, other: &Self) -> bool {
|
||||
debug_assert!(self.sources.is_sorted() && other.sources.is_sorted());
|
||||
self.features.contains(other.features) && other.sources.iter().all(|id| self.sources.binary_search(id).is_ok())
|
||||
}
|
||||
|
||||
pub fn difference(&self, other: &Self) -> Self {
|
||||
debug_assert!(other.sources.is_sorted());
|
||||
Self {
|
||||
features: self.features.difference(other.features),
|
||||
sources: self.sources.iter().copied().filter(|id| other.sources.binary_search(id).is_err()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.features.is_empty() && self.sources.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Sorts and deduplicates unconditionally, so the result is ordered no matter what
|
||||
/// order the inputs arrived in.
|
||||
pub fn merge_sorted_sources(sources: &mut Vec<SourceId>, other: &[SourceId]) {
|
||||
sources.extend_from_slice(other);
|
||||
sources.sort_unstable();
|
||||
sources.dedup();
|
||||
}
|
||||
|
||||
impl From<&[ContextFeature]> for ContextDependencies {
|
||||
@@ -336,7 +227,7 @@ impl From<&[ContextFeature]> for ContextDependencies {
|
||||
_ => ContextFeatures::empty(),
|
||||
};
|
||||
}
|
||||
Self { extract, inject, sources: Vec::new() }
|
||||
Self { extract, inject }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -578,7 +469,8 @@ impl CloneVarArgs for Arc<OwnedContextImpl> {
|
||||
// TYPES `Context` AND `OwnedContextImpl`
|
||||
// ======================================
|
||||
|
||||
pub type Context<'a> = Option<Arc<OwnedContextImpl>>;
|
||||
pub type OwnedContext = Option<Arc<OwnedContextImpl>>;
|
||||
pub type Context<'a> = ContextImpl<'a>;
|
||||
type DynRef<'a> = &'a (dyn Any + Send + Sync);
|
||||
type DynBox = Box<dyn AnyHash + Send + Sync>;
|
||||
|
||||
@@ -835,13 +727,7 @@ pub struct VarArgLink<'a> {
|
||||
pub outer: Option<&'a VarArgLink<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> std::fmt::Debug for VarArgLink<'a> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("VarArgLink").field("args_len", &self.args.len()).field("outer", &self.outer).finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct EvalScope<'a> {
|
||||
real_time: Option<f64>,
|
||||
animation_time: Option<f64>,
|
||||
@@ -861,52 +747,53 @@ impl<'a> EvalScope<'a> {
|
||||
arena,
|
||||
hash: 0,
|
||||
};
|
||||
scope.hash = scope.compute_hash(|_| true);
|
||||
scope.hash = scope.compute_hash(None);
|
||||
scope
|
||||
}
|
||||
|
||||
pub fn retained(&self, retain: &[SourceId]) -> EvalScope<'a> {
|
||||
EvalScope {
|
||||
hash: self.compute_hash(Some(retain)),
|
||||
..*self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_real_time(&self, real_time: Option<f64>) -> EvalScope<'a> {
|
||||
let mut scope = EvalScope { real_time, ..*self };
|
||||
scope.hash = scope.compute_hash(|_| true);
|
||||
scope.hash = scope.compute_hash(None);
|
||||
scope
|
||||
}
|
||||
|
||||
pub fn with_animation_time(&self, animation_time: Option<f64>) -> EvalScope<'a> {
|
||||
let mut scope = EvalScope { animation_time, ..*self };
|
||||
scope.hash = scope.compute_hash(|_| true);
|
||||
scope.hash = scope.compute_hash(None);
|
||||
scope
|
||||
}
|
||||
|
||||
pub fn with_pointer_position(&self, pointer_position: Option<DVec2>) -> EvalScope<'a> {
|
||||
let mut scope = EvalScope { pointer_position, ..*self };
|
||||
scope.hash = scope.compute_hash(|_| true);
|
||||
scope.hash = scope.compute_hash(None);
|
||||
scope
|
||||
}
|
||||
|
||||
pub fn nullified(&self, keep: ContextFeatures, retain: Option<&[SourceId]>) -> EvalScope<'a> {
|
||||
pub fn nullified(&self, keep: ContextFeatures) -> EvalScope<'a> {
|
||||
let mut scope = EvalScope {
|
||||
real_time: self.real_time.filter(|_| keep.contains(ContextFeatures::REAL_TIME)),
|
||||
animation_time: self.animation_time.filter(|_| keep.contains(ContextFeatures::ANIMATION_TIME)),
|
||||
pointer_position: self.pointer_position.filter(|_| keep.contains(ContextFeatures::POINTER_POSITION)),
|
||||
..*self
|
||||
};
|
||||
scope.hash = scope.compute_hash(|source| retain.is_none_or(|retain| retain.contains(source)));
|
||||
scope.hash = scope.compute_hash(None);
|
||||
scope
|
||||
}
|
||||
|
||||
pub fn excluding(&self, source: SourceId) -> EvalScope<'a> {
|
||||
let mut scope = *self;
|
||||
scope.hash = scope.compute_hash(|candidate| *candidate != source);
|
||||
scope
|
||||
}
|
||||
|
||||
fn compute_hash(&self, keep_source: impl Fn(&SourceId) -> bool) -> u64 {
|
||||
fn compute_hash(&self, retain: Option<&[SourceId]>) -> u64 {
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
self.real_time.map(f64::to_bits).hash(&mut hasher);
|
||||
self.animation_time.map(f64::to_bits).hash(&mut hasher);
|
||||
self.pointer_position.map(|position| (position.x.to_bits(), position.y.to_bits())).hash(&mut hasher);
|
||||
for (source, generation) in self.generations {
|
||||
if keep_source(source) {
|
||||
if retain.is_none_or(|retain| retain.contains(source)) {
|
||||
(source, generation).hash(&mut hasher);
|
||||
}
|
||||
}
|
||||
@@ -1006,8 +893,8 @@ pub struct CtxSnapshot {
|
||||
real_time: Option<f64>,
|
||||
animation_time: Option<f64>,
|
||||
pointer_position: Option<DVec2>,
|
||||
index: Option<Vec<usize>>,
|
||||
positions: Option<Vec<DVec2>>,
|
||||
index: Vec<usize>,
|
||||
positions: Vec<DVec2>,
|
||||
varargs: Vec<Vec<OwnedSlot>>,
|
||||
generations: Vec<(SourceId, u64)>,
|
||||
}
|
||||
@@ -1022,8 +909,8 @@ impl CtxSnapshot {
|
||||
real_time: ctx.try_real_time(),
|
||||
animation_time: ctx.try_animation_time(),
|
||||
pointer_position: ctx.try_pointer_position(),
|
||||
index: ctx.try_index().map(|levels| levels.collect()),
|
||||
positions: ctx.try_position().map(|positions| positions.collect()),
|
||||
index: ctx.try_index().map(|levels| levels.collect()).unwrap_or_default(),
|
||||
positions: ctx.try_position().map(|positions| positions.collect()).unwrap_or_default(),
|
||||
varargs: std::iter::successors(ctx.varargs_head(), |link| link.outer)
|
||||
.map(|link| link.args.iter().map(|slot| slot.clone_slot()).collect())
|
||||
.collect(),
|
||||
@@ -1034,6 +921,10 @@ impl CtxSnapshot {
|
||||
pub fn generations(&self) -> &[(SourceId, u64)] {
|
||||
&self.generations
|
||||
}
|
||||
|
||||
pub fn scope<'s>(&'s self, arena: &'s Arena) -> EvalScope<'s> {
|
||||
EvalScope::new(self.real_time, self.animation_time, self.pointer_position, &self.generations, arena)
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtractFootprint for CtxSnapshot {
|
||||
@@ -1062,13 +953,13 @@ impl ExtractPointerPosition for CtxSnapshot {
|
||||
|
||||
impl ExtractIndex for CtxSnapshot {
|
||||
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
|
||||
self.index.as_ref().map(|levels| levels.iter().copied())
|
||||
Some(self.index.iter().copied())
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtractPosition for CtxSnapshot {
|
||||
fn try_position(&self) -> Option<impl Iterator<Item = DVec2>> {
|
||||
self.positions.as_ref().map(|positions| positions.iter().copied())
|
||||
Some(self.positions.iter().copied())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1129,7 +1020,7 @@ impl CtxFamily for ContextImplFamily {
|
||||
type Ctx<'s> = ContextImpl<'s>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ContextImpl<'a> {
|
||||
index: IndexLink<'a>,
|
||||
position: Option<&'a PositionLink<'a>>,
|
||||
@@ -1393,7 +1284,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn equal_contexts_hash_equal() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let arena = Arena::new(64);
|
||||
let generations = [(0, 1), (1, 3)];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let a = ContextImpl::root(&scope);
|
||||
@@ -1403,7 +1294,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn each_axis_changes_the_hash() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let arena = Arena::new(64);
|
||||
let generations = [(0, 1)];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1427,7 +1318,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn index_level_order_matters() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1445,7 +1336,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn axis_boundaries_are_unambiguous() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1463,13 +1354,13 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn retain_scopes_generation_invalidation() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let arena = Arena::new(64);
|
||||
let initial = [(0, 1), (1, 3)];
|
||||
let bumped_unretained = [(0, 2), (1, 3)];
|
||||
let bumped_retained = [(0, 1), (1, 4)];
|
||||
|
||||
let hash_with = |generations: &[(SourceId, u64)]| {
|
||||
let scope = scope_fixture(generations, &arena).nullified(ContextFeatures::all(), Some(&[1]));
|
||||
let scope = scope_fixture(generations, &arena).retained(&[1]);
|
||||
let retained_scope_context = ContextImpl::root(&scope);
|
||||
hash_of(&retained_scope_context)
|
||||
};
|
||||
@@ -1477,24 +1368,9 @@ mod context_impl_tests {
|
||||
assert_ne!(hash_with(&initial), hash_with(&bumped_retained), "retained source bumps must invalidate");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excluding_keys_ignore_own_source_bumps() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let initial = [(7, 1), (9, 5)];
|
||||
let own_bumped = [(7, 2), (9, 5)];
|
||||
let other_bumped = [(7, 1), (9, 6)];
|
||||
|
||||
let hash_with = |generations: &[(SourceId, u64)]| {
|
||||
let scope = scope_fixture(generations, &arena).excluding(7);
|
||||
hash_of(&ContextImpl::root(&scope))
|
||||
};
|
||||
assert_eq!(hash_with(&initial), hash_with(&own_bumped), "a source's own generation bump must not change its slot key");
|
||||
assert_ne!(hash_with(&initial), hash_with(&other_bumped), "bumps of other sources must change the slot key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unretained_scope_sees_every_bump() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let arena = Arena::new(64);
|
||||
let initial = [(0, 1)];
|
||||
let bumped = [(0, 2)];
|
||||
let hash_with = |generations: &[(SourceId, u64)]| {
|
||||
@@ -1506,7 +1382,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn set_index_is_visible_and_keeps_outer_levels() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1519,7 +1395,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn vararg_chain_concatenates_innermost_first() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1550,7 +1426,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn snapshot_captures_vararg_levels() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1593,35 +1469,9 @@ mod context_impl_tests {
|
||||
assert!(matches!(empty.vararg(0), Err(VarArgsResult::NoVarArgs)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sources_are_normalized_regardless_of_insertion_order() {
|
||||
let mut dependencies = ContextDependencies::default();
|
||||
dependencies.add_sources(&[9, 3, 9]);
|
||||
dependencies.add_sources(&[5, 1]);
|
||||
assert_eq!(dependencies.sources(), &[1, 3, 5, 9]);
|
||||
|
||||
let modification = ContextModification::from_sources(ContextFeatures::empty(), &[7, 2, 7]);
|
||||
assert_eq!(modification.sources(), &[2, 7]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_snapshot_preserves_an_absent_position_axis() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
|
||||
let absent = CtxSnapshot::capture(&root);
|
||||
assert!(absent.try_position().is_none(), "capturing an unpositioned context must not invent a position stack");
|
||||
|
||||
let position = DVec2::new(1., 2.);
|
||||
let positioned = CtxSnapshot::capture(&root.with_position(&PositionLink { position, outer: None }));
|
||||
assert_eq!(positioned.try_position().map(|p| p.collect::<Vec<_>>()), Some(vec![position]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_arena_reaches_kernels_through_extract_arena() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::gpoll::Finality;
|
||||
use std::cell::UnsafeCell;
|
||||
use std::mem::{ManuallyDrop, MaybeUninit};
|
||||
use std::mem::MaybeUninit;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
|
||||
|
||||
const SLOT_EMPTY: u8 = 0;
|
||||
@@ -45,8 +45,8 @@ impl<T, const CAP: usize> FrameTable<T, CAP> {
|
||||
}
|
||||
|
||||
pub fn lookup(&self, hash: u64) -> Lookup<'_, T> {
|
||||
// Only hash 0 is remapped, so distinct hashes stay distinct keys.
|
||||
let key = if hash == 0 { 1 } else { hash };
|
||||
// Keys are forced odd so the empty sentinel (0) can never collide.
|
||||
let key = hash | 1;
|
||||
for probe in 0..CAP {
|
||||
let slot = &self.slots[(key as usize).wrapping_add(probe) % CAP];
|
||||
let stored = slot.key.load(Ordering::Acquire);
|
||||
@@ -81,27 +81,18 @@ impl<T, const CAP: usize> Drop for FrameTable<T, CAP> {
|
||||
|
||||
impl<'t, T> VacantSlot<'t, T> {
|
||||
pub fn publish(self, value: T, finality: Finality) -> &'t T {
|
||||
let slot = ManuallyDrop::new(self).slot;
|
||||
// SAFETY: the CAS in `lookup` reserved this slot exclusively for us and
|
||||
// its state is still SLOT_EMPTY, so nobody reads the value yet.
|
||||
let lent = unsafe { &*(*slot.value.get()).write(value) };
|
||||
let lent = unsafe { &*(*self.slot.value.get()).write(value) };
|
||||
let state = match finality {
|
||||
Finality::AllFinal => SLOT_FINAL,
|
||||
Finality::Partial => SLOT_PARTIAL,
|
||||
};
|
||||
slot.state.store(state, Ordering::Release);
|
||||
self.slot.state.store(state, Ordering::Release);
|
||||
lent
|
||||
}
|
||||
|
||||
pub fn release(self) {
|
||||
drop(self);
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees the reservation, so an early return or panic between `lookup` and
|
||||
/// `publish` cannot retire the slot for the rest of the table's life.
|
||||
impl<T> Drop for VacantSlot<'_, T> {
|
||||
fn drop(&mut self) {
|
||||
self.slot.key.store(0, Ordering::Release);
|
||||
}
|
||||
}
|
||||
@@ -132,33 +123,6 @@ mod tests {
|
||||
assert!(matches!(table.lookup(7), Lookup::Vacant(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_reservation_frees_the_slot() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
|
||||
drop(slot);
|
||||
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an abandoned reservation must not retire the slot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighboring_hashes_do_not_share_an_entry() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(6) else { unreachable!() };
|
||||
slot.publish(600, Finality::AllFinal);
|
||||
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an even hash must not answer for its odd neighbor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_zero_hash_round_trips() {
|
||||
let table = FrameTable::<u32, 8>::new();
|
||||
let Lookup::Vacant(slot) = table.lookup(0) else { unreachable!() };
|
||||
slot.publish(11, Finality::AllFinal);
|
||||
let Lookup::Hit(_, value) = table.lookup(0) else {
|
||||
panic!("the remapped sentinel hash must still hit");
|
||||
};
|
||||
assert_eq!(*value, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distinct_keys_probe_past_collisions_until_full() {
|
||||
let table = FrameTable::<u32, 4>::new();
|
||||
|
||||
+42
-118
@@ -7,48 +7,13 @@ use std::ops::Range;
|
||||
#[derive(Debug)]
|
||||
pub enum BatchStatus<'a, T> {
|
||||
Lent(&'a [T], Finality),
|
||||
Filled(FilledBatch<'a, T>, Finality),
|
||||
Filled(&'a mut [T], Finality),
|
||||
Pending,
|
||||
Error(GraphError),
|
||||
NeedBuffer,
|
||||
InvalidRange,
|
||||
}
|
||||
|
||||
/// Owns the initialized prefix of a caller-supplied scratch buffer, dropping every
|
||||
/// lane unless [`FilledBatch::into_values`] hands the obligation back to the caller.
|
||||
#[derive(Debug)]
|
||||
pub struct FilledBatch<'a, T> {
|
||||
values: &'a mut [T],
|
||||
}
|
||||
|
||||
impl<'a, T> FilledBatch<'a, T> {
|
||||
/// # Safety
|
||||
///
|
||||
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
|
||||
pub unsafe fn new(scratch: &'a mut [MaybeUninit<T>], len: usize) -> Self {
|
||||
Self {
|
||||
values: unsafe { assume_init_prefix_mut(scratch, len) },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn values(&self) -> &[T] {
|
||||
self.values
|
||||
}
|
||||
|
||||
pub fn into_values(self) -> &'a mut [T] {
|
||||
let mut guard = std::mem::ManuallyDrop::new(self);
|
||||
std::mem::take(&mut guard.values)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for FilledBatch<'_, T> {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: every lane was initialized when the guard was built and none has
|
||||
// been moved out, since `into_values` consumes the guard instead.
|
||||
unsafe { std::ptr::drop_in_place(self.values as *mut [T]) }
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
///
|
||||
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
|
||||
@@ -57,7 +22,7 @@ pub unsafe fn assume_init_prefix_mut<T>(scratch: &mut [MaybeUninit<T>], len: usi
|
||||
unsafe { std::slice::from_raw_parts_mut(scratch.as_mut_ptr().cast::<T>(), len) }
|
||||
}
|
||||
|
||||
pub trait Node<Input> {
|
||||
pub trait GNode<Input> {
|
||||
type Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output>;
|
||||
@@ -66,11 +31,6 @@ pub trait Node<Input> {
|
||||
GPoll::Final(Extent::Free)
|
||||
}
|
||||
|
||||
/// Introspection access to node-resident records; `None` for ordinary nodes.
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
None
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -78,7 +38,7 @@ pub trait Node<Input> {
|
||||
let Some(scratch) = scratch else {
|
||||
return BatchStatus::NeedBuffer;
|
||||
};
|
||||
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
|
||||
let Some(len) = range.end.checked_sub(range.start).map(|len| len as usize) else {
|
||||
return BatchStatus::InvalidRange;
|
||||
};
|
||||
if scratch.len() < len {
|
||||
@@ -111,13 +71,13 @@ pub trait Node<Input> {
|
||||
}
|
||||
}
|
||||
// SAFETY: all `len` lanes were written by the loop above.
|
||||
BatchStatus::Filled(unsafe { FilledBatch::new(scratch, len) }, finality)
|
||||
BatchStatus::Filled(unsafe { assume_init_prefix_mut(scratch, len) }, finality)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input, N> Node<Input> for &N
|
||||
impl<Input, N> GNode<Input> for &N
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
N: GNode<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
@@ -129,10 +89,6 @@ where
|
||||
(**self).extent(input)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
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,9 +97,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input, N> Node<Input> for Box<N>
|
||||
impl<Input, N> GNode<Input> for Box<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
N: GNode<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
@@ -155,36 +111,6 @@ where
|
||||
(**self).extent(input)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
|
||||
where
|
||||
Input: InjectIndex + Copy,
|
||||
{
|
||||
(**self).eval_batch(input, range, scratch)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Input, N> Node<Input> for std::sync::Arc<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
|
||||
(**self).eval(input)
|
||||
}
|
||||
|
||||
fn extent(&self, input: &Input) -> GPoll<Extent> {
|
||||
(**self).extent(input)
|
||||
}
|
||||
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
|
||||
fn 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,
|
||||
@@ -215,10 +141,13 @@ impl StatusCell {
|
||||
}
|
||||
|
||||
pub fn no_partial() -> Self {
|
||||
Self { no_partial: true, ..Self::new() }
|
||||
Self {
|
||||
no_partial: true,
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eval_input<Input, N: Node<Input>>(&self, input_index: usize, node: &N, input: &Input) -> Result<N::Output, Interrupt> {
|
||||
pub fn eval_input<Input, N: GNode<Input>>(&self, input_index: usize, node: &N, input: &Input) -> Result<N::Output, Interrupt> {
|
||||
match node.eval(input) {
|
||||
GPoll::Final(value) => Ok(value),
|
||||
GPoll::Partial(_) if self.no_partial => Err(Interrupt::Pending),
|
||||
@@ -280,12 +209,34 @@ impl<'a, N> LazyInput<'a, N> {
|
||||
|
||||
pub fn eval<Input>(&self, ctx: &Input) -> Result<N::Output, Interrupt>
|
||||
where
|
||||
N: Node<Input>,
|
||||
N: GNode<Input>,
|
||||
{
|
||||
self.cell.eval_input(self.input_index, self.node, ctx)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Input, N> GNode<Input> for LazyInput<'a, N>
|
||||
where
|
||||
N: GNode<Input>,
|
||||
{
|
||||
type Output = N::Output;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
|
||||
self.node.eval(input)
|
||||
}
|
||||
|
||||
fn extent(&self, input: &Input) -> GPoll<Extent> {
|
||||
self.node.extent(input)
|
||||
}
|
||||
|
||||
fn eval_batch<'b>(&self, input: &'b Input, range: Range<u64>, scratch: Option<&'b mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'b, Self::Output>
|
||||
where
|
||||
Input: InjectIndex + Copy,
|
||||
{
|
||||
self.node.eval_batch(input, range, scratch)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -304,7 +255,7 @@ mod tests {
|
||||
|
||||
struct Double;
|
||||
|
||||
impl Node<TestInput> for Double {
|
||||
impl GNode<TestInput> for Double {
|
||||
type Output = u64;
|
||||
|
||||
fn eval(&self, input: &TestInput) -> GPoll<u64> {
|
||||
@@ -320,37 +271,10 @@ mod tests {
|
||||
let BatchStatus::Filled(lanes, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
assert_eq!(lanes.values(), &[4, 6, 8, 10]);
|
||||
assert_eq!(lanes, &[4, 6, 8, 10]);
|
||||
assert_eq!(finality, Finality::AllFinal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_filled_batch_reclaims_every_lane() {
|
||||
static DROPS: AtomicU32 = AtomicU32::new(0);
|
||||
#[derive(Clone)]
|
||||
struct Probe;
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
struct Probes;
|
||||
impl Node<TestInput> for Probes {
|
||||
type Output = Probe;
|
||||
|
||||
fn eval(&self, _input: &TestInput) -> GPoll<Probe> {
|
||||
GPoll::Final(Probe)
|
||||
}
|
||||
}
|
||||
|
||||
let input = TestInput { index: 0 };
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 3];
|
||||
let status = Probes.eval_batch(&input, 0..3, Some(&mut scratch));
|
||||
assert!(matches!(status, BatchStatus::Filled(..)));
|
||||
drop(status);
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 3, "an unconsumed batch must not leak its lanes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_without_scratch_requests_a_buffer() {
|
||||
let input = TestInput { index: 0 };
|
||||
@@ -367,7 +291,7 @@ mod tests {
|
||||
#[test]
|
||||
fn partial_lane_downgrades_batch_finality() {
|
||||
struct PartialAtThree;
|
||||
impl Node<TestInput> for PartialAtThree {
|
||||
impl GNode<TestInput> for PartialAtThree {
|
||||
type Output = u64;
|
||||
fn eval(&self, input: &TestInput) -> GPoll<u64> {
|
||||
match input.index {
|
||||
@@ -382,7 +306,7 @@ mod tests {
|
||||
let BatchStatus::Filled(lanes, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
assert_eq!(lanes.values(), &[0, 1, 2, 3]);
|
||||
assert_eq!(lanes, &[0, 1, 2, 3]);
|
||||
assert_eq!(finality, Finality::Partial);
|
||||
}
|
||||
|
||||
@@ -396,7 +320,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
struct PendingAtTwo;
|
||||
impl Node<TestInput> for PendingAtTwo {
|
||||
impl GNode<TestInput> for PendingAtTwo {
|
||||
type Output = Probe;
|
||||
fn eval(&self, input: &TestInput) -> GPoll<Probe> {
|
||||
match input.index {
|
||||
@@ -414,7 +338,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn trait_is_object_safe_across_erased_edges() {
|
||||
let erased: Box<dyn Node<TestInput, Output = u64>> = Box::new(Double);
|
||||
let erased: Box<dyn GNode<TestInput, Output = u64>> = Box::new(Double);
|
||||
let input = TestInput { index: 21 };
|
||||
assert_eq!(erased.eval(&input), GPoll::Final(42));
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 2];
|
||||
@@ -2,7 +2,6 @@
|
||||
pub enum ErrorKind {
|
||||
Node(&'static str),
|
||||
ArenaExhausted,
|
||||
Panic,
|
||||
}
|
||||
|
||||
impl PartialEq<&str> for ErrorKind {
|
||||
@@ -132,13 +131,6 @@ impl<T> GPoll<T> {
|
||||
trace: Vec::new(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn panicked() -> Self {
|
||||
GPoll::Error(Box::new(GraphError {
|
||||
kind: ErrorKind::Panic,
|
||||
trace: Vec::new(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
||||
@@ -6,12 +6,12 @@ pub mod consts;
|
||||
pub mod context;
|
||||
pub mod frame_table;
|
||||
pub mod generic;
|
||||
pub mod gnode;
|
||||
pub mod gpoll;
|
||||
pub mod list;
|
||||
pub mod math;
|
||||
pub mod memo;
|
||||
pub mod misc;
|
||||
pub mod node;
|
||||
pub mod ops;
|
||||
pub mod registry;
|
||||
pub mod render_complexity;
|
||||
@@ -19,6 +19,7 @@ pub mod runtime;
|
||||
pub mod transform;
|
||||
pub mod uuid;
|
||||
pub mod value;
|
||||
pub mod wire;
|
||||
|
||||
pub use crate as core_types;
|
||||
pub use blending::*;
|
||||
|
||||
@@ -44,13 +44,13 @@ impl<'i, N: for<'a> Node<'a, I> + Copy, I: 'i> Copy for TypeNode<N, I, <N as Nod
|
||||
pub trait Convert<T, C>: Sized {
|
||||
/// Converts this type into the (usually inferred) output type.
|
||||
#[must_use]
|
||||
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send;
|
||||
fn convert(self, footprint: Footprint, converter: C) -> T;
|
||||
}
|
||||
|
||||
impl<T: ToString + Send> Convert<String, ()> for T {
|
||||
/// Converts this type into a `String` using its `ToString` implementation.
|
||||
#[inline]
|
||||
async fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||
fn convert(self, _: Footprint, _converter: ()) -> String {
|
||||
self.to_string()
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@ pub trait ListConvert<U> {
|
||||
}
|
||||
|
||||
impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
|
||||
async fn convert(self, _: Footprint, _: ()) -> List<U> {
|
||||
fn convert(self, _: Footprint, _: ()) -> List<U> {
|
||||
let list: List<U> = self
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
@@ -76,7 +76,7 @@ impl<U, T: ListConvert<U> + Send> Convert<List<U>, ()> for List<T> {
|
||||
/// from any `List<U>` express their signature as `AttributeDyn` and avoid monomorphizing
|
||||
/// 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> {
|
||||
async fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
|
||||
fn convert(self, _: Footprint, _: ()) -> AttributeDyn {
|
||||
let values: Vec<T> = self.into_iter().map(|row| row.into_element()).collect();
|
||||
AttributeDyn(Box::new(Attribute(values)))
|
||||
}
|
||||
@@ -86,7 +86,7 @@ impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash
|
||||
/// (such as `write_attribute`'s value-producing input) be generic over the destination list type
|
||||
/// 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 {
|
||||
async fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
|
||||
fn convert(self, _: Footprint, _: ()) -> AttributeValueDyn {
|
||||
AttributeValueDyn(Box::new(self))
|
||||
}
|
||||
}
|
||||
@@ -95,13 +95,13 @@ impl<T: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash
|
||||
/// only need attribute access (such as the `read_attribute_*` family) take a single `ListDyn` input
|
||||
/// instead of monomorphizing over every possible carrier list type.
|
||||
impl<T: Send> Convert<ListDyn, ()> for List<T> {
|
||||
async fn convert(self, _: Footprint, _: ()) -> ListDyn {
|
||||
fn convert(self, _: Footprint, _: ()) -> ListDyn {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Convert<DVec2, ()> for DVec2 {
|
||||
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -115,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 {
|
||||
async fn convert(self, _: Footprint, _: ()) -> List<T> {
|
||||
fn convert(self, _: Footprint, _: ()) -> List<T> {
|
||||
List::new_from_item(Item::new_from_element(T::from_anchor_position(self)))
|
||||
}
|
||||
}
|
||||
@@ -124,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 {
|
||||
async fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
fn convert(self, _: Footprint, _: ()) -> $to {
|
||||
self as $to
|
||||
}
|
||||
}
|
||||
@@ -146,7 +146,7 @@ macro_rules! impl_convert {
|
||||
impl_convert!(usize, $to);
|
||||
|
||||
impl Convert<DVec2, ()> for $to {
|
||||
async fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
fn convert(self, _: Footprint, _: ()) -> DVec2 {
|
||||
DVec2::splat(self as f64)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
use crate::SourceId;
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type SourceFuture<T = ()> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
|
||||
@@ -22,13 +20,6 @@ pub trait Runtime {
|
||||
#[derive(Clone)]
|
||||
pub struct RuntimeHandle(pub Arc<DynRuntime>);
|
||||
|
||||
// SAFETY: wasm is single threaded, so the handle never actually crosses a thread.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Send for RuntimeHandle {}
|
||||
// SAFETY: as in Send.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for RuntimeHandle {}
|
||||
|
||||
impl std::fmt::Debug for RuntimeHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RuntimeHandle").finish_non_exhaustive()
|
||||
@@ -39,110 +30,243 @@ impl graphene_hash::CacheHash for RuntimeHandle {
|
||||
fn cache_hash<H: std::hash::Hasher>(&self, _state: &mut H) {}
|
||||
}
|
||||
|
||||
pub trait Spawner {
|
||||
fn spawn(&self, task: SourceFuture);
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::arena::Arena;
|
||||
use crate::context::{ContextImpl, Ctx, CtxSnapshot, EvalScope, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots};
|
||||
use crate::gnode::GNode;
|
||||
use crate::gpoll::GPoll;
|
||||
use crate::transform::Footprint;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type DynSpawner = dyn Spawner + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type DynSpawner = dyn Spawner;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type DynNotifier = dyn Fn() + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type DynNotifier = dyn Fn();
|
||||
|
||||
impl<S: Spawner + ?Sized> Spawner for Box<S> {
|
||||
fn spawn(&self, task: SourceFuture) {
|
||||
(**self).spawn(task)
|
||||
#[derive(Default)]
|
||||
struct MockRuntime {
|
||||
futures: Mutex<Vec<(SourceId, SourceFuture)>>,
|
||||
}
|
||||
}
|
||||
|
||||
/// Dropped tasks never complete.
|
||||
pub struct NoopSpawner;
|
||||
|
||||
impl Spawner for NoopSpawner {
|
||||
fn spawn(&self, _task: SourceFuture) {
|
||||
log::warn!("async source spawned before a host spawner is wired; the task is dropped");
|
||||
}
|
||||
}
|
||||
|
||||
pub type DynGraphRuntime = GraphRuntime<Box<DynSpawner>>;
|
||||
|
||||
impl Default for RuntimeHandle {
|
||||
fn default() -> Self {
|
||||
Self(Arc::new(GraphRuntime::new(Box::new(NoopSpawner) as Box<DynSpawner>)))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GraphRuntime<S> {
|
||||
generations: Arc<Mutex<HashMap<SourceId, u64>>>,
|
||||
dirty: Arc<AtomicBool>,
|
||||
notifier: Arc<Mutex<Arc<DynNotifier>>>,
|
||||
spawner: S,
|
||||
}
|
||||
|
||||
// SAFETY: wasm is single threaded, so the runtime never actually crosses a thread.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl<S> Send for GraphRuntime<S> {}
|
||||
// SAFETY: as in Send.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl<S> Sync for GraphRuntime<S> {}
|
||||
|
||||
impl<S> GraphRuntime<S> {
|
||||
pub fn new(spawner: S) -> Self {
|
||||
Self {
|
||||
generations: Arc::default(),
|
||||
dirty: Arc::default(),
|
||||
notifier: Arc::new(Mutex::new(Arc::new(|| {}))),
|
||||
spawner,
|
||||
impl Runtime for MockRuntime {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) {
|
||||
self.futures.lock().unwrap().push((source, future));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_notifier(&self, notifier: Arc<DynNotifier>) {
|
||||
*self.notifier.lock().unwrap_or_else(PoisonError::into_inner) = notifier;
|
||||
}
|
||||
|
||||
pub fn retain_sources(&self, live: &[SourceId]) {
|
||||
let mut generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
generations.retain(|source, _| live.contains(source));
|
||||
for source in live {
|
||||
generations.entry(*source).or_insert(0);
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Vec<(SourceId, u64)> {
|
||||
let generations = self.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect();
|
||||
snapshot.sort_unstable();
|
||||
snapshot
|
||||
struct SourceNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> GNode<Input> for SourceNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_dirty(&self) -> bool {
|
||||
self.dirty.swap(false, Ordering::Acquire)
|
||||
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.
|
||||
}
|
||||
|
||||
pub fn spawner(&self) -> &S {
|
||||
&self.spawner
|
||||
fn stand_in(_value: &f64) -> f64 {
|
||||
-1.
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Spawner> Runtime for GraphRuntime<S> {
|
||||
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);
|
||||
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();
|
||||
#[node_macro::node(category(""), placeholder(stand_in))]
|
||||
async fn preview_double(_: impl Ctx, value: f64) -> f64 {
|
||||
value * 2.
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), placeholder(stand_in), no_partial)]
|
||||
async fn strict_double(_: impl Ctx, value: f64) -> f64 {
|
||||
value * 2.
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn snapshot_resolution(ctx: CtxSnapshot, _primary: ()) -> u32 {
|
||||
ctx.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn snapshot_vararg(ctx: CtxSnapshot, _primary: ()) -> f64 {
|
||||
ctx.vararg(0).ok().and_then(|slot| slot.downcast_ref::<f64>()).copied().unwrap_or(0.)
|
||||
}
|
||||
|
||||
static STAGED_RUNS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn staged_double(_: impl Ctx, value: f64) -> SourceFuture<f64> {
|
||||
STAGED_RUNS.fetch_add(1, Ordering::Relaxed);
|
||||
Box::pin(async move { value * 2. })
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn staged_sum(ctx: impl Ctx, value: f64, addend: impl Node<Context<'_>, Output = f64>) -> Result<SourceFuture<f64>, crate::gpoll::Interrupt> {
|
||||
let addend = addend.eval(ctx)?;
|
||||
Ok(Box::pin(async move { value + addend }))
|
||||
}
|
||||
|
||||
struct GatedSource(Arc<std::sync::atomic::AtomicBool>, f64);
|
||||
|
||||
impl<Input> GNode<Input> for GatedSource {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
match self.0.load(Ordering::Relaxed) {
|
||||
true => GPoll::Final(self.1),
|
||||
false => GPoll::Pending,
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(None, None, None, generations, arena)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_source_spawns_once_and_lands_via_the_slot() {
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = SlowDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(7u64));
|
||||
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(runtime.drain(), vec![7]);
|
||||
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
assert_eq!(SLOW_DOUBLE_RUNS.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_source_reports_the_placeholder_while_in_flight() {
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = PreviewDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(1u64));
|
||||
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Partial(-1.0));
|
||||
runtime.drain();
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_partial_maps_the_placeholder_frame_to_pending() {
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = StrictDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(2u64));
|
||||
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
|
||||
runtime.drain();
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prologue_runs_sync_and_spawns_once() {
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = StagedDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(8u64));
|
||||
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "the prologue runs synchronously on the miss");
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "in flight must not rerun the prologue");
|
||||
assert_eq!(runtime.drain(), vec![8]);
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prologue_interrupt_defers_the_spawn() {
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let gate = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = StagedSumNode::new(
|
||||
SourceNode(40.0f64),
|
||||
GatedSource(gate.clone(), 2.0),
|
||||
SourceNode(RuntimeHandle(runtime.clone())),
|
||||
SourceNode(9u64),
|
||||
);
|
||||
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(runtime.drain(), Vec::<SourceId>::new(), "an interrupted prologue must not spawn or claim the slot");
|
||||
gate.store(true, Ordering::Relaxed);
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
|
||||
assert_eq!(runtime.drain(), vec![9]);
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_kernels_read_captured_varargs() {
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
let payload = 21.5f64;
|
||||
let link = VarArgLink {
|
||||
args: VarArgSlots::Single(&payload),
|
||||
outer: None,
|
||||
};
|
||||
let ctx = root.with_varargs(&link);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = SnapshotVarargNode::new(SourceNode(()), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(5u64));
|
||||
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
|
||||
runtime.drain();
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(21.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_kernels_read_the_captured_context_snapshot() {
|
||||
let arena = Arena::new(64);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
let footprint = Footprint::DEFAULT;
|
||||
let ctx = root.with_footprint(&footprint);
|
||||
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let graph = SnapshotResolutionNode::new(SourceNode(()), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(3u64));
|
||||
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Pending);
|
||||
runtime.drain();
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(Footprint::DEFAULT.resolution.x));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
use crate::Type;
|
||||
use crate::arena::{Arena, ArenaCell};
|
||||
use crate::concrete;
|
||||
use crate::context::{ContextImpl, Ctx, ExtractArena};
|
||||
use crate::frame_table::{FrameTable, Lookup};
|
||||
use crate::gnode::GNode;
|
||||
use crate::gpoll::{Extent, Finality, GPoll};
|
||||
use graphene_hash::CacheHash;
|
||||
use std::any::Any;
|
||||
use std::hash::Hasher;
|
||||
use std::sync::Mutex;
|
||||
|
||||
pub type ErasedGNode<T> = dyn for<'c> GNode<ContextImpl<'c>, Output = T>;
|
||||
pub type ErasedLendGNode<T> = dyn for<'c> GNode<ContextImpl<'c>, Output = &'c T>;
|
||||
|
||||
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
ctx.cache_hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum WireError {
|
||||
Arity { expected: usize, got: usize },
|
||||
Type { expected: Type, found: Type },
|
||||
MissingCapability { ty: Type },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct WireCapabilities {
|
||||
pub memoize: Option<fn(EdgeHandle) -> Result<EdgeHandle, WireError>>,
|
||||
pub lend: Option<fn(EdgeHandle) -> Result<EdgeHandle, WireError>>,
|
||||
}
|
||||
|
||||
fn memoize_edge<T: Clone + 'static>(edge: EdgeHandle) -> Result<EdgeHandle, WireError> {
|
||||
let content = edge.downcast::<T>()?;
|
||||
Ok(EdgeHandle::new(Box::new(MemoizeNode::new(content)) as Box<ErasedGNode<T>>))
|
||||
}
|
||||
|
||||
fn lend_edge<T: Clone + 'static>(edge: EdgeHandle) -> Result<EdgeHandle, WireError> {
|
||||
let content = edge.downcast::<T>()?;
|
||||
Ok(EdgeHandle::new_ref(Box::new(FrameMemoNode::new(content)) as Box<ErasedLendGNode<T>>))
|
||||
}
|
||||
|
||||
pub struct EdgeHandle {
|
||||
node: Box<dyn Any>,
|
||||
ty: Type,
|
||||
capabilities: WireCapabilities,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EdgeHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EdgeHandle").field("ty", &self.ty).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl EdgeHandle {
|
||||
pub fn new<T: Clone + 'static>(node: Box<ErasedGNode<T>>) -> Self {
|
||||
Self::new_erased(
|
||||
node,
|
||||
concrete!(T),
|
||||
WireCapabilities {
|
||||
memoize: Some(memoize_edge::<T>),
|
||||
lend: Some(lend_edge::<T>),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new_ref<T: 'static>(node: Box<ErasedLendGNode<T>>) -> Self {
|
||||
Self::new_erased(node, Type::Ref(Box::new(concrete!(T))), WireCapabilities::default())
|
||||
}
|
||||
|
||||
pub fn new_erased<N: ?Sized>(node: Box<N>, ty: Type, capabilities: WireCapabilities) -> Self
|
||||
where
|
||||
Box<N>: Any,
|
||||
{
|
||||
Self {
|
||||
node: Box::new(node),
|
||||
ty,
|
||||
capabilities,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wire_type(&self) -> &Type {
|
||||
&self.ty
|
||||
}
|
||||
|
||||
pub fn memoized(self) -> Result<EdgeHandle, WireError> {
|
||||
match self.capabilities.memoize {
|
||||
Some(wrap) => wrap(self),
|
||||
None => Err(WireError::MissingCapability { ty: self.ty }),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lent(self) -> Result<EdgeHandle, WireError> {
|
||||
match self.capabilities.lend {
|
||||
Some(wrap) => wrap(self),
|
||||
None => Err(WireError::MissingCapability { ty: self.ty }),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn downcast<T: 'static>(self) -> Result<Box<ErasedGNode<T>>, WireError> {
|
||||
self.downcast_erased(concrete!(T))
|
||||
}
|
||||
|
||||
pub fn downcast_lend<T: 'static>(self) -> Result<Box<ErasedLendGNode<T>>, WireError> {
|
||||
self.downcast_erased(Type::Ref(Box::new(concrete!(T))))
|
||||
}
|
||||
|
||||
pub fn downcast_erased<N: ?Sized>(self, expected: Type) -> Result<Box<N>, WireError>
|
||||
where
|
||||
Box<N>: Any,
|
||||
{
|
||||
let found = self.ty;
|
||||
self.node.downcast::<Box<N>>().map(|node| *node).map_err(|_| WireError::Type { expected, found })
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NodeIoRecord {
|
||||
pub inputs: Vec<Type>,
|
||||
pub output: Type,
|
||||
}
|
||||
|
||||
pub struct RegistryEntry {
|
||||
pub io: NodeIoRecord,
|
||||
pub wire: fn(Vec<EdgeHandle>) -> Result<EdgeHandle, WireError>,
|
||||
}
|
||||
|
||||
pub fn resolve_and_wire(entry: &RegistryEntry, inputs: Vec<EdgeHandle>) -> Result<EdgeHandle, WireError> {
|
||||
if inputs.len() != entry.io.inputs.len() {
|
||||
return Err(WireError::Arity {
|
||||
expected: entry.io.inputs.len(),
|
||||
got: inputs.len(),
|
||||
});
|
||||
}
|
||||
for (handle, expected) in inputs.iter().zip(&entry.io.inputs) {
|
||||
if handle.wire_type() != expected {
|
||||
return Err(WireError::Type {
|
||||
expected: expected.clone(),
|
||||
found: handle.wire_type().clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
(entry.wire)(inputs)
|
||||
}
|
||||
|
||||
pub struct MemoizeNode<T, NodeContent> {
|
||||
cache: Mutex<Option<(u64, T, Finality)>>,
|
||||
content: NodeContent,
|
||||
}
|
||||
|
||||
impl<T, NodeContent> MemoizeNode<T, NodeContent> {
|
||||
pub fn new(content: NodeContent) -> Self {
|
||||
Self {
|
||||
cache: Mutex::new(None),
|
||||
content,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Input, NodeContent> GNode<Input> for MemoizeNode<T, NodeContent>
|
||||
where
|
||||
T: Clone,
|
||||
Input: Ctx + CacheHash,
|
||||
NodeContent: GNode<Input, Output = T>,
|
||||
{
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<T> {
|
||||
let key = cache_key(input);
|
||||
if let Some((hash, value, finality)) = self.cache.lock().unwrap().as_ref() {
|
||||
if *hash == key {
|
||||
return match finality {
|
||||
Finality::AllFinal => GPoll::Final(value.clone()),
|
||||
Finality::Partial => GPoll::Partial(value.clone()),
|
||||
};
|
||||
}
|
||||
}
|
||||
let result = self.content.eval(input);
|
||||
match &result {
|
||||
GPoll::Final(value) => *self.cache.lock().unwrap() = Some((key, value.clone(), Finality::AllFinal)),
|
||||
GPoll::Partial(value) => *self.cache.lock().unwrap() = Some((key, value.clone(), Finality::Partial)),
|
||||
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => {}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn extent(&self, input: &Input) -> GPoll<Extent> {
|
||||
self.content.extent(input)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FrameMemoNode<T, NodeContent> {
|
||||
cell: ArenaCell<FrameTable<T, 32>>,
|
||||
content: NodeContent,
|
||||
}
|
||||
|
||||
impl<T, NodeContent> FrameMemoNode<T, NodeContent> {
|
||||
pub fn new(content: NodeContent) -> Self {
|
||||
Self {
|
||||
cell: ArenaCell::new(),
|
||||
content,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e, T, Input, NodeContent> GNode<Input> for FrameMemoNode<T, NodeContent>
|
||||
where
|
||||
T: Clone + 'static,
|
||||
Input: Ctx + CacheHash + ExtractArena<ArenaRef = &'e Arena>,
|
||||
NodeContent: GNode<Input, Output = T>,
|
||||
{
|
||||
type Output = &'e T;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<&'e T> {
|
||||
let arena = input.arena();
|
||||
let table = match self.cell.load(arena) {
|
||||
Some(table) => table,
|
||||
None => match arena.alloc(FrameTable::new()) {
|
||||
Some((table, weak)) => {
|
||||
self.cell.store(weak);
|
||||
table
|
||||
}
|
||||
None => return park(arena, self.content.eval(input)),
|
||||
},
|
||||
};
|
||||
match table.lookup(cache_key(input)) {
|
||||
Lookup::Hit(Finality::AllFinal, value) => GPoll::Final(value),
|
||||
Lookup::Hit(Finality::Partial, value) => GPoll::Partial(value),
|
||||
Lookup::Vacant(slot) => match self.content.eval(input) {
|
||||
GPoll::Final(value) => GPoll::Final(slot.publish(value, Finality::AllFinal)),
|
||||
GPoll::Partial(value) => GPoll::Partial(slot.publish(value, Finality::Partial)),
|
||||
unpublishable => {
|
||||
slot.release();
|
||||
park(arena, unpublishable)
|
||||
}
|
||||
},
|
||||
Lookup::Full => park(arena, self.content.eval(input)),
|
||||
}
|
||||
}
|
||||
|
||||
fn extent(&self, input: &Input) -> GPoll<Extent> {
|
||||
self.content.extent(input)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn park<'e, T>(arena: &'e Arena, result: GPoll<T>) -> GPoll<&'e T> {
|
||||
match result {
|
||||
GPoll::Final(value) => match arena.alloc(value) {
|
||||
Some((parked, _)) => GPoll::Final(parked),
|
||||
None => GPoll::arena_exhausted(),
|
||||
},
|
||||
GPoll::Partial(value) => match arena.alloc(value) {
|
||||
Some((parked, _)) => GPoll::Partial(parked),
|
||||
None => GPoll::arena_exhausted(),
|
||||
},
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
match arena.alloc(value) {
|
||||
Some((parked, _)) => GPoll::Fallback(Box::new((parked, error))),
|
||||
None => GPoll::arena_exhausted(),
|
||||
}
|
||||
}
|
||||
GPoll::Pending => GPoll::Pending,
|
||||
GPoll::Error(error) => GPoll::Error(error),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::context::EvalScope;
|
||||
use crate::SourceId;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
struct CountingNode(AtomicU32);
|
||||
|
||||
impl<Input> GNode<Input> for CountingNode {
|
||||
type Output = u32;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<u32> {
|
||||
GPoll::Final(self.0.fetch_add(1, Ordering::Relaxed) + 1)
|
||||
}
|
||||
}
|
||||
|
||||
struct ValueNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> GNode<Input> for ValueNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
|
||||
EvalScope::new(Some(0.5), None, None, generations, arena)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memo_capability_wraps_edges_type_blind() {
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let edge = EdgeHandle::new(Box::new(CountingNode(AtomicU32::new(0))) as Box<ErasedGNode<u32>>);
|
||||
let memoized = edge.memoized().unwrap().downcast::<u32>().unwrap();
|
||||
|
||||
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memo_invalidates_on_generation_bump() {
|
||||
let arena = Arena::new(1024);
|
||||
let source: SourceId = 7;
|
||||
let before = [(source, 1)];
|
||||
let after = [(source, 2)];
|
||||
let scope_before = scope_fixture(&before, &arena);
|
||||
let scope_after = scope_fixture(&after, &arena);
|
||||
|
||||
let edge = EdgeHandle::new(Box::new(CountingNode(AtomicU32::new(0))) as Box<ErasedGNode<u32>>);
|
||||
let memoized = edge.memoized().unwrap().downcast::<u32>().unwrap();
|
||||
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
|
||||
assert_eq!(memoized.eval(&ContextImpl::root(&scope_after)), GPoll::Final(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memoized_edges_stack_and_rewire() {
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let edge = EdgeHandle::new(Box::new(CountingNode(AtomicU32::new(0))) as Box<ErasedGNode<u32>>);
|
||||
let stacked = edge.memoized().unwrap().memoized().unwrap().downcast::<u32>().unwrap();
|
||||
|
||||
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
|
||||
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lend_capability_turns_an_owned_edge_into_a_lending_edge() {
|
||||
let arena = Arena::new(4096);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let edge = EdgeHandle::new(Box::new(ValueNode("lent out".to_string())) as Box<ErasedGNode<String>>);
|
||||
let lending = edge.lent().unwrap();
|
||||
assert_eq!(*lending.wire_type(), Type::Ref(Box::new(concrete!(String))));
|
||||
|
||||
let node = lending.downcast_lend::<String>().unwrap();
|
||||
let GPoll::Final(first) = node.eval(&ctx) else {
|
||||
panic!("lend must fill the frame table and lend");
|
||||
};
|
||||
let GPoll::Final(second) = node.eval(&ctx) else {
|
||||
panic!("second eval must lend the published value");
|
||||
};
|
||||
assert_eq!(first, "lent out");
|
||||
assert!(std::ptr::eq(first, second));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ref_edges_report_missing_capabilities() {
|
||||
let edge = EdgeHandle::new(Box::new(ValueNode(5u32)) as Box<ErasedGNode<u32>>);
|
||||
let lending = edge.lent().unwrap();
|
||||
|
||||
match lending.memoized() {
|
||||
Err(WireError::MissingCapability { ty }) => assert_eq!(ty, Type::Ref(Box::new(concrete!(u32)))),
|
||||
other => panic!("expected missing capability, got {:?}", other.map(|handle| handle.ty)),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrow_carrying_value_types_wire_through_the_general_constructor() {
|
||||
struct SplitBorrow<'c>(&'c str, usize);
|
||||
|
||||
struct SplitNode<Node0> {
|
||||
content: Node0,
|
||||
}
|
||||
|
||||
impl<'e, Input, Node0> GNode<Input> for SplitNode<Node0>
|
||||
where
|
||||
Input: Ctx,
|
||||
Node0: GNode<Input, Output = &'e String>,
|
||||
{
|
||||
type Output = SplitBorrow<'e>;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<SplitBorrow<'e>> {
|
||||
self.content.eval(input).map(|value| SplitBorrow(value, value.len()))
|
||||
}
|
||||
}
|
||||
|
||||
type ErasedSplitEdge = dyn for<'c> GNode<ContextImpl<'c>, Output = SplitBorrow<'c>>;
|
||||
|
||||
let arena = Arena::new(4096);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let lending = EdgeHandle::new(Box::new(ValueNode("held".to_string())) as Box<ErasedGNode<String>>).lent().unwrap();
|
||||
let upstream = lending.downcast_lend::<String>().unwrap();
|
||||
let node: Box<ErasedSplitEdge> = Box::new(SplitNode { content: upstream });
|
||||
let handle = EdgeHandle::new_erased(node, concrete!(SplitBorrow<'static>), WireCapabilities::default());
|
||||
assert_eq!(*handle.wire_type(), concrete!(SplitBorrow<'static>));
|
||||
|
||||
let wired = handle.downcast_erased::<ErasedSplitEdge>(concrete!(SplitBorrow<'static>)).unwrap();
|
||||
let GPoll::Final(split) = wired.eval(&ctx) else {
|
||||
panic!("borrow-carrying output must eval through the erased edge");
|
||||
};
|
||||
assert_eq!(split.0, "held");
|
||||
assert_eq!(split.1, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_ctx_repeat_pushes_index_levels_through_the_erased_edge() {
|
||||
use crate::context::{Derived, DeriveCtx, ExtractIndex};
|
||||
|
||||
struct RepeatNode<Node0> {
|
||||
content: Node0,
|
||||
}
|
||||
|
||||
impl<C, T, Node0> GNode<C> for RepeatNode<Node0>
|
||||
where
|
||||
C: Ctx + DeriveCtx,
|
||||
Node0: for<'x> GNode<Derived<'x, C>, Output = T>,
|
||||
{
|
||||
type Output = Vec<T>;
|
||||
|
||||
fn eval(&self, input: &C) -> GPoll<Vec<T>> {
|
||||
let spilled = input.index_head();
|
||||
let mut result = Vec::new();
|
||||
for index in 0..3 {
|
||||
let derived = input.promoted(&spilled, index);
|
||||
match self.content.eval(&derived) {
|
||||
GPoll::Final(value) => result.push(value),
|
||||
other => return other.map(|_| Vec::new()),
|
||||
}
|
||||
}
|
||||
GPoll::Final(result)
|
||||
}
|
||||
}
|
||||
|
||||
struct LevelsNode;
|
||||
|
||||
impl<Input: ExtractIndex> GNode<Input> for LevelsNode {
|
||||
type Output = Vec<usize>;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<Vec<usize>> {
|
||||
GPoll::Final(input.try_index().map(|levels| levels.collect()).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let nested = RepeatNode {
|
||||
content: RepeatNode { content: LevelsNode },
|
||||
};
|
||||
let erased: Box<ErasedGNode<Vec<Vec<Vec<usize>>>>> = Box::new(nested);
|
||||
|
||||
let GPoll::Final(outer) = erased.eval(&ctx) else {
|
||||
panic!("nested repeat must evaluate");
|
||||
};
|
||||
assert_eq!(outer.len(), 3);
|
||||
assert_eq!(outer[2][1], vec![1, 2, 0]);
|
||||
assert_eq!(outer[0][0], vec![0, 0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_ctx_footprint_replace_reaches_the_content() {
|
||||
use crate::context::{Derived, DeriveCtx, ExtractFootprint};
|
||||
use crate::transform::Footprint;
|
||||
|
||||
struct ShiftFootprintNode<Node0> {
|
||||
content: Node0,
|
||||
}
|
||||
|
||||
impl<C, T, Node0> GNode<C> for ShiftFootprintNode<Node0>
|
||||
where
|
||||
C: Ctx + DeriveCtx + ExtractFootprint,
|
||||
Node0: for<'x> GNode<Derived<'x, C>, Output = T>,
|
||||
{
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, input: &C) -> GPoll<T> {
|
||||
let mut footprint = input.try_footprint().copied().unwrap_or(Footprint::DEFAULT);
|
||||
footprint.resolution.x += 7;
|
||||
let derived = input.with_footprint(&footprint);
|
||||
self.content.eval(&derived)
|
||||
}
|
||||
}
|
||||
|
||||
struct ResolutionNode;
|
||||
|
||||
impl<Input: ExtractFootprint> GNode<Input> for ResolutionNode {
|
||||
type Output = u32;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<u32> {
|
||||
GPoll::Final(input.try_footprint().map(|footprint| footprint.resolution.x).unwrap_or(0))
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(1024);
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph: Box<ErasedGNode<u32>> = Box::new(ShiftFootprintNode {
|
||||
content: ShiftFootprintNode { content: ResolutionNode },
|
||||
});
|
||||
assert_eq!(graph.eval(&ctx), GPoll::Final(Footprint::DEFAULT.resolution.x + 14));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_and_wire_checks_arity_and_types() {
|
||||
fn wire_strlen(args: Vec<EdgeHandle>) -> Result<EdgeHandle, WireError> {
|
||||
let mut args = args.into_iter();
|
||||
let value = args.next().ok_or(WireError::Arity { expected: 1, got: 0 })?.downcast::<String>()?;
|
||||
drop(value);
|
||||
Ok(EdgeHandle::new(Box::new(ValueNode(0u32)) as Box<ErasedGNode<u32>>))
|
||||
}
|
||||
let entry = RegistryEntry {
|
||||
io: NodeIoRecord {
|
||||
inputs: vec![concrete!(String)],
|
||||
output: concrete!(u32),
|
||||
},
|
||||
wire: wire_strlen,
|
||||
};
|
||||
|
||||
let owned = EdgeHandle::new(Box::new(ValueNode("typed".to_string())) as Box<ErasedGNode<String>>);
|
||||
assert!(resolve_and_wire(&entry, vec![owned]).is_ok());
|
||||
|
||||
assert_eq!(resolve_and_wire(&entry, vec![]).unwrap_err(), WireError::Arity { expected: 1, got: 0 });
|
||||
|
||||
let mistyped = EdgeHandle::new(Box::new(ValueNode(1.0f64)) as Box<ErasedGNode<f64>>);
|
||||
assert_eq!(
|
||||
resolve_and_wire(&entry, vec![mistyped]).unwrap_err(),
|
||||
WireError::Type {
|
||||
expected: concrete!(String),
|
||||
found: concrete!(f64),
|
||||
}
|
||||
);
|
||||
|
||||
let lent = EdgeHandle::new(Box::new(ValueNode("typed".to_string())) as Box<ErasedGNode<String>>).lent().unwrap();
|
||||
assert_eq!(
|
||||
resolve_and_wire(&entry, vec![lent]).unwrap_err(),
|
||||
WireError::Type {
|
||||
expected: concrete!(String),
|
||||
found: Type::Ref(Box::new(concrete!(String))),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -236,142 +236,3 @@ impl_tuple!(A, B, C);
|
||||
impl_tuple!(A, B, C, D);
|
||||
impl_tuple!(A, B, C, D, E);
|
||||
impl_tuple!(A, B, C, D, E, F);
|
||||
|
||||
/// rustc-hash's polynomial hash with the state pinned to u64, so keys match across native and wasm targets.
|
||||
/// The state starts at a nonzero seed: zero-initialized fx absorbs leading zero words, which produced
|
||||
/// a real wrong-value memo hit in the prototype.
|
||||
#[derive(Clone)]
|
||||
pub struct FxHasher64 {
|
||||
hash: u64,
|
||||
}
|
||||
|
||||
const K: u64 = 0xf1357aea2e62a9c5;
|
||||
const SEED: u64 = 0x517cc1b727220a95;
|
||||
const SEED1: u64 = 0x243f6a8885a308d3;
|
||||
const SEED2: u64 = 0x13198a2e03707344;
|
||||
const PREVENT_TRIVIAL_ZERO_COLLAPSE: u64 = 0xa4093822299f31d0;
|
||||
|
||||
impl Default for FxHasher64 {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl FxHasher64 {
|
||||
pub const fn new() -> Self {
|
||||
Self { hash: SEED }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn add_to_hash(&mut self, i: u64) {
|
||||
self.hash = self.hash.wrapping_add(i).wrapping_mul(K);
|
||||
}
|
||||
}
|
||||
|
||||
impl core::hash::Hasher for FxHasher64 {
|
||||
#[inline]
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
self.add_to_hash(hash_bytes(bytes));
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u8(&mut self, i: u8) {
|
||||
self.add_to_hash(i as u64);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u16(&mut self, i: u16) {
|
||||
self.add_to_hash(i as u64);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u32(&mut self, i: u32) {
|
||||
self.add_to_hash(i as u64);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u64(&mut self, i: u64) {
|
||||
self.add_to_hash(i);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u128(&mut self, i: u128) {
|
||||
self.add_to_hash(i as u64);
|
||||
self.add_to_hash((i >> 64) as u64);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_usize(&mut self, i: usize) {
|
||||
self.add_to_hash(i as u64);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn finish(&self) -> u64 {
|
||||
self.hash.rotate_left(26)
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn multiply_mix(x: u64, y: u64) -> u64 {
|
||||
let full = (x as u128) * (y as u128);
|
||||
(full as u64) ^ ((full >> 64) as u64)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn hash_bytes(bytes: &[u8]) -> u64 {
|
||||
let len = bytes.len();
|
||||
let mut s0 = SEED1;
|
||||
let mut s1 = SEED2;
|
||||
|
||||
if len <= 16 {
|
||||
if len >= 8 {
|
||||
s0 ^= u64::from_le_bytes(bytes[0..8].try_into().unwrap());
|
||||
s1 ^= u64::from_le_bytes(bytes[len - 8..].try_into().unwrap());
|
||||
} else if len >= 4 {
|
||||
s0 ^= u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as u64;
|
||||
s1 ^= u32::from_le_bytes(bytes[len - 4..].try_into().unwrap()) as u64;
|
||||
} else if len > 0 {
|
||||
let lo = bytes[0];
|
||||
let mid = bytes[len / 2];
|
||||
let hi = bytes[len - 1];
|
||||
s0 ^= lo as u64;
|
||||
s1 ^= ((hi as u64) << 8) | mid as u64;
|
||||
}
|
||||
} else {
|
||||
let mut off = 0;
|
||||
while off < len - 16 {
|
||||
let x = u64::from_le_bytes(bytes[off..off + 8].try_into().unwrap());
|
||||
let y = u64::from_le_bytes(bytes[off + 8..off + 16].try_into().unwrap());
|
||||
let t = multiply_mix(s0 ^ x, PREVENT_TRIVIAL_ZERO_COLLAPSE ^ y);
|
||||
s0 = s1;
|
||||
s1 = t;
|
||||
off += 16;
|
||||
}
|
||||
|
||||
let suffix = &bytes[len - 16..];
|
||||
s0 ^= u64::from_le_bytes(suffix[0..8].try_into().unwrap());
|
||||
s1 ^= u64::from_le_bytes(suffix[8..16].try_into().unwrap());
|
||||
}
|
||||
|
||||
multiply_mix(s0, s1) ^ (len as u64)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::FxHasher64;
|
||||
use core::hash::Hasher;
|
||||
|
||||
#[test]
|
||||
fn leading_zero_words_are_not_absorbed() {
|
||||
let hash_words = |words: &[u64]| {
|
||||
let mut hasher = FxHasher64::new();
|
||||
for &word in words {
|
||||
hasher.write_u64(word);
|
||||
}
|
||||
hasher.finish()
|
||||
};
|
||||
assert_ne!(hash_words(&[]), hash_words(&[0]), "a zero word must change the hash of the empty input");
|
||||
assert_ne!(hash_words(&[0]), hash_words(&[0, 0]), "zero words must accumulate distinct states");
|
||||
assert_ne!(hash_words(&[0, 7]), hash_words(&[7]), "a leading zero word must not be absorbed");
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ use crate::texture_cache::TextureCache;
|
||||
use anyhow::Result;
|
||||
use core_types::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use futures::lock::Mutex;
|
||||
use std::sync::Mutex;
|
||||
use glam::UVec2;
|
||||
use graphene_application_io::{ApplicationIo, EditorApi};
|
||||
use raster_types::Texture;
|
||||
@@ -19,7 +19,6 @@ 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;
|
||||
@@ -68,8 +67,8 @@ impl<'a, T: ApplicationIo<Executor = WgpuExecutor>> From<&'a EditorApi<T>> for &
|
||||
}
|
||||
|
||||
impl WgpuExecutor {
|
||||
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;
|
||||
pub fn render_vello_scene(&self, scene: &Scene, size: UVec2, context: &RenderContext, background: Option<Color>) -> Result<Texture> {
|
||||
let texture = self.request_texture(size);
|
||||
|
||||
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
@@ -82,7 +81,7 @@ impl WgpuExecutor {
|
||||
};
|
||||
|
||||
{
|
||||
let mut renderer = self.inner.vello_renderer.lock().await;
|
||||
let mut renderer = self.inner.vello_renderer.lock().unwrap();
|
||||
for (image_brush, texture) in context.resource_overrides.iter() {
|
||||
let texture_view = wgpu::TexelCopyTextureInfoBase {
|
||||
texture: (**texture).clone(),
|
||||
@@ -109,8 +108,8 @@ impl WgpuExecutor {
|
||||
pipeline.init::<P>(self);
|
||||
}
|
||||
|
||||
pub async fn request_texture(&self, size: UVec2) -> Texture {
|
||||
self.inner.texture_cache.lock().await.request_texture(&self.context().device, size)
|
||||
pub fn request_texture(&self, size: UVec2) -> Texture {
|
||||
self.inner.texture_cache.lock().unwrap().request_texture(&self.context().device, size)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,42 +1,16 @@
|
||||
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<'_>) -> 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))
|
||||
}
|
||||
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out;
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, DynAny)]
|
||||
@@ -51,13 +25,13 @@ impl PipelineCache {
|
||||
self.pipeline.get_or_init(|| Box::new(P::create(executor)));
|
||||
}
|
||||
|
||||
pub async fn run<P: Pipeline>(&self, args: &P::Args<'_>) -> P::Out {
|
||||
pub fn run<P: Pipeline>(&self, args: &P::Args<'_>) -> P::Out {
|
||||
let executor = self.executor.get().expect("PipelineCache not initialized");
|
||||
let entry = self.pipeline.get().expect("PipelineCache not initialized");
|
||||
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).await
|
||||
pipeline.run(executor, args)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ 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 std::sync::Mutex;
|
||||
use raster_types::{GPU, Raster};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
@@ -33,8 +33,8 @@ impl PerPixelAdjustShaderRuntime {
|
||||
}
|
||||
|
||||
impl ShaderRuntime {
|
||||
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;
|
||||
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();
|
||||
let pipeline = cache
|
||||
.entry(shaders.fragment_shader_name.to_owned())
|
||||
.or_insert_with(|| PerPixelAdjustGraphicsPipeline::new(&self.context, shaders));
|
||||
|
||||
@@ -38,120 +38,17 @@ fn upload_to_texture(device: &wgpu::Device, queue: &wgpu::Queue, image: &Raster<
|
||||
)
|
||||
}
|
||||
|
||||
/// Converts a Raster<GPU> texture to Raster<CPU> by downloading the underlying texture data.
|
||||
///
|
||||
/// Assumptions:
|
||||
/// - 2D texture, mip level 0
|
||||
/// - 4 bytes-per-pixel RGBA8
|
||||
/// - Texture has COPY_SRC usage
|
||||
struct RasterGpuToRasterCpuConverter {
|
||||
buffer: wgpu::Buffer,
|
||||
width: u32,
|
||||
height: u32,
|
||||
unpadded_bytes_per_row: u32,
|
||||
padded_bytes_per_row: u32,
|
||||
_source: raster_types::Texture,
|
||||
}
|
||||
impl RasterGpuToRasterCpuConverter {
|
||||
fn new(device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
|
||||
let texture = data_gpu.data();
|
||||
let width = texture.width();
|
||||
let height = texture.height();
|
||||
let bytes_per_pixel = 4; // RGBA8
|
||||
let unpadded_bytes_per_row = width * bytes_per_pixel;
|
||||
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
||||
let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
|
||||
let buffer_size = padded_bytes_per_row as u64 * height as u64;
|
||||
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("texture_download_buffer"),
|
||||
size: buffer_size,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(padded_bytes_per_row),
|
||||
rows_per_image: Some(height),
|
||||
},
|
||||
},
|
||||
Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
|
||||
Self {
|
||||
buffer,
|
||||
width,
|
||||
height,
|
||||
unpadded_bytes_per_row,
|
||||
padded_bytes_per_row,
|
||||
// Keep source texture alive
|
||||
_source: data_gpu.texture.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn convert(self, device: &wgpu::Device) -> Result<Raster<CPU>, wgpu::BufferAsyncError> {
|
||||
let buffer_slice = self.buffer.slice(..);
|
||||
let (sender, receiver) = futures::channel::oneshot::channel();
|
||||
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
||||
let _ = sender.send(result);
|
||||
});
|
||||
|
||||
let _ = device.poll(wgpu::wgt::PollType::wait_indefinitely());
|
||||
|
||||
receiver.await.expect("Failed to receive map result")?;
|
||||
|
||||
let view = buffer_slice.get_mapped_range();
|
||||
|
||||
let row_stride = self.padded_bytes_per_row as usize;
|
||||
let row_bytes = self.unpadded_bytes_per_row as usize;
|
||||
let mut cpu_data: Vec<Color> = Vec::with_capacity((self.width * self.height) as usize);
|
||||
for row in 0..self.height as usize {
|
||||
let start = row * row_stride;
|
||||
let row_slice = &view[start..start + row_bytes];
|
||||
for px in row_slice.chunks_exact(4) {
|
||||
// `Image<Color>` pixels are stored linear-light with associated (premultiplied) alpha
|
||||
let srgba = SRGBA8::new(px[0], px[1], px[2], px[3]);
|
||||
cpu_data.push(Color::from(srgba).apply_opacity(px[3] as f32 / 255.));
|
||||
}
|
||||
}
|
||||
|
||||
drop(view);
|
||||
self.buffer.unmap();
|
||||
let cpu_image = Image {
|
||||
data: cpu_data,
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
base64_string: None,
|
||||
};
|
||||
|
||||
Ok(Raster::new_cpu(cpu_image))
|
||||
}
|
||||
}
|
||||
|
||||
/// Passthrough conversion for GPU `List`s - no conversion needed
|
||||
impl<'i> Convert<List<Raster<GPU>>, &'i WgpuExecutor> for List<Raster<GPU>> {
|
||||
async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<GPU>> {
|
||||
fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<GPU>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>> {
|
||||
fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> List<Raster<GPU>> {
|
||||
let device = &executor.context().device;
|
||||
let queue = executor.context().queue.lock();
|
||||
let list = self
|
||||
@@ -171,7 +68,7 @@ impl<'i> Convert<List<Raster<GPU>>, &'i WgpuExecutor> for List<Raster<CPU>> {
|
||||
|
||||
/// Converts single CPU raster to GPU by uploading to texture
|
||||
impl<'i> Convert<Raster<GPU>, &'i WgpuExecutor> for Raster<CPU> {
|
||||
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<GPU> {
|
||||
fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<GPU> {
|
||||
let device = &executor.context().device;
|
||||
let queue = executor.context().queue.lock();
|
||||
let texture = upload_to_texture(device, &queue, &self);
|
||||
@@ -183,79 +80,19 @@ impl<'i> Convert<Raster<GPU>, &'i WgpuExecutor> for Raster<CPU> {
|
||||
|
||||
/// Passthrough conversion for CPU `List`s - no conversion needed
|
||||
impl<'i> Convert<List<Raster<CPU>>, &'i WgpuExecutor> for List<Raster<CPU>> {
|
||||
async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<CPU>> {
|
||||
fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List<Raster<CPU>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a `List<Raster<GPU>>` to `List<Raster<CPU>>` by downloading texture data in one go then asynchronously maps all buffers and processes the results.
|
||||
impl<'i> Convert<List<Raster<CPU>>, &'i WgpuExecutor> for List<Raster<GPU>> {
|
||||
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> List<Raster<CPU>> {
|
||||
let device = &executor.context().device;
|
||||
let queue = &executor.context().queue;
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("batch_texture_download_encoder"),
|
||||
});
|
||||
|
||||
let mut converters = Vec::new();
|
||||
let mut rows_meta = Vec::new();
|
||||
|
||||
for row in self {
|
||||
let (element, attributes) = row.into_parts();
|
||||
converters.push(RasterGpuToRasterCpuConverter::new(device, &mut encoder, element));
|
||||
rows_meta.push(Item::from_parts((), attributes));
|
||||
}
|
||||
|
||||
queue.submit([encoder.finish()]);
|
||||
|
||||
let mut map_futures = Vec::new();
|
||||
for converter in converters {
|
||||
map_futures.push(converter.convert(device));
|
||||
}
|
||||
|
||||
let map_results = futures::future::try_join_all(map_futures)
|
||||
.await
|
||||
.map_err(|_| "Failed to receive map result")
|
||||
.expect("Buffer mapping communication failed");
|
||||
|
||||
map_results
|
||||
.into_iter()
|
||||
.zip(rows_meta)
|
||||
.map(|(element, row)| {
|
||||
let (_, attributes) = row.into_parts();
|
||||
Item::from_parts(element, attributes)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts single GPU raster to CPU by downloading texture data
|
||||
impl<'i> Convert<Raster<CPU>, &'i WgpuExecutor> for Raster<GPU> {
|
||||
async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster<CPU> {
|
||||
let device = &executor.context().device;
|
||||
let queue = &executor.context().queue;
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("single_texture_download_encoder"),
|
||||
});
|
||||
|
||||
let converter = RasterGpuToRasterCpuConverter::new(device, &mut encoder, self);
|
||||
|
||||
queue.submit([encoder.finish()]);
|
||||
|
||||
converter.convert(device).await.expect("Failed to download texture data")
|
||||
}
|
||||
}
|
||||
|
||||
/// Uploads an raster texture from the CPU to the GPU. This is now deprecated and the Convert node should be used in the future.
|
||||
///
|
||||
/// 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 async fn upload_texture<'a: 'n, T: Convert<List<Raster<GPU>>, &'a WgpuExecutor>>(
|
||||
pub fn upload_texture<'a, T: Convert<List<Raster<GPU>>, &'a WgpuExecutor>>(
|
||||
_: impl Ctx,
|
||||
#[implementations(List<Raster<CPU>>, List<Raster<GPU>>)] input: T,
|
||||
executor: &'a WgpuExecutor,
|
||||
) -> List<Raster<GPU>> {
|
||||
input.convert(Footprint::DEFAULT, executor).await
|
||||
input.convert(Footprint::DEFAULT, executor)
|
||||
}
|
||||
@@ -1,28 +1,23 @@
|
||||
use crate::parsing::*;
|
||||
use convert_case::{Case, Casing};
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{ToTokens, format_ident, quote, quote_spanned};
|
||||
use quote::{ToTokens, format_ident, quote};
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::token::Comma;
|
||||
use syn::{Error, Ident, PatIdent, Token, WhereClause, WherePredicate, parse_quote};
|
||||
use syn::{Ident, PatIdent};
|
||||
static NODE_ID: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn) -> syn::Result<TokenStream2> {
|
||||
let ParsedNodeFn {
|
||||
vis,
|
||||
attributes,
|
||||
fn_name,
|
||||
struct_name,
|
||||
mod_name,
|
||||
fn_generics,
|
||||
where_clause,
|
||||
input,
|
||||
output_type,
|
||||
is_async,
|
||||
fields,
|
||||
body,
|
||||
description,
|
||||
..
|
||||
} = parsed;
|
||||
@@ -80,13 +75,10 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
// Combined struct generic parameters with bounds for struct definition
|
||||
// struct MemoizeNode<T: Clone, Node0>
|
||||
let struct_generic_params: Vec<TokenStream2> = data_field_generics.iter().map(|gp| quote!(#gp)).chain(node_generics.iter().map(|id| quote!(#id))).collect();
|
||||
let input_ident = &input.pat_ident;
|
||||
|
||||
let context_features = &input.context_features;
|
||||
|
||||
// Regular field idents and names (for function parameters)
|
||||
let field_idents: Vec<_> = regular_fields.iter().map(|f| &f.pat_ident).collect();
|
||||
let field_names: Vec<_> = field_idents.iter().map(|pat_ident| &pat_ident.ident).collect();
|
||||
let regular_field_names: Vec<_> = regular_fields.iter().map(|f| &f.pat_ident.ident).collect();
|
||||
let data_field_names: Vec<_> = data_fields.iter().map(|f| &f.pat_ident.ident).collect();
|
||||
|
||||
@@ -119,34 +111,12 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
quote! { pub(super) #name: #r#gen }
|
||||
});
|
||||
|
||||
let struct_fields = data_field_defs.chain(regular_field_defs);
|
||||
|
||||
let mut future_idents = Vec::new();
|
||||
|
||||
// Data fields get passed as references to the underlying function
|
||||
let data_field_idents: Vec<_> = data_fields.iter().map(|f| &f.pat_ident).collect();
|
||||
let data_field_types: Vec<_> = data_fields
|
||||
.iter()
|
||||
.map(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => {
|
||||
let ty = ty.clone();
|
||||
quote!(&#ty)
|
||||
}
|
||||
_ => unreachable!("Data fields must be Regular types, not Node types"),
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Regular fields have types passed to the function
|
||||
let field_types: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, input_type, .. }) => match parsed.is_async {
|
||||
true => parse_quote!(&'n impl #core_types::Node<'n, #input_type, Output = impl core::future::Future<Output=#output_type>>),
|
||||
false => parse_quote!(&'n impl #core_types::Node<'n, #input_type, Output = #output_type>),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
let async_source = *is_async || crate::gcodegen::is_source_kernel(output_type);
|
||||
let slot_value_type = crate::gcodegen::slot_value_type(output_type);
|
||||
let slot_field = async_source
|
||||
.then(|| quote! { pub(super) slot: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<u64, Option<gcore::gpoll::GPoll<#slot_value_type>>>>> })
|
||||
.into_iter();
|
||||
let struct_fields = data_field_defs.chain(regular_field_defs).chain(slot_field);
|
||||
|
||||
// Only regular fields have UI metadata (data fields are internal state)
|
||||
let widget_override: Vec<_> = regular_fields
|
||||
@@ -233,39 +203,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
.collect();
|
||||
|
||||
// Only eval regular fields (data fields are accessed directly as self.field_name)
|
||||
let eval_args = regular_fields.iter().map(|field| {
|
||||
let name = &field.pat_ident.ident;
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular { .. } => {
|
||||
quote! { let #name = self.#name.eval(__input.clone()).await; }
|
||||
}
|
||||
ParsedFieldType::Node { .. } => {
|
||||
quote! { let #name = &self.#name; }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Only regular fields can have min/max constraints
|
||||
let min_max_args = regular_fields.iter().map(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { number_hard_min, number_hard_max, .. }) => {
|
||||
let name = &field.pat_ident.ident;
|
||||
let mut tokens = quote!();
|
||||
if let Some(min) = number_hard_min {
|
||||
tokens.extend(quote_spanned! {min.span()=>
|
||||
let #name = #core_types::misc::Clampable::clamp_hard_min(#name, #min);
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(max) = number_hard_max {
|
||||
tokens.extend(quote_spanned! {max.span()=>
|
||||
let #name = #core_types::misc::Clampable::clamp_hard_max(#name, #max);
|
||||
});
|
||||
}
|
||||
tokens
|
||||
}
|
||||
ParsedFieldType::Node { .. } => quote!(),
|
||||
});
|
||||
|
||||
let all_implementation_types = fields.iter().flat_map(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { implementations, .. }) => implementations.iter().cloned().collect::<Vec<_>>(),
|
||||
ParsedFieldType::Node(NodeParsedField { implementations, .. }) => implementations
|
||||
@@ -275,61 +212,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
});
|
||||
let all_implementation_types = all_implementation_types.chain(input.implementations.iter().cloned());
|
||||
|
||||
let input_type = &parsed.input.ty;
|
||||
let mut clauses = Vec::new();
|
||||
let mut clampable_clauses = Vec::new();
|
||||
|
||||
for (field, name) in regular_fields.iter().zip(node_generics.iter()) {
|
||||
clauses.push(match (&field.ty, *is_async) {
|
||||
(
|
||||
ParsedFieldType::Regular(RegularParsedField {
|
||||
ty, number_hard_min, number_hard_max, ..
|
||||
}),
|
||||
_,
|
||||
) => {
|
||||
let all_lifetime_ty = substitute_lifetimes(ty.clone(), "all");
|
||||
let id = future_idents.len();
|
||||
let fut_ident = format_ident!("F{}", id);
|
||||
future_idents.push(fut_ident.clone());
|
||||
|
||||
// Add Clampable bound if this field uses hard_min or hard_max
|
||||
if number_hard_min.is_some() || number_hard_max.is_some() {
|
||||
// The bound applies to the Output type of the future, which is #ty
|
||||
clampable_clauses.push(quote!(#ty: #core_types::misc::Clampable));
|
||||
}
|
||||
|
||||
quote!(
|
||||
#fut_ident: core::future::Future<Output = #ty> + #core_types::WasmNotSend + 'n,
|
||||
for<'all> #all_lifetime_ty: #core_types::WasmNotSend,
|
||||
#name: #core_types::Node<'n, #input_type, Output = #fut_ident> + #core_types::WasmNotSync
|
||||
)
|
||||
}
|
||||
(ParsedFieldType::Node(NodeParsedField { input_type, output_type, .. }), true) => {
|
||||
let id = future_idents.len();
|
||||
let fut_ident = format_ident!("F{}", id);
|
||||
future_idents.push(fut_ident.clone());
|
||||
|
||||
quote!(
|
||||
#fut_ident: core::future::Future<Output = #output_type> + #core_types::WasmNotSend + 'n,
|
||||
#name: #core_types::Node<'n, #input_type, Output = #fut_ident > + #core_types::WasmNotSync
|
||||
)
|
||||
}
|
||||
(ParsedFieldType::Node { .. }, false) => unreachable!("Found node which takes an impl Node<> input but is not async"),
|
||||
});
|
||||
}
|
||||
let where_clause = where_clause.clone().unwrap_or(WhereClause {
|
||||
where_token: Token),
|
||||
predicates: Default::default(),
|
||||
});
|
||||
|
||||
let mut struct_where_clause = where_clause.clone();
|
||||
let extra_where: Punctuated<WherePredicate, Comma> = parse_quote!(
|
||||
#(#clauses,)*
|
||||
#(#clampable_clauses,)*
|
||||
#output_type: 'n,
|
||||
);
|
||||
struct_where_clause.predicates.extend(extra_where);
|
||||
|
||||
// Only regular fields are parameters to new()
|
||||
let new_args = node_generics.iter().zip(regular_field_names.iter()).map(|(r#gen, name)| {
|
||||
quote! { #name: #r#gen }
|
||||
@@ -342,46 +224,16 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let regular_inits = regular_field_names.iter().map(|name| {
|
||||
quote! { #name }
|
||||
});
|
||||
let all_field_inits = data_inits.chain(regular_inits);
|
||||
|
||||
let async_keyword = is_async.then(|| quote!(async));
|
||||
let await_keyword = is_async.then(|| quote!(.await));
|
||||
let slot_init = async_source.then(|| quote! { slot: Default::default() }).into_iter();
|
||||
let all_field_inits = data_inits.chain(regular_inits).chain(slot_init);
|
||||
|
||||
// Data fields may not implement Copy, PartialEq, etc., so only derive Debug and Clone
|
||||
let struct_derives = if data_fields.is_empty() {
|
||||
let struct_derives = if data_fields.is_empty() && !async_source {
|
||||
quote!(#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)])
|
||||
} else {
|
||||
quote!(#[derive(Debug, Clone)])
|
||||
};
|
||||
|
||||
// Generate serialize method if serialize attribute is specified
|
||||
let serialize_impl = if let Some(serialize_fn) = &parsed.attributes.serialize {
|
||||
let data_field_refs = data_field_names.iter().map(|name| quote!(&self.#name));
|
||||
quote! {
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
#serialize_fn(#(#data_field_refs),*)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
quote!()
|
||||
};
|
||||
|
||||
let eval_impl = quote! {
|
||||
type Output = #core_types::registry::DynFuture<'n, #output_type>;
|
||||
#[inline]
|
||||
fn eval(&'n self, __input: #input_type) -> Self::Output {
|
||||
Box::pin(async move {
|
||||
use #core_types::misc::Clampable;
|
||||
|
||||
#(#eval_args)*
|
||||
#(#min_max_args)*
|
||||
self::#fn_name(__input #(, &self.#data_field_names)* #(, #regular_field_names)*) #await_keyword
|
||||
})
|
||||
}
|
||||
|
||||
#serialize_impl
|
||||
};
|
||||
|
||||
let identifier = format_ident!("{}_proto_ident", fn_name);
|
||||
let identifier_path = match parsed.attributes.path.as_ref() {
|
||||
Some(path) => {
|
||||
@@ -391,8 +243,18 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
None => quote!(std::module_path!()),
|
||||
};
|
||||
|
||||
let register_node_impl = generate_register_node_impl(parsed, &field_names, &struct_name, &identifier)?;
|
||||
let registry_name = format_ident!("__node_registry_{}_{}", NODE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst), struct_name);
|
||||
let register_node_impl = quote! {
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn #registry_name() {
|
||||
register_metadata();
|
||||
}
|
||||
};
|
||||
let import_name = format_ident!("_IMPORT_STUB_{}", mod_name.to_string().to_case(Case::UpperSnake));
|
||||
let gnode = crate::gcodegen::generate_gnode_code(crate_ident, parsed)?;
|
||||
let gnode_in_mod = gnode.in_mod;
|
||||
let gnode_top_level = gnode.top_level;
|
||||
|
||||
let properties = &attributes.properties_string.as_ref().map(|value| quote!(Some(#value))).unwrap_or(quote!(None));
|
||||
let memoize_flag = attributes.memoize;
|
||||
@@ -428,17 +290,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
|
||||
Ok(quote! {
|
||||
#(#description_doc_attrs)*
|
||||
#[inline]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#vis #async_keyword fn #fn_name <'n, #(#fn_generics,)*> (#input_ident: #input_type #(, #data_field_idents: #data_field_types)* #(, #field_idents: #field_types)*) -> #output_type #where_clause #body
|
||||
|
||||
#cfg
|
||||
#[automatically_derived]
|
||||
impl<'n, #(#fn_generics,)* #(#node_generics,)* #(#future_idents,)*> #core_types::Node<'n, #input_type> for #mod_name::#struct_name<#(#struct_type_params,)*>
|
||||
#struct_where_clause
|
||||
{
|
||||
#eval_impl
|
||||
}
|
||||
#gnode_top_level
|
||||
|
||||
#cfg
|
||||
const fn #identifier() -> #core_types::ProtoNodeIdentifier {
|
||||
@@ -458,10 +310,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
mod #mod_name {
|
||||
use super::*;
|
||||
use #core_types as gcore;
|
||||
use gcore::{Node, NodeIOTypes, concrete, fn_type, fn_type_fut, future, ProtoNodeIdentifier, WasmNotSync, NodeIO, ContextFeature};
|
||||
use gcore::value::ClonedNode;
|
||||
use gcore::ops::TypeNode;
|
||||
use gcore::registry::{NodeMetadata, FieldMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, DynFuture, TypeErasedBox, PanicNode, RegistryValueSource, RegistryWidgetOverride};
|
||||
use gcore::{ContextFeature, concrete};
|
||||
use gcore::registry::{NodeMetadata, FieldMetadata, NODE_METADATA, RegistryValueSource, RegistryWidgetOverride};
|
||||
use gcore::ctor::ctor;
|
||||
|
||||
// Use the types specified in the implementation
|
||||
@@ -484,6 +334,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
}
|
||||
|
||||
#gnode_in_mod
|
||||
|
||||
#register_node_impl
|
||||
|
||||
#[cfg_attr(not(target_family = "wasm"), ctor)]
|
||||
@@ -619,161 +471,10 @@ fn generate_phantom_data<'a>(fn_generics: impl Iterator<Item = &'a crate::Generi
|
||||
(fn_generic_params, phantom_data_declerations)
|
||||
}
|
||||
|
||||
fn generate_register_node_impl(parsed: &ParsedNodeFn, field_names: &[&Ident], struct_name: &Ident, identifier: &Ident) -> Result<TokenStream2, Error> {
|
||||
// On native, `register_node` and `register_metadata` run automatically via `#[ctor]`.
|
||||
// On Wasm, `ctor` isn't available, so this `extern "C"` fn is invoked from JS to register the same way.
|
||||
// `skip_impl` nodes don't generate a `register_node`, so the shim calls only `register_metadata` for them.
|
||||
let registry_name = format_ident!("__node_registry_{}_{}", NODE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst), struct_name);
|
||||
let register_node_call = if parsed.attributes.skip_impl { quote!() } else { quote!(register_node();) };
|
||||
let wasm_shim = quote! {
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn #registry_name() {
|
||||
#register_node_call
|
||||
register_metadata();
|
||||
}
|
||||
};
|
||||
|
||||
if parsed.attributes.skip_impl {
|
||||
return Ok(wasm_shim);
|
||||
}
|
||||
|
||||
let mut constructors = Vec::new();
|
||||
let unit = parse_quote!(gcore::Context);
|
||||
|
||||
let regular_fields: Vec<_> = parsed.fields.iter().filter(|f| !f.is_data_field).collect();
|
||||
|
||||
let parameter_types: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { implementations, ty, .. }) => {
|
||||
if !implementations.is_empty() {
|
||||
implementations.iter().map(|ty| (&unit, ty)).collect()
|
||||
} else {
|
||||
vec![(&unit, ty)]
|
||||
}
|
||||
}
|
||||
ParsedFieldType::Node(NodeParsedField {
|
||||
implementations,
|
||||
input_type,
|
||||
output_type,
|
||||
..
|
||||
}) => {
|
||||
if !implementations.is_empty() {
|
||||
implementations.iter().map(|impl_| (&impl_.input, &impl_.output)).collect()
|
||||
} else {
|
||||
vec![(input_type, output_type)]
|
||||
}
|
||||
}
|
||||
}
|
||||
.into_iter()
|
||||
.map(|(input, out)| (substitute_lifetimes(input.clone(), "_"), substitute_lifetimes(out.clone(), "_")))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
|
||||
let max_implementations = parameter_types.iter().map(|x| x.len()).chain([parsed.input.implementations.len().max(1)]).max();
|
||||
|
||||
for i in 0..max_implementations.unwrap_or(0) {
|
||||
let mut temp_constructors = Vec::new();
|
||||
let mut temp_node_io = Vec::new();
|
||||
let mut panic_node_types = Vec::new();
|
||||
|
||||
for (j, types) in parameter_types.iter().enumerate() {
|
||||
let field_name = field_names[j];
|
||||
let (input_type, output_type) = &types[i.min(types.len() - 1)];
|
||||
|
||||
let node = matches!(regular_fields[j].ty, ParsedFieldType::Node { .. });
|
||||
|
||||
let downcast_node = quote!(
|
||||
let #field_name: DowncastBothNode<#input_type, #output_type> = DowncastBothNode::new(args[#j].clone());
|
||||
);
|
||||
if node && !parsed.is_async {
|
||||
return Err(Error::new_spanned(&parsed.fn_name, "Node needs to be async if you want to use lambda parameters"));
|
||||
}
|
||||
temp_constructors.push(downcast_node);
|
||||
temp_node_io.push(quote!(fn_type_fut!(#input_type, #output_type, alias: #output_type)));
|
||||
panic_node_types.push(quote!(#input_type, DynFuture<'static, #output_type>));
|
||||
}
|
||||
let input_type = match parsed.input.implementations.is_empty() {
|
||||
true => parsed.input.ty.clone(),
|
||||
false => parsed.input.implementations[i.min(parsed.input.implementations.len() - 1)].clone(),
|
||||
};
|
||||
constructors.push(quote!(
|
||||
(
|
||||
|args| {
|
||||
Box::pin(async move {
|
||||
#(#temp_constructors;)*
|
||||
let node = #struct_name::new(#(#field_names,)*);
|
||||
// try polling futures
|
||||
let any: DynAnyNode<#input_type, _, _> = DynAnyNode::new(node);
|
||||
Box::new(any) as TypeErasedBox<'_>
|
||||
})
|
||||
}, {
|
||||
let node = #struct_name::new(#(PanicNode::<#panic_node_types>::new(),)*);
|
||||
let params = vec![#(#temp_node_io,)*];
|
||||
let mut node_io = NodeIO::<'_, #input_type>::to_async_node_io(&node, params);
|
||||
node_io
|
||||
|
||||
}
|
||||
)
|
||||
));
|
||||
}
|
||||
Ok(quote! {
|
||||
#[cfg_attr(not(target_family = "wasm"), ctor)]
|
||||
fn register_node() {
|
||||
let mut registry = NODE_REGISTRY.lock().unwrap();
|
||||
registry.insert(
|
||||
#identifier(),
|
||||
vec![
|
||||
#(#constructors,)*
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#wasm_shim
|
||||
})
|
||||
}
|
||||
|
||||
use crate::crate_ident::CrateIdent;
|
||||
use crate::shader_nodes::{ShaderCodegen, ShaderTokens};
|
||||
use syn::visit_mut::VisitMut;
|
||||
use syn::{GenericArgument, Lifetime, Type};
|
||||
|
||||
struct LifetimeReplacer(&'static str);
|
||||
|
||||
impl VisitMut for LifetimeReplacer {
|
||||
fn visit_lifetime_mut(&mut self, lifetime: &mut Lifetime) {
|
||||
lifetime.ident = Ident::new(self.0, lifetime.ident.span());
|
||||
}
|
||||
|
||||
fn visit_type_mut(&mut self, ty: &mut Type) {
|
||||
match ty {
|
||||
Type::Reference(type_reference) => {
|
||||
if let Some(lifetime) = &mut type_reference.lifetime {
|
||||
self.visit_lifetime_mut(lifetime);
|
||||
}
|
||||
self.visit_type_mut(&mut type_reference.elem);
|
||||
}
|
||||
_ => syn::visit_mut::visit_type_mut(self, ty),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_generic_argument_mut(&mut self, arg: &mut GenericArgument) {
|
||||
if let GenericArgument::Lifetime(lifetime) = arg {
|
||||
self.visit_lifetime_mut(lifetime);
|
||||
} else {
|
||||
syn::visit_mut::visit_generic_argument_mut(self, arg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn substitute_lifetimes(mut ty: Type, lifetime: &'static str) -> Type {
|
||||
LifetimeReplacer(lifetime).visit_type_mut(&mut ty);
|
||||
ty
|
||||
}
|
||||
use syn::{Lifetime, Type};
|
||||
|
||||
/// Get only the necessary generics.
|
||||
struct FilterUsedGenerics {
|
||||
@@ -856,7 +557,7 @@ impl FilterUsedGenerics {
|
||||
}
|
||||
|
||||
/// Check if a type contains a reference to a specific identifier (e.g., a generic type parameter)
|
||||
fn type_contains_ident(ty: &Type, ident: &Ident) -> bool {
|
||||
pub(crate) fn type_contains_ident(ty: &Type, ident: &Ident) -> bool {
|
||||
struct IdentChecker<'a> {
|
||||
target: &'a Ident,
|
||||
found: bool,
|
||||
|
||||
@@ -0,0 +1,661 @@
|
||||
use crate::crate_ident::CrateIdent;
|
||||
use crate::parsing::*;
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{format_ident, quote};
|
||||
use syn::visit::Visit;
|
||||
use syn::{GenericArgument, GenericParam, Ident, Lifetime, PathArguments, Type, TypeParam, TypeParamBound};
|
||||
|
||||
pub(crate) struct GNodeTokens {
|
||||
pub(crate) in_mod: TokenStream2,
|
||||
pub(crate) top_level: TokenStream2,
|
||||
}
|
||||
|
||||
pub(crate) fn generate_gnode_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn) -> syn::Result<GNodeTokens> {
|
||||
let core_types = crate_ident.gcore()?;
|
||||
|
||||
let ctx_param = context_param(parsed);
|
||||
let ctx_ident = match ctx_param {
|
||||
Some(ctx_param) => ctx_param.ident.clone(),
|
||||
None => format_ident!("__Ctx"),
|
||||
};
|
||||
let async_fn = parsed.is_async;
|
||||
let future_kernel = is_source_kernel(&parsed.output_type);
|
||||
let async_source = async_fn || future_kernel;
|
||||
if async_fn && parsed.fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_))) {
|
||||
return Ok(GNodeTokens {
|
||||
in_mod: quote!(),
|
||||
top_level: quote!(),
|
||||
});
|
||||
}
|
||||
let snapshot_ctx = async_fn && matches!(&parsed.input.ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "CtxSnapshot"));
|
||||
|
||||
let mut ctx_bounds: Vec<TokenStream2> = match ctx_param {
|
||||
Some(ctx_param) => ctx_param
|
||||
.bounds
|
||||
.iter()
|
||||
.filter_map(|bound| match bound {
|
||||
TypeParamBound::Lifetime(_) => None,
|
||||
bound => Some(desugar_extract_lifetime(bound, core_types)),
|
||||
})
|
||||
.collect(),
|
||||
None => vec![quote!(#core_types::Ctx)],
|
||||
};
|
||||
if async_source {
|
||||
ctx_bounds.push(quote!(#core_types::CacheHash));
|
||||
}
|
||||
if snapshot_ctx {
|
||||
ctx_bounds.extend([
|
||||
quote!(#core_types::context::DeriveCtx),
|
||||
quote!(#core_types::context::ExtractFootprint),
|
||||
quote!(#core_types::context::ExtractRealTime),
|
||||
quote!(#core_types::context::ExtractAnimationTime),
|
||||
quote!(#core_types::context::ExtractPointerPosition),
|
||||
quote!(#core_types::context::ExtractIndex),
|
||||
quote!(#core_types::context::ExtractPosition),
|
||||
]);
|
||||
}
|
||||
|
||||
let derives = ctx_param.is_some_and(|ctx_param| {
|
||||
ctx_param.bounds.iter().any(|bound| match bound {
|
||||
TypeParamBound::Trait(trait_bound) => trait_bound.path.segments.last().is_some_and(|segment| segment.ident == "DeriveCtx"),
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
|
||||
let ctx_generic = match ctx_bounds.is_empty() {
|
||||
true => quote!(#ctx_ident),
|
||||
false => quote!(#ctx_ident: #(#ctx_bounds)+*),
|
||||
};
|
||||
let mut generics: Vec<TokenStream2> = parsed
|
||||
.fn_generics
|
||||
.iter()
|
||||
.map(|param| match param {
|
||||
GenericParam::Type(type_param) if Some(&type_param.ident) == ctx_param.map(|ctx_param| &ctx_param.ident) => ctx_generic.clone(),
|
||||
param => quote!(#param),
|
||||
})
|
||||
.collect();
|
||||
if ctx_param.is_none() {
|
||||
generics.push(ctx_generic);
|
||||
}
|
||||
|
||||
let fn_name = &parsed.fn_name;
|
||||
let mod_name = format_ident!("_{}_mod", parsed.mod_name);
|
||||
let struct_name = format_ident!("{}Node", parsed.struct_name);
|
||||
let output_type = &parsed.output_type;
|
||||
let trait_output = slot_value_type(&parsed.output_type);
|
||||
let raw_lazy = matches!(kernel_kind(&parsed.output_type), KernelKind::Poll(_));
|
||||
let injected_name = |ident: &Ident| async_source && (ident == "_runtime" || ident == "_source");
|
||||
let where_predicates: Vec<TokenStream2> = parsed.where_clause.iter().flat_map(|clause| clause.predicates.iter()).map(|predicate| quote!(#predicate)).collect();
|
||||
|
||||
let (data_fields, regular_fields): (Vec<_>, Vec<_>) = parsed.fields.iter().partition(|field| field.is_data_field);
|
||||
|
||||
let data_field_generic_idents: Vec<Ident> = parsed
|
||||
.fn_generics
|
||||
.iter()
|
||||
.filter_map(|generic| match generic {
|
||||
GenericParam::Type(type_param) => Some(type_param.ident.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|ident| {
|
||||
data_fields.iter().any(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => crate::codegen::type_contains_ident(ty, ident),
|
||||
_ => false,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let node_generics: Vec<Ident> = regular_fields.iter().enumerate().map(|(index, _)| format_ident!("Node{}", index)).collect();
|
||||
let struct_type_params: Vec<Ident> = data_field_generic_idents.iter().cloned().chain(node_generics.iter().cloned()).collect();
|
||||
|
||||
let data_names: Vec<&Ident> = data_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
let data_params = data_fields.iter().map(|field| {
|
||||
let pat = &field.pat_ident;
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
unreachable!("data fields are regular types");
|
||||
};
|
||||
quote!(#pat: &#ty)
|
||||
});
|
||||
|
||||
let lazy_bound = |output_type: &Type| match derives {
|
||||
true => quote!(for<'__derived> #core_types::gnode::GNode<#core_types::context::Derived<'__derived, #ctx_ident>, Output = #output_type>),
|
||||
false => quote!(#core_types::gnode::GNode<#ctx_ident, Output = #output_type>),
|
||||
};
|
||||
|
||||
let kernel_params = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).map(|field| {
|
||||
let pat = &field.pat_ident;
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(#pat: #ty),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) if raw_lazy => {
|
||||
let bound = lazy_bound(output_type);
|
||||
quote!(#pat: &impl #bound)
|
||||
}
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
|
||||
let bound = lazy_bound(output_type);
|
||||
quote!(#pat: #core_types::gnode::LazyInput<'_, impl #bound>)
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let node_bounds = regular_fields.iter().zip(&node_generics).map(|(field, node_generic)| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(#node_generic: #core_types::gnode::GNode<#ctx_ident, Output = #ty>),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
|
||||
let bound = lazy_bound(output_type);
|
||||
quote!(#node_generic: #bound)
|
||||
}
|
||||
});
|
||||
|
||||
let async_bounds = match (async_fn, future_kernel) {
|
||||
(false, false) => Vec::new(),
|
||||
(false, true) => vec![quote!(#trait_output: Clone)],
|
||||
(true, _) => {
|
||||
let output_clone = std::iter::once(quote!(#trait_output: Clone));
|
||||
let value_clones = regular_fields.iter().filter_map(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => Some(quote!(#ty: Clone)),
|
||||
_ => None,
|
||||
});
|
||||
let data_clones = data_fields.iter().filter_map(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => Some(quote!(#ty: Clone)),
|
||||
_ => None,
|
||||
});
|
||||
output_clone.chain(value_clones).chain(data_clones).collect()
|
||||
}
|
||||
};
|
||||
|
||||
let clampable_bounds = regular_fields.iter().filter_map(|field| {
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, number_hard_min, number_hard_max, .. }) = &field.ty else {
|
||||
return None;
|
||||
};
|
||||
(number_hard_min.is_some() || number_hard_max.is_some()).then(|| quote!(#ty: #core_types::misc::Clampable))
|
||||
});
|
||||
|
||||
let eval_values = regular_fields.iter().enumerate().map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(_) => quote! {
|
||||
let #name = match __cell.eval_input(#index, &self.#name, __input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
},
|
||||
ParsedFieldType::Node(_) if raw_lazy => quote!(),
|
||||
ParsedFieldType::Node(_) => quote! {
|
||||
let #name = #core_types::gnode::LazyInput::new(&self.#name, &__cell, #index);
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
let clamps = regular_fields.iter().filter_map(|field| {
|
||||
let ParsedFieldType::Regular(RegularParsedField { number_hard_min, number_hard_max, .. }) = &field.ty else {
|
||||
return None;
|
||||
};
|
||||
let name = &field.pat_ident.ident;
|
||||
let mut tokens = quote!();
|
||||
if let Some(min) = number_hard_min {
|
||||
tokens.extend(quote!(let #name = #core_types::misc::Clampable::clamp_hard_min(#name, #min);));
|
||||
}
|
||||
if let Some(max) = number_hard_max {
|
||||
tokens.extend(quote!(let #name = #core_types::misc::Clampable::clamp_hard_max(#name, #max);));
|
||||
}
|
||||
(!tokens.is_empty()).then_some(tokens)
|
||||
});
|
||||
|
||||
let call_args = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).map(|field| {
|
||||
let name = &field.pat_ident.ident;
|
||||
match &field.ty {
|
||||
ParsedFieldType::Node(_) if raw_lazy => quote!(&self.#name),
|
||||
_ => quote!(#name),
|
||||
}
|
||||
});
|
||||
|
||||
let value_field_names: Vec<&Ident> = regular_fields
|
||||
.iter()
|
||||
.filter(|field| matches!(field.ty, ParsedFieldType::Regular(_)))
|
||||
.map(|field| &field.pat_ident.ident)
|
||||
.collect();
|
||||
|
||||
let extent_impl = match &parsed.attributes.extent {
|
||||
Some(path) => quote! {
|
||||
fn extent(&self, __input: &#ctx_ident) -> #core_types::gpoll::GPoll<#core_types::gpoll::Extent> {
|
||||
#path(self, __input)
|
||||
}
|
||||
},
|
||||
None if value_field_names.is_empty() => quote!(),
|
||||
None => {
|
||||
let first = value_field_names[0];
|
||||
let mut meet = quote!(self.#first.extent(__input));
|
||||
for name in &value_field_names[1..] {
|
||||
meet = quote!(#core_types::gpoll::Extent::meet(#meet, self.#name.extent(__input)));
|
||||
}
|
||||
quote! {
|
||||
fn extent(&self, __input: &#ctx_ident) -> #core_types::gpoll::GPoll<#core_types::gpoll::Extent> {
|
||||
#meet
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let batch_impl = match &parsed.attributes.batch {
|
||||
Some(path) => quote! {
|
||||
fn eval_batch<'__batch>(
|
||||
&self,
|
||||
__input: &'__batch #ctx_ident,
|
||||
__range: ::std::ops::Range<u64>,
|
||||
__scratch: Option<&'__batch mut [::std::mem::MaybeUninit<Self::Output>]>,
|
||||
) -> #core_types::gnode::BatchStatus<'__batch, Self::Output>
|
||||
where
|
||||
#ctx_ident: #core_types::context::InjectIndex + Copy,
|
||||
{
|
||||
#path(self, __input, __range, __scratch)
|
||||
}
|
||||
},
|
||||
None => quote!(),
|
||||
};
|
||||
|
||||
let ctx_pat = &parsed.input.pat_ident;
|
||||
let fn_where = &parsed.where_clause;
|
||||
let body = &parsed.body;
|
||||
let vis = &parsed.vis;
|
||||
let kernel_fields: Vec<&&ParsedField> = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).collect();
|
||||
let kernel = match async_fn {
|
||||
false => quote! {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#vis fn #fn_name<#(#generics,)*>(#ctx_pat: &#ctx_ident #(, #data_params)* #(, #kernel_params)*) -> #output_type #fn_where #body
|
||||
},
|
||||
true => {
|
||||
let kernel_generics = parsed.fn_generics.iter().filter(|param| match param {
|
||||
GenericParam::Type(type_param) => Some(&type_param.ident) != ctx_param.map(|ctx_param| &ctx_param.ident),
|
||||
_ => true,
|
||||
});
|
||||
let snapshot_param = snapshot_ctx.then(|| quote!(#ctx_pat: #core_types::context::CtxSnapshot)).into_iter();
|
||||
let data_kernel_params = data_fields.iter().map(|field| {
|
||||
let pat = &field.pat_ident;
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
unreachable!("data fields are regular types");
|
||||
};
|
||||
quote!(#pat: #ty)
|
||||
});
|
||||
let value_kernel_params = kernel_fields.iter().map(|field| {
|
||||
let pat = &field.pat_ident;
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
unreachable!("async source fields are eager values");
|
||||
};
|
||||
quote!(#pat: #ty)
|
||||
});
|
||||
let params = snapshot_param.chain(data_kernel_params).chain(value_kernel_params);
|
||||
quote! {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#vis async fn #fn_name<#(#kernel_generics,)*>(#(#params),*) -> #output_type #fn_where #body
|
||||
}
|
||||
}
|
||||
};
|
||||
let cell_constructor = match parsed.attributes.no_partial {
|
||||
true => quote!(#core_types::gnode::StatusCell::no_partial()),
|
||||
false => quote!(#core_types::gnode::StatusCell::new()),
|
||||
};
|
||||
let kernel_call = quote!(self::#fn_name(__input #(, &self.#data_names)* #(, #call_args)*));
|
||||
let lift = match kernel_kind(&parsed.output_type) {
|
||||
KernelKind::Interrupt(_) => quote! {
|
||||
match #kernel_call {
|
||||
Ok(value) => __cell.finish(value),
|
||||
Err(interrupt) => interrupt.into(),
|
||||
}
|
||||
},
|
||||
KernelKind::Poll(_) => quote!(__cell.merge(#kernel_call)),
|
||||
_ => quote!(__cell.finish(#kernel_call)),
|
||||
};
|
||||
|
||||
let placeholder_value_names: Vec<&Ident> = kernel_fields
|
||||
.iter()
|
||||
.filter(|field| matches!(field.ty, ParsedFieldType::Regular(_)))
|
||||
.map(|field| &field.pat_ident.ident)
|
||||
.collect();
|
||||
let inflight = match &parsed.attributes.placeholder {
|
||||
Some(path) => quote!(__cell.merge(#core_types::gpoll::GPoll::Partial(#path(#(&#placeholder_value_names),*)))),
|
||||
None => quote!(#core_types::gpoll::GPoll::Pending),
|
||||
};
|
||||
let slot_check = quote! {
|
||||
let __key = #core_types::wire::cache_key(__input);
|
||||
{
|
||||
let __entries = self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(__state) = __entries.get(&__key) {
|
||||
return match __state {
|
||||
Some(value) => __cell.merge(value.clone()),
|
||||
None => #inflight,
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
let future_completion = |payload: &Type| match kernel_kind(payload) {
|
||||
KernelKind::Poll(_) => quote!(__future.await),
|
||||
KernelKind::Interrupt(_) => quote! {
|
||||
match __future.await {
|
||||
Ok(value) => #core_types::gpoll::GPoll::Final(value),
|
||||
Err(interrupt) => interrupt.into(),
|
||||
}
|
||||
},
|
||||
_ => quote!(#core_types::gpoll::GPoll::Final(__future.await)),
|
||||
};
|
||||
let eval_tail = match (async_fn, future_kernel) {
|
||||
(false, false) => lift,
|
||||
(true, _) => {
|
||||
let kernel_value_names: Vec<&Ident> = kernel_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
let snapshot_binding = snapshot_ctx.then(|| quote!(let __snapshot = #core_types::context::CtxSnapshot::capture(__input);)).into_iter();
|
||||
let snapshot_arg = snapshot_ctx.then(|| quote!(__snapshot)).into_iter();
|
||||
let future_args = snapshot_arg
|
||||
.chain(data_names.iter().map(|name| quote!(self.#name.clone())))
|
||||
.chain(kernel_value_names.iter().map(|name| quote!(#name.clone())));
|
||||
let completion = future_completion(&parsed.output_type);
|
||||
quote! {
|
||||
#slot_check
|
||||
self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, None);
|
||||
let __slot = std::sync::Arc::clone(&self.slot);
|
||||
#(#snapshot_binding)*
|
||||
let __future = self::#fn_name(#(#future_args),*);
|
||||
_runtime.0.spawn(_source, Box::pin(async move {
|
||||
let __value = #completion;
|
||||
__slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, Some(__value));
|
||||
}));
|
||||
#inflight
|
||||
}
|
||||
}
|
||||
(false, true) => {
|
||||
let (placeholder_binding, spawn_return) = match &parsed.attributes.placeholder {
|
||||
Some(path) => (
|
||||
quote!(let __placeholder = #path(#(&#placeholder_value_names),*);),
|
||||
quote!(__cell.merge(#core_types::gpoll::GPoll::Partial(__placeholder))),
|
||||
),
|
||||
None => (quote!(), quote!(#core_types::gpoll::GPoll::Pending)),
|
||||
};
|
||||
let acquire = match kernel_kind(&parsed.output_type) {
|
||||
KernelKind::FutureInterrupt(_) => quote! {
|
||||
let __future = match #kernel_call {
|
||||
Ok(future) => future,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
},
|
||||
_ => quote!(let __future = #kernel_call;),
|
||||
};
|
||||
let payload = match kernel_kind(&parsed.output_type) {
|
||||
KernelKind::Future(payload) | KernelKind::FutureInterrupt(payload) => payload,
|
||||
_ => unreachable!("guarded by future_kernel"),
|
||||
};
|
||||
let completion = future_completion(&payload);
|
||||
quote! {
|
||||
#slot_check
|
||||
#placeholder_binding
|
||||
#acquire
|
||||
self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, None);
|
||||
let __slot = std::sync::Arc::clone(&self.slot);
|
||||
_runtime.0.spawn(_source, Box::pin(async move {
|
||||
let __value = #completion;
|
||||
__slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, Some(__value));
|
||||
}));
|
||||
#spawn_return
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let wire = entries_tokens(parsed, &struct_name, &data_field_generic_idents, ®ular_fields);
|
||||
let cfg = crate::shader_nodes::modify_cfg(&parsed.attributes);
|
||||
let wire_reexport = match wire.is_empty() {
|
||||
true => quote!(),
|
||||
false => {
|
||||
let entries_name = format_ident!("{}_entries", fn_name);
|
||||
quote! {
|
||||
#cfg
|
||||
#[doc(hidden)]
|
||||
pub use #mod_name::#entries_name;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let top_level = quote! {
|
||||
#wire_reexport
|
||||
|
||||
#cfg
|
||||
#[automatically_derived]
|
||||
impl<#(#generics,)* #(#node_generics,)*> #core_types::gnode::GNode<#ctx_ident> for #mod_name::#struct_name<#(#struct_type_params,)*>
|
||||
where
|
||||
#(#node_bounds,)*
|
||||
#(#clampable_bounds,)*
|
||||
#(#async_bounds,)*
|
||||
#(#where_predicates,)*
|
||||
{
|
||||
type Output = #trait_output;
|
||||
|
||||
fn eval(&self, __input: &#ctx_ident) -> #core_types::gpoll::GPoll<Self::Output> {
|
||||
let __cell = #cell_constructor;
|
||||
#(#eval_values)*
|
||||
#(#clamps)*
|
||||
#eval_tail
|
||||
}
|
||||
|
||||
#extent_impl
|
||||
|
||||
#batch_impl
|
||||
}
|
||||
};
|
||||
|
||||
Ok(GNodeTokens {
|
||||
in_mod: wire,
|
||||
top_level: quote! {
|
||||
#kernel
|
||||
|
||||
#top_level
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn slot_value_type(output: &Type) -> Type {
|
||||
match kernel_kind(output) {
|
||||
KernelKind::Plain => output.clone(),
|
||||
KernelKind::Poll(inner) | KernelKind::Interrupt(inner) => inner,
|
||||
KernelKind::Future(payload) | KernelKind::FutureInterrupt(payload) => match kernel_kind(&payload) {
|
||||
KernelKind::Poll(inner) | KernelKind::Interrupt(inner) => inner,
|
||||
_ => payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_source_kernel(output: &Type) -> bool {
|
||||
matches!(kernel_kind(output), KernelKind::Future(_) | KernelKind::FutureInterrupt(_))
|
||||
}
|
||||
|
||||
enum KernelKind {
|
||||
Plain,
|
||||
Interrupt(Type),
|
||||
Poll(Type),
|
||||
Future(Type),
|
||||
FutureInterrupt(Type),
|
||||
}
|
||||
|
||||
fn source_future_payload(segment: &syn::PathSegment) -> Type {
|
||||
let PathArguments::AngleBracketed(args) = &segment.arguments else {
|
||||
return syn::parse_quote!(());
|
||||
};
|
||||
args.args
|
||||
.iter()
|
||||
.find_map(|argument| match argument {
|
||||
GenericArgument::Type(ty) => Some(ty.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| syn::parse_quote!(()))
|
||||
}
|
||||
|
||||
fn kernel_kind(output: &Type) -> KernelKind {
|
||||
let plain = || KernelKind::Plain;
|
||||
let Type::Path(path) = output else { return plain() };
|
||||
let Some(segment) = path.path.segments.last() else { return plain() };
|
||||
match segment.ident.to_string().as_str() {
|
||||
"GPoll" => {
|
||||
let PathArguments::AngleBracketed(args) = &segment.arguments else { return plain() };
|
||||
let inner = args.args.iter().find_map(|argument| match argument {
|
||||
GenericArgument::Type(ty) => Some(ty.clone()),
|
||||
_ => None,
|
||||
});
|
||||
inner.map(KernelKind::Poll).unwrap_or_else(plain)
|
||||
}
|
||||
"SourceFuture" => KernelKind::Future(source_future_payload(segment)),
|
||||
"Result" => {
|
||||
let PathArguments::AngleBracketed(args) = &segment.arguments else { return plain() };
|
||||
let mut types = args.args.iter().filter_map(|argument| match argument {
|
||||
GenericArgument::Type(ty) => Some(ty),
|
||||
_ => None,
|
||||
});
|
||||
let (Some(inner), Some(Type::Path(error_path))) = (types.next(), types.next()) else {
|
||||
return plain();
|
||||
};
|
||||
if !error_path.path.segments.last().is_some_and(|segment| segment.ident == "Interrupt") {
|
||||
return plain();
|
||||
}
|
||||
if let Type::Path(inner_path) = inner {
|
||||
if let Some(inner_segment) = inner_path.path.segments.last() {
|
||||
if inner_segment.ident == "SourceFuture" {
|
||||
return KernelKind::FutureInterrupt(source_future_payload(inner_segment));
|
||||
}
|
||||
}
|
||||
}
|
||||
KernelKind::Interrupt(inner.clone())
|
||||
}
|
||||
_ => plain(),
|
||||
}
|
||||
}
|
||||
|
||||
fn context_param<'a>(parsed: &'a ParsedNodeFn) -> Option<&'a TypeParam> {
|
||||
let Type::Path(path) = &parsed.input.ty else {
|
||||
return None;
|
||||
};
|
||||
let ident = path.path.get_ident()?;
|
||||
parsed.fn_generics.iter().find_map(|param| match param {
|
||||
GenericParam::Type(type_param) if &type_param.ident == ident => Some(type_param),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn type_disqualifies(ty: &Type) -> bool {
|
||||
struct Disqualifier {
|
||||
found: bool,
|
||||
}
|
||||
|
||||
impl<'ast> Visit<'ast> for Disqualifier {
|
||||
fn visit_type_reference(&mut self, _: &'ast syn::TypeReference) {
|
||||
self.found = true;
|
||||
}
|
||||
|
||||
fn visit_type_impl_trait(&mut self, _: &'ast syn::TypeImplTrait) {
|
||||
self.found = true;
|
||||
}
|
||||
|
||||
fn visit_lifetime(&mut self, _: &'ast Lifetime) {
|
||||
self.found = true;
|
||||
}
|
||||
}
|
||||
|
||||
let mut visitor = Disqualifier { found: false };
|
||||
visitor.visit_type(ty);
|
||||
visitor.found
|
||||
}
|
||||
|
||||
fn desugar_extract_lifetime(bound: &TypeParamBound, core_types: &TokenStream2) -> TokenStream2 {
|
||||
let TypeParamBound::Trait(trait_bound) = bound else {
|
||||
return quote!(#bound);
|
||||
};
|
||||
let Some(segment) = trait_bound.path.segments.last() else {
|
||||
return quote!(#bound);
|
||||
};
|
||||
if segment.ident != "ExtractArena" {
|
||||
return quote!(#bound);
|
||||
}
|
||||
let PathArguments::AngleBracketed(args) = &segment.arguments else {
|
||||
return quote!(#bound);
|
||||
};
|
||||
if args.args.len() != 1 {
|
||||
return quote!(#bound);
|
||||
}
|
||||
let Some(GenericArgument::Lifetime(lifetime)) = args.args.first() else {
|
||||
return quote!(#bound);
|
||||
};
|
||||
quote!(#core_types::context::ExtractArena<ArenaRef = &#lifetime #core_types::arena::Arena>)
|
||||
}
|
||||
|
||||
fn entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
if !data_field_generic_idents.is_empty() {
|
||||
return quote!();
|
||||
}
|
||||
let Some(rows) = implementation_rows(parsed, regular_fields) else {
|
||||
return quote!();
|
||||
};
|
||||
let rows: Vec<&Vec<Type>> = rows.iter().filter(|row| row.iter().all(|ty| !type_disqualifies(ty))).collect();
|
||||
if rows.is_empty() {
|
||||
return quote!();
|
||||
}
|
||||
|
||||
let fn_name = &parsed.fn_name;
|
||||
let entries_name = format_ident!("{}_entries", fn_name);
|
||||
let arity = regular_fields.len();
|
||||
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
|
||||
let entries = rows.iter().map(|row| {
|
||||
let types = row.iter();
|
||||
let boxed_types = row.iter().map(|ty| quote!(::std::boxed::Box<gcore::wire::ErasedGNode<#ty>>));
|
||||
let output = quote!(<#struct_name<#(#boxed_types),*> as gcore::gnode::GNode<gcore::context::ContextImpl<'static>>>::Output);
|
||||
let downcasts = names.iter().zip(row.iter()).map(|(name, ty)| {
|
||||
quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;)
|
||||
});
|
||||
quote! {
|
||||
gcore::wire::RegistryEntry {
|
||||
io: gcore::wire::NodeIoRecord {
|
||||
inputs: vec![#(gcore::concrete!(#types)),*],
|
||||
output: gcore::concrete!(#output),
|
||||
},
|
||||
wire: |inputs| {
|
||||
if inputs.len() != #arity {
|
||||
return Err(gcore::wire::WireError::Arity { expected: #arity, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
Ok(gcore::wire::EdgeHandle::new(::std::boxed::Box::new(#struct_name::new(#(#names),*)) as ::std::boxed::Box<gcore::wire::ErasedGNode<#output>>))
|
||||
},
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
quote! {
|
||||
pub fn #entries_name() -> ::std::vec::Vec<gcore::wire::RegistryEntry> {
|
||||
vec![#(#entries),*]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn implementation_rows(parsed: &ParsedNodeFn, regular_fields: &[&ParsedField]) -> Option<Vec<Vec<Type>>> {
|
||||
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
|
||||
let open_generics: Vec<&Ident> = parsed
|
||||
.fn_generics
|
||||
.iter()
|
||||
.filter_map(|param| match param {
|
||||
GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() => Some(&type_param.ident),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let candidates: Vec<Vec<Type>> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => match implementations.is_empty() {
|
||||
false => Some(implementations.iter().cloned().collect()),
|
||||
true => open_generics.iter().all(|generic| !crate::codegen::type_contains_ident(ty, generic)).then(|| vec![ty.clone()]),
|
||||
},
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, implementations, .. }) => match implementations.is_empty() {
|
||||
false => Some(implementations.iter().map(|implementation| implementation.output.clone()).collect()),
|
||||
true => open_generics.iter().all(|generic| !crate::codegen::type_contains_ident(output_type, generic)).then(|| vec![output_type.clone()]),
|
||||
},
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
|
||||
let row_count = candidates.iter().map(|types| types.len()).max().unwrap_or(1).max(1);
|
||||
Some(
|
||||
(0..row_count)
|
||||
.map(|row| candidates.iter().map(|types| types[row.min(types.len() - 1)].clone()).collect())
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ mod buffer_struct;
|
||||
mod codegen;
|
||||
mod crate_ident;
|
||||
mod derive_choice_type;
|
||||
mod gcodegen;
|
||||
mod parsing;
|
||||
mod shader_nodes;
|
||||
mod validation;
|
||||
|
||||
@@ -56,6 +56,14 @@ 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,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -311,6 +319,10 @@ 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 content = input;
|
||||
// let content;
|
||||
@@ -453,13 +465,63 @@ 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, ...)]
|
||||
"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', and 'inject_scope'.
|
||||
Supported attributes are 'category', 'name', 'path', 'skip_impl', 'properties', 'cfg', 'shader_node', 'serialize', 'memoize', 'inject_scope', 'placeholder', 'extent', 'batch', and 'no_partial'.
|
||||
Example usage:
|
||||
#[node_macro::node(..., name("Test Node"), ...)]
|
||||
"#
|
||||
@@ -493,6 +555,10 @@ impl Parse for NodeFnAttributes {
|
||||
serialize,
|
||||
memoize,
|
||||
inject_scope,
|
||||
placeholder,
|
||||
extent,
|
||||
batch,
|
||||
no_partial,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -931,6 +997,10 @@ pub fn new_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<TokenS
|
||||
let crate_ident = CrateIdent::default();
|
||||
let 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.is_async || crate::gcodegen::is_source_kernel(&parsed_node.output_type) {
|
||||
let core_types = crate_ident.gcore()?.clone();
|
||||
parsed_node.inject_async_source_fields(&core_types);
|
||||
}
|
||||
crate::validation::validate_node_fn(&parsed_node).map_err(|e| Error::new(e.span(), format!("Validation error:\n{e}")))?;
|
||||
generate_node_code(&crate_ident, &parsed_node).map_err(|e| Error::new(e.span(), format!("Failed to generate node code:\n{e}")))
|
||||
}
|
||||
@@ -958,6 +1028,43 @@ impl ParsedNodeFn {
|
||||
self.input.pat_ident.ident = Ident::new("__ctx", self.input.pat_ident.ident.span());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn inject_async_source_fields(&mut self, core_types: &TokenStream2) {
|
||||
let hidden_field = |name: &str, ty: Type, value_source: ParsedValueSource| ParsedField {
|
||||
pat_ident: PatIdent {
|
||||
attrs: Vec::new(),
|
||||
by_ref: None,
|
||||
mutability: None,
|
||||
ident: Ident::new(name, proc_macro2::Span::call_site()),
|
||||
subpat: None,
|
||||
},
|
||||
name: None,
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::Hidden,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty,
|
||||
exposed: false,
|
||||
value_source,
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
number_hard_max: None,
|
||||
number_mode_range: false,
|
||||
implementations: Default::default(),
|
||||
gpu_image: false,
|
||||
}),
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
is_data_field: false,
|
||||
};
|
||||
self.fields.push(hidden_field(
|
||||
"_runtime",
|
||||
parse_quote!(#core_types::runtime::RuntimeHandle),
|
||||
ParsedValueSource::Scope(parse_quote!("graphene_std::runtime::RuntimeNode")),
|
||||
));
|
||||
self.fields.push(hidden_field("_source", parse_quote!(#core_types::SourceId), ParsedValueSource::None));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1082,6 +1189,10 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
},
|
||||
fn_name: Ident::new("add", Span::call_site()),
|
||||
struct_name: Ident::new("Add", Span::call_site()),
|
||||
@@ -1152,6 +1263,10 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
},
|
||||
fn_name: Ident::new("transform", Span::call_site()),
|
||||
struct_name: Ident::new("Transform", Span::call_site()),
|
||||
@@ -1236,6 +1351,10 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
},
|
||||
fn_name: Ident::new("circle", Span::call_site()),
|
||||
struct_name: Ident::new("Circle", Span::call_site()),
|
||||
@@ -1302,6 +1421,10 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
},
|
||||
fn_name: Ident::new("levels", Span::call_site()),
|
||||
struct_name: Ident::new("Levels", Span::call_site()),
|
||||
@@ -1380,6 +1503,10 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
},
|
||||
fn_name: Ident::new("add", Span::call_site()),
|
||||
struct_name: Ident::new("Add", Span::call_site()),
|
||||
@@ -1461,6 +1588,10 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: false,
|
||||
},
|
||||
fn_name: Ident::new("load_image", Span::call_site()),
|
||||
struct_name: Ident::new("LoadImage", Span::call_site()),
|
||||
@@ -1527,6 +1658,10 @@ mod tests {
|
||||
serialize: None,
|
||||
memoize: false,
|
||||
inject_scope: false,
|
||||
placeholder: None,
|
||||
extent: None,
|
||||
batch: None,
|
||||
no_partial: 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,9 +231,9 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
description: "".to_string(),
|
||||
widget_override: Default::default(),
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty: parse_quote!(&'a WgpuExecutor),
|
||||
ty: parse_quote!(std::sync::Arc<WgpuExecutor>),
|
||||
exposed: true,
|
||||
value_source: ParsedValueSource::Scope(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode")),
|
||||
value_source: ParsedValueSource::Scope(parse_quote!("graphene_std::platform_application_io::WgpuExecutorArcNode")),
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
@@ -287,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).await
|
||||
}, #gpu_image, #uniform_buffer)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -305,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![parse_quote!('a: 'n)],
|
||||
fn_generics: Vec::new(),
|
||||
where_clause: None,
|
||||
input: Input {
|
||||
pat_ident: self.parsed.input.pat_ident.clone(),
|
||||
@@ -314,7 +314,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
context_features: self.parsed.input.context_features.clone(),
|
||||
},
|
||||
output_type: raster_gpu,
|
||||
is_async: true,
|
||||
is_async: false,
|
||||
fields,
|
||||
body,
|
||||
description: self.parsed.description.clone(),
|
||||
|
||||
@@ -11,6 +11,7 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
validate_primary_input_expose,
|
||||
validate_min_max,
|
||||
validate_range_slider_bounds,
|
||||
validate_async_source,
|
||||
];
|
||||
|
||||
for validator in validators {
|
||||
@@ -20,6 +21,52 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_async_source(parsed: &ParsedNodeFn) {
|
||||
let snapshot_ctx = matches!(&parsed.input.ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "CtxSnapshot"));
|
||||
let future_kernel = crate::gcodegen::is_source_kernel(&parsed.output_type);
|
||||
if parsed.is_async && future_kernel {
|
||||
emit_error!(
|
||||
parsed.output_type.span(),
|
||||
"an `async fn` kernel already is the async part; returning `SourceFuture` is the sync-prologue form, so drop the `async` keyword or return the value directly"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if !parsed.is_async {
|
||||
if snapshot_ctx {
|
||||
emit_error!(parsed.input.pat_ident.span(), "`CtxSnapshot` is the async source context; synchronous nodes take `impl Ctx` and read through extract bounds");
|
||||
}
|
||||
if !future_kernel {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if parsed.is_async {
|
||||
for field in &parsed.fields {
|
||||
if matches!(field.ty, ParsedFieldType::Node(_)) {
|
||||
emit_error!(
|
||||
field.pat_ident.span(),
|
||||
"`async fn` source nodes cannot take `impl Node` inputs: the spawned future outlives any borrow of the graph, so it cannot evaluate other nodes; use the sync-prologue form (return `SourceFuture`) to evaluate lazy inputs before spawning"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let ctx_ident = match &parsed.input.ty {
|
||||
Type::Path(path) => path.path.get_ident(),
|
||||
_ => None,
|
||||
};
|
||||
for param in &parsed.fn_generics {
|
||||
let GenericParam::Type(type_param) = param else { continue };
|
||||
if Some(&type_param.ident) == ctx_ident {
|
||||
continue;
|
||||
}
|
||||
if crate::codegen::type_contains_ident(&parsed.output_type, &type_param.ident) {
|
||||
emit_error!(
|
||||
parsed.output_type.span(),
|
||||
"async source nodes do not support generic output types yet; the slot map needs the output type stated per implementation row, which is not wired up until a node requires it"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_min_max(parsed: &ParsedNodeFn) {
|
||||
for field in &parsed.fields {
|
||||
if let ParsedField {
|
||||
|
||||
@@ -3,15 +3,12 @@ use crate::brush_stroke::{BrushStroke, BrushStyle};
|
||||
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 core_types::Ctx;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_nodes::blending_nodes::blend_colors;
|
||||
use raster_nodes::std_nodes::{empty_image, extend_image_to_bounds};
|
||||
@@ -63,7 +60,7 @@ impl<P: Pixel + Alpha> Sample for BrushStampGenerator<P> {
|
||||
/// The feather exponent is calculated from hardness to determine edge softness.
|
||||
/// 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(#[unit(" px")] diameter: f64, color: Color, hardness: f64, flow: f64) -> BrushStampGenerator<Color> {
|
||||
fn brush_stamp_generator(_: impl Ctx, #[unit(" px")] diameter: f64, color: Color, hardness: f64, flow: f64) -> BrushStampGenerator<Color> {
|
||||
// Diameter
|
||||
let radius = diameter / 2.;
|
||||
|
||||
@@ -83,9 +80,9 @@ fn brush_stamp_generator(#[unit(" px")] diameter: f64, color: Color, hardness: f
|
||||
|
||||
/// Used to efficiently paint brush strokes. Applies the same texture repeatedly at different positions with proper blending and boundary handling.
|
||||
#[node_macro::node(category(""), skip_impl)]
|
||||
fn blit<BlendFn>(mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>>
|
||||
fn blit<BlendFn>(_: impl Ctx, mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>>
|
||||
where
|
||||
BlendFn: for<'any_input> Node<'any_input, (Color, Color), Output = Color>,
|
||||
BlendFn: Fn(Color, Color) -> Color,
|
||||
{
|
||||
if positions.is_empty() {
|
||||
return target;
|
||||
@@ -125,7 +122,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.eval((src_pixel, *dst_pixel));
|
||||
*dst_pixel = blend_mode(src_pixel, *dst_pixel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,10 +131,10 @@ where
|
||||
target
|
||||
}
|
||||
|
||||
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);
|
||||
pub fn create_brush_texture(brush_style: &BrushStyle) -> Raster<CPU> {
|
||||
let stamp = brush_stamp_generator(&(), brush_style.diameter, brush_style.color, brush_style.hardness, brush_style.flow);
|
||||
let 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()
|
||||
@@ -188,7 +185,7 @@ pub fn blend_with_mode(background: Item<Raster<CPU>>, foreground: Item<Raster<CP
|
||||
/// Generates the brush strokes painted with the Brush tool as a raster image.
|
||||
/// If an input image is supplied, strokes are drawn on top of it, expanding bounds as needed.
|
||||
#[node_macro::node(category("Raster"))]
|
||||
async fn brush(
|
||||
fn brush(
|
||||
_: impl Ctx,
|
||||
/// Optional raster content that may be drawn onto.
|
||||
mut background: List<Raster<CPU>>,
|
||||
@@ -224,7 +221,7 @@ async 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();
|
||||
};
|
||||
|
||||
@@ -234,7 +231,7 @@ async 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).await;
|
||||
let tex = create_brush_texture(&stroke.style);
|
||||
cache.store_brush(stroke.style.clone(), tex.clone());
|
||||
brush_texture = Some(tex);
|
||||
}
|
||||
@@ -255,21 +252,14 @@ async fn brush(
|
||||
let stroke_origin_in_layer = bbox.start - snap_offset - DVec2::splat(stroke.style.diameter / 2.);
|
||||
let stroke_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))
|
||||
// EmptyImageNode::new(CopiedNode::new(stroke_to_layer), CopiedNode::new(Color::TRANSPARENT)).eval(())
|
||||
empty_image(&(), stroke_to_layer, List::new_from_element(Color::TRANSPARENT))
|
||||
};
|
||||
|
||||
let list = blit_node.eval(blit_target).await;
|
||||
let list = blit(&(), blit_target, brush_texture, positions, |a, b| blend_colors(a, b, BlendMode::Normal, 1.));
|
||||
assert_eq!(list.len(), 1);
|
||||
list.into_iter().next().unwrap_or_default()
|
||||
};
|
||||
@@ -291,7 +281,7 @@ async fn brush(
|
||||
for stroke in trace.into_iter().map(|row| row.into_element()) {
|
||||
let mut brush_texture = cache.get_cached_brush(&stroke.style);
|
||||
if brush_texture.is_none() {
|
||||
let tex = create_brush_texture(&stroke.style).await;
|
||||
let tex = create_brush_texture(&stroke.style);
|
||||
cache.store_brush(stroke.style.clone(), tex.clone());
|
||||
brush_texture = Some(tex);
|
||||
}
|
||||
@@ -305,17 +295,13 @@ async fn brush(
|
||||
_ => BlendMode::Restore,
|
||||
};
|
||||
|
||||
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();
|
||||
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(|(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)));
|
||||
actual_image = blend_image_closure(erase_restore_mask, actual_image, |a, b| blend_colors(a, b, BlendMode::MultiplyAlpha, 1.));
|
||||
}
|
||||
|
||||
let transform: DAffine2 = actual_image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
@@ -410,16 +396,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));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_brush_output_size() {
|
||||
#[test]
|
||||
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 {
|
||||
@@ -433,8 +419,7 @@ mod test {
|
||||
blend_mode: BlendMode::Normal,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
);
|
||||
assert_eq!(image.element(0).unwrap().width, 20);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::List;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl};
|
||||
use core_types::{CacheHash, Color, Context, Ctx, DeriveCtx, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::vector_types::GradientStops;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
@@ -61,8 +62,8 @@ fn animation_time(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
async fn quantize_real_time<T>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs,
|
||||
fn quantize_real_time<T>(
|
||||
ctx: impl Ctx + ExtractRealTime + DeriveCtx,
|
||||
#[implementations(
|
||||
Context -> bool,
|
||||
Context -> u32,
|
||||
@@ -84,11 +85,11 @@ async fn quantize_real_time<T>(
|
||||
Context -> List<f64>,
|
||||
Context -> (),
|
||||
)]
|
||||
value: impl Node<'n, Context<'static>, Output = T>,
|
||||
value: impl Node<Context<'_>, Output = T>,
|
||||
#[default(1)]
|
||||
#[unit("sec")]
|
||||
quantum: f64,
|
||||
) -> T {
|
||||
) -> GPoll<T> {
|
||||
let time = ctx.try_real_time().unwrap_or_default();
|
||||
let time = time / 1000.;
|
||||
let mut quantized_time = (time * quantum.recip()).round() / quantum.recip();
|
||||
@@ -96,13 +97,13 @@ async fn quantize_real_time<T>(
|
||||
quantized_time = time;
|
||||
}
|
||||
let quantized_time = quantized_time * 1000.;
|
||||
let new_context = OwnedContextImpl::from(ctx).with_real_time(quantized_time);
|
||||
value.eval(Some(new_context.into())).await
|
||||
let scope = ctx.scope().with_real_time(Some(quantized_time));
|
||||
value.eval(&ctx.with_scope(&scope))
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
async fn quantize_animation_time<T>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs,
|
||||
fn quantize_animation_time<T>(
|
||||
ctx: impl Ctx + ExtractAnimationTime + DeriveCtx,
|
||||
#[implementations(
|
||||
Context -> bool,
|
||||
Context -> u32,
|
||||
@@ -124,18 +125,18 @@ async fn quantize_animation_time<T>(
|
||||
Context -> List<f64>,
|
||||
Context -> (),
|
||||
)]
|
||||
value: impl Node<'n, Context<'static>, Output = T>,
|
||||
value: impl Node<Context<'_>, Output = T>,
|
||||
#[default(1)]
|
||||
#[unit("sec")]
|
||||
quantum: f64,
|
||||
) -> T {
|
||||
) -> GPoll<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 new_context = OwnedContextImpl::from(ctx).with_animation_time(quantized_time);
|
||||
value.eval(Some(new_context.into())).await
|
||||
let scope = ctx.scope().with_animation_time(Some(quantized_time));
|
||||
value.eval(&ctx.with_scope(&scope))
|
||||
}
|
||||
|
||||
/// 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))]
|
||||
async fn read_position(
|
||||
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 @@ async fn read_position(
|
||||
///
|
||||
/// Nested loops can enable 2D or higher-dimensional iteration by using the *Loop Level* parameter to read the index from outer levels of loops.
|
||||
#[node_macro::node(category("Context"), path(core_types::vector))]
|
||||
async fn read_index(
|
||||
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,5 +1,6 @@
|
||||
use core::f64;
|
||||
use core_types::context::{CloneVarArgs, Context, ContextFeatures, Ctx, ExtractAll};
|
||||
use core_types::context::{Context, ContextFeatures, Ctx, DeriveCtx};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
@@ -12,8 +13,8 @@ use raster_types::{CPU, GPU, Raster};
|
||||
/// Filters out what should be unused components of the context based on the specified requirements.
|
||||
/// This node is inserted by the compiler to "zero out" unused context components.
|
||||
#[node_macro::node(category(""))]
|
||||
async fn context_modification<T>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
fn context_modification<T>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
/// The data to pass through, evaluated with the stripped down context.
|
||||
#[implementations(
|
||||
Context -> (),
|
||||
@@ -41,13 +42,12 @@ async fn context_modification<T>(
|
||||
Context -> AttributeValueDyn,
|
||||
Context -> ListDyn,
|
||||
)]
|
||||
value: impl Node<Context<'static>, Output = T>,
|
||||
value: impl Node<Context<'_>, Output = T>,
|
||||
/// The parts of the context to keep when evaluating the input value. All other parts are nullified.
|
||||
features_to_keep: ContextFeatures,
|
||||
) -> T {
|
||||
let new_context = OwnedContextImpl::from_flags(ctx, features_to_keep);
|
||||
|
||||
value.eval(Some(new_context.into())).await
|
||||
) -> GPoll<T> {
|
||||
let scope = ctx.scope().nullified(features_to_keep);
|
||||
value.eval(&ctx.nullified(features_to_keep, &scope))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use core_types::WasmNotSend;
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::memo::*;
|
||||
use std::hash::DefaultHasher;
|
||||
@@ -10,7 +10,7 @@ use std::sync::Mutex;
|
||||
///
|
||||
/// Stores the last evaluated data that flowed through this node and immediately returns that data on subsequent renders if the context has not changed.
|
||||
#[node_macro::node(category("General"), path(graphene_core::memo), skip_impl)]
|
||||
async fn memoize<I: CacheHash + Send + 'n, T: Clone + WasmNotSend>(input: I, #[data] cache: Arc<Mutex<Option<(u64, T)>>>, content: impl Node<I, Output = T>) -> T {
|
||||
fn memoize<I: CacheHash, T: Clone>(input: I, #[data] cache: Arc<Mutex<Option<(u64, T)>>>, content: impl Node<I, Output = T>) -> Result<T, Interrupt> {
|
||||
// Caches the output of a given node called with a specific input.
|
||||
//
|
||||
// A cache miss occurs when the Option is None. In this case, the node evaluates the inner node and memoizes (stores) the result.
|
||||
@@ -24,28 +24,31 @@ async fn memoize<I: CacheHash + Send + 'n, T: Clone + WasmNotSend>(input: I, #[d
|
||||
let hash = hasher.finish();
|
||||
|
||||
if let Some(data) = cache.lock().as_ref().unwrap().as_ref().and_then(|data| (data.0 == hash).then_some(data.1.clone())) {
|
||||
return data;
|
||||
return Ok(data);
|
||||
}
|
||||
|
||||
let value = content.eval(input).await;
|
||||
let value = content.eval(input)?;
|
||||
*cache.lock().unwrap() = Some((hash, value.clone()));
|
||||
value
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
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"), skip_impl)]
|
||||
async fn monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>(
|
||||
fn monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>(
|
||||
input: I,
|
||||
#[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
|
||||
) -> Result<T, Interrupt> {
|
||||
let output = content.eval(input)?;
|
||||
*io.lock().unwrap() = Some(Arc::new(IORecord {
|
||||
input: input.clone(),
|
||||
output: output.clone(),
|
||||
}));
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn serialize_monitor<I: Clone + 'static + Send + Sync, T: Clone + 'static + Send + Sync>(io: &MonitorValue<I, T>) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
|
||||
|
||||
@@ -16,8 +16,8 @@ fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), skip_impl)]
|
||||
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
|
||||
fn convert<T: Send + Convert<O, C>, O: Send, C: Send>(ctx: impl Ctx + ExtractFootprint, value: T, converter: C, _out_ty: PhantomData<O>) -> O {
|
||||
value.convert(*ctx.try_footprint().unwrap_or(&Footprint::DEFAULT), converter)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, Color, Context, Ctx, DeriveCtx, ExtractFootprint};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
@@ -9,8 +10,8 @@ use vector_types::GradientStops;
|
||||
|
||||
/// Constructs a single-element `Artboard[]` with the given content and metadata stored as row attributes.
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn create_artboard<T: IntoGraphicList>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
pub fn create_artboard<T: IntoGraphicList>(
|
||||
ctx: impl Ctx + ExtractFootprint + DeriveCtx,
|
||||
/// Graphics to include within the artboard.
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
@@ -22,7 +23,7 @@ pub async fn create_artboard<T: IntoGraphicList>(
|
||||
Context -> List<GradientStops>,
|
||||
Context -> DAffine2,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = T>,
|
||||
content: impl Node<Context<'_>, Output = T>,
|
||||
/// Coordinate of the top-left corner of the artboard within the document.
|
||||
location: DVec2,
|
||||
/// Width and height of the artboard within the document.
|
||||
@@ -32,14 +33,9 @@ pub async fn create_artboard<T: IntoGraphicList>(
|
||||
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible.
|
||||
#[default(true)]
|
||||
clip: bool,
|
||||
) -> 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();
|
||||
) -> Result<List<Artboard>, Interrupt> {
|
||||
let translated = ctx.modify_footprint(|footprint| footprint.translate(location));
|
||||
let content = content.eval(&translated.ctx())?.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
|
||||
@@ -50,11 +46,11 @@ pub async 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
|
||||
List::new_from_item(
|
||||
Ok(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),
|
||||
)
|
||||
))
|
||||
}
|
||||
@@ -2,7 +2,8 @@ use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
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, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, Color, Context, Ctx, DeriveCtx};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
@@ -108,8 +109,8 @@ pub fn extract_element<T: Clone + Default + Send + Sync + 'static>(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("General"))]
|
||||
async fn map<Item: AnyHash + Send + Sync + CacheHash>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
fn map<Item: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
@@ -127,23 +128,24 @@ async fn map<Item: AnyHash + Send + Sync + CacheHash>(
|
||||
Context -> List<GradientStops>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
mapped: impl Node<Context<'static>, Output = List<Item>>,
|
||||
) -> List<Item> {
|
||||
mapped: impl Node<Context<'_>, Output = List<Item>>,
|
||||
) -> Result<List<Item>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
let mut rows = List::new();
|
||||
|
||||
for (i, row) in content.into_iter().enumerate() {
|
||||
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;
|
||||
let item = List::new_from_item(row);
|
||||
let scoped = ctx.push_vararg(&item);
|
||||
let list = mapped.eval(&scoped.ctx().promoted(&spilled, i as u64))?;
|
||||
|
||||
rows.extend(list);
|
||||
}
|
||||
|
||||
rows
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("General"))]
|
||||
async fn mirror<T: 'n + Send + Clone>(
|
||||
fn mirror<T: Send + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
@@ -229,8 +231,8 @@ pub fn path_of_subgraph(_: impl Ctx, node_path: List<NodeId>) -> List<NodeId> {
|
||||
/// The value is type-erased into an `AttributeValueDyn` by an auto-inserted convert node, so this node only
|
||||
/// monomorphizes over `T` instead of the cartesian product `(T, U)`.
|
||||
#[node_macro::node(category("Attributes: Write"))]
|
||||
async fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
/// The `List` to set the named attribute on (one value per item).
|
||||
#[implementations(
|
||||
List<Artboard>,
|
||||
@@ -252,15 +254,17 @@ async 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<'n, Context<'static>, Output = AttributeValueDyn>,
|
||||
) -> List<T> {
|
||||
value: impl Node<Context<'_>, Output = AttributeValueDyn>,
|
||||
) -> Result<List<T>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
for index in 0..content.len() {
|
||||
let row = content.clone_item(index).expect("index is within bounds");
|
||||
let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_vararg(Box::new(List::new_from_item(row))).with_index(index);
|
||||
let v = value.eval(owned_ctx.into_context()).await;
|
||||
let item = List::new_from_item(row);
|
||||
let scoped = ctx.push_vararg(&item);
|
||||
let v = value.eval(&scoped.ctx().promoted(&spilled, index as u64))?;
|
||||
content.set_attribute_value_dyn(&name, index, v);
|
||||
}
|
||||
content
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
/// Sets a named attribute on the primary list, with each value taken from the corresponding item's element in the source list (paired by index, wrapping if the source has fewer items).
|
||||
@@ -497,7 +501,7 @@ fn read_attribute_raster(
|
||||
|
||||
/// Joins two `List`s of the same type, extending the base `List` with the items from the new `List`.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub async fn extend<T: 'n + Send + Clone>(
|
||||
pub fn extend<T: 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>)]
|
||||
@@ -517,7 +521,7 @@ pub async fn extend<T: 'n + Send + Clone>(
|
||||
/// Performs an obsolete function as part of a migration from an older document format.
|
||||
/// Users are advised to delete this node and replace it with a new one.
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn legacy_layer_extend<T: 'n + Send + Clone>(
|
||||
pub fn legacy_layer_extend<T: 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]
|
||||
@@ -544,7 +548,7 @@ pub async fn legacy_layer_extend<T: 'n + Send + Clone>(
|
||||
/// Nests the input graphical content in a wrapper graphic. This essentially "groups" the input.
|
||||
/// The inverse of this node is 'Flatten Graphic'.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub async fn wrap_graphic<T: Into<Graphic> + 'n>(
|
||||
pub fn wrap_graphic<T: Into<Graphic>>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
@@ -565,7 +569,7 @@ pub async fn wrap_graphic<T: Into<Graphic> + 'n>(
|
||||
/// Converts a list of graphical content into a `Graphic[]` by placing it into an element of a new wrapper `Graphic[]`.
|
||||
/// 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 async fn to_graphic<T: IntoGraphicList>(
|
||||
pub fn to_graphic<T: IntoGraphicList>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
@@ -583,7 +587,7 @@ pub async fn to_graphic<T: IntoGraphicList>(
|
||||
|
||||
/// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: bool) -> List<Graphic> {
|
||||
pub fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: bool) -> List<Graphic> {
|
||||
// TODO: Avoid mutable reference, instead return a new List<Graphic>?
|
||||
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() {
|
||||
@@ -620,7 +624,7 @@ pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten:
|
||||
|
||||
/// Converts a `Graphic[]` into a `Vector[]` by deeply flattening any vector content it contains, and discarding any non-vector content.
|
||||
#[node_macro::node(category("Vector"))]
|
||||
pub async fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
pub fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
let graphic_list = content.into_graphic_list();
|
||||
let mut output: List<Vector> = graphic_list.clone().into_flattened_list();
|
||||
|
||||
@@ -653,19 +657,19 @@ pub async fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(L
|
||||
|
||||
/// Converts a `Graphic[]` into a `Raster[]` by deeply flattening any raster content it contains, and discarding any non-raster content.
|
||||
#[node_macro::node(category("Raster"))]
|
||||
pub async fn flatten_raster<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Raster<CPU>>)] content: T) -> List<Raster<CPU>> {
|
||||
pub fn flatten_raster<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Raster<CPU>>)] content: T) -> List<Raster<CPU>> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
/// 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 async fn flatten_color<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] content: T) -> List<Color> {
|
||||
pub fn flatten_color<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] content: T) -> List<Color> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
/// 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 async fn flatten_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<GradientStops>)] content: T) -> List<GradientStops> {
|
||||
pub fn flatten_gradient<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<GradientStops>)] content: T) -> List<GradientStops> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ use core_types::math::bbox::Bbox;
|
||||
use core_types::transform::Footprint;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, WasmNotSend};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::runtime::SourceFuture;
|
||||
use core_types::{Color, Ctx};
|
||||
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
|
||||
pub use graph_craft::application_io::*;
|
||||
@@ -137,7 +139,7 @@ fn image_to_bytes(_: impl Ctx, image: List<Raster<CPU>>) -> List<u8> {
|
||||
|
||||
/// Loads binary from URLs and local asset paths. Returns a transparent placeholder if the resource fails to load, allowing rendering to continue.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: String) -> Arc<[u8]> {
|
||||
async fn load_resource(_: impl Ctx, _primary: (), #[name("URL")] url: String) -> Arc<[u8]> {
|
||||
let placeholder = || -> Arc<[u8]> { Arc::from(Vec::<u8>::new()) };
|
||||
|
||||
let response = match reqwest::Client::new().get(&url).send().await {
|
||||
@@ -185,14 +187,14 @@ fn decode_image(_: impl Ctx, data: Arc<[u8]>) -> List<Raster<CPU>> {
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[node_macro::node(category(""))]
|
||||
async fn create_canvas(_: impl Ctx) -> CanvasHandle {
|
||||
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 + 'n>(
|
||||
fn rasterize<T: WasmNotSend + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Vector>,
|
||||
@@ -262,20 +264,26 @@ where
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub async fn editor_api<'a: 'n>(_: impl Ctx, #[scope("editor-api")] editor_api: &'a PlatformEditorApi) -> &'a PlatformEditorApi {
|
||||
pub fn editor_api<'a>(_: impl Ctx, #[scope("editor-api")] editor_api: &'a PlatformEditorApi) -> &'a PlatformEditorApi {
|
||||
editor_api
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
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");
|
||||
pub fn resource<'a>(_: impl Ctx, hash: ResourceHash, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> SourceFuture<GPoll<Resource>> {
|
||||
let application_io = editor_api.application_io.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"),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> &'a ::wgpu_executor::WgpuExecutor {
|
||||
pub fn wgpu_executor<'a>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> &'a ::wgpu_executor::WgpuExecutor {
|
||||
editor_api
|
||||
.application_io
|
||||
.as_ref()
|
||||
@@ -285,6 +293,16 @@ pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)]
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub async fn try_wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Option<&'a ::wgpu_executor::WgpuExecutor> {
|
||||
pub fn try_wgpu_executor<'a>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Option<&'a ::wgpu_executor::WgpuExecutor> {
|
||||
editor_api.application_io.as_ref()?.gpu_executor()
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub fn wgpu_executor_arc<'a>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> std::sync::Arc<::wgpu_executor::WgpuExecutor> {
|
||||
editor_api
|
||||
.application_io
|
||||
.as_ref()
|
||||
.expect("ApplicationIo not available")
|
||||
.gpu_executor_arc()
|
||||
.expect("GPU executor not available")
|
||||
}
|
||||
@@ -9,10 +9,10 @@ use graphic_types::raster_types::Texture;
|
||||
use rendering::{RenderParams, SvgRender, SvgRenderOutput};
|
||||
use std::fmt::Write;
|
||||
use wgpu::util::DeviceExt;
|
||||
use wgpu_executor::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache};
|
||||
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn render_background<'a: 'n>(
|
||||
fn render_background<'a>(
|
||||
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
|
||||
#[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
|
||||
data: RenderOutput,
|
||||
@@ -35,14 +35,12 @@ async fn render_background<'a: 'n>(
|
||||
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(),
|
||||
})
|
||||
.await;
|
||||
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(),
|
||||
});
|
||||
|
||||
RenderOutputType::Texture(blended)
|
||||
}
|
||||
@@ -121,7 +119,7 @@ async fn render_background<'a: 'n>(
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
async fn composite_background_pipeline<'a: 'n>(
|
||||
fn composite_background_pipeline<'a>(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
|
||||
#[data] pipeline: WgpuPipelineCache,
|
||||
@@ -148,7 +146,7 @@ pub struct CompositeBackgroundArgs<'a> {
|
||||
zoom: f32,
|
||||
}
|
||||
|
||||
impl AsyncWgpuPipeline for CompositeBackground {
|
||||
impl WgpuPipeline for CompositeBackground {
|
||||
type Args<'a> = CompositeBackgroundArgs<'a>;
|
||||
type Out = Texture;
|
||||
|
||||
@@ -331,7 +329,7 @@ impl AsyncWgpuPipeline for CompositeBackground {
|
||||
}
|
||||
}
|
||||
|
||||
async fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
let &CompositeBackgroundArgs {
|
||||
foreground,
|
||||
backgrounds,
|
||||
@@ -340,7 +338,7 @@ impl AsyncWgpuPipeline for CompositeBackground {
|
||||
} = args;
|
||||
|
||||
let foreground_size = foreground.size();
|
||||
let output = executor.request_texture(UVec2::new(foreground_size.width, foreground_size.height)).await;
|
||||
let output = executor.request_texture(UVec2::new(foreground_size.width, foreground_size.height));
|
||||
|
||||
if zoom <= 0. {
|
||||
return output;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! 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::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl};
|
||||
use core_types::{Context, Ctx, DeriveCtx, ExtractAll};
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
@@ -321,25 +322,23 @@ fn flood_fill(start: &TileCoord, tile_set: &HashSet<TileCoord>, visited: &mut Ha
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn render_output_cache<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + ExtractRealTime + ExtractAnimationTime + ExtractPointerPosition + Sync,
|
||||
pub fn render_output_cache<'a>(
|
||||
ctx: impl Ctx + ExtractAll + DeriveCtx,
|
||||
#[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: impl Node<Context<'_>, Output = RenderOutput>,
|
||||
#[data] tile_cache: TileCache,
|
||||
) -> RenderOutput {
|
||||
let footprint = ctx.footprint();
|
||||
) -> Result<RenderOutput, Interrupt> {
|
||||
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");
|
||||
let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint);
|
||||
return data.eval(context.into_context()).await;
|
||||
return data.eval(&ctx.derived());
|
||||
};
|
||||
|
||||
// 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 {
|
||||
let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint).with_vararg(Box::new(render_params.clone()));
|
||||
return data.eval(context.into_context()).await;
|
||||
return data.eval(&ctx.derived());
|
||||
}
|
||||
|
||||
let zoom = footprint.scale_magnitudes().x;
|
||||
@@ -375,8 +374,38 @@ pub async fn render_output_cache<'a: 'n>(
|
||||
if missing_region.tiles.is_empty() {
|
||||
continue;
|
||||
}
|
||||
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);
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
tile_cache.store_regions(new_regions.clone());
|
||||
@@ -385,68 +414,18 @@ pub async fn render_output_cache<'a: 'n>(
|
||||
|
||||
// If no regions, fall back to direct render
|
||||
if all_regions.is_empty() {
|
||||
let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint).with_vararg(Box::new(render_params.clone()));
|
||||
return data.eval(context.into_context()).await;
|
||||
return data.eval(&ctx.derived());
|
||||
}
|
||||
|
||||
let executor = executor.expect("GPU executor not available");
|
||||
let output_texture = executor.request_texture(physical_resolution).await;
|
||||
let output_texture = executor.request_texture(physical_resolution);
|
||||
|
||||
let combined_metadata = composite_cached_regions(&all_regions, &output_texture, &device_origin_offset, &footprint.transform, executor);
|
||||
|
||||
RenderOutput {
|
||||
Ok(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::{CloneVarArgs, ExtractAll, ExtractVarArgs};
|
||||
use core_types::{Color, Context, Ctx, ExtractFootprint, OwnedContextImpl, WasmNotSend};
|
||||
use core_types::{Color, Context, Ctx, DeriveCtx, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots, WasmNotSend};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphene_application_io::{ExportFormat, RenderConfig};
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
@@ -23,8 +23,8 @@ pub struct RenderIntermediate {
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
ctx: impl Ctx + ExtractVarArgs + ExtractAll + CloneVarArgs,
|
||||
fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
ctx: impl Ctx + ExtractVarArgs + DeriveCtx,
|
||||
#[implementations(
|
||||
Context -> List<Artboard>,
|
||||
Context -> List<Graphic>,
|
||||
@@ -34,21 +34,19 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
|
||||
Context -> List<GradientStops>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
data: impl Node<Context<'static>, Output = T>,
|
||||
) -> RenderIntermediate {
|
||||
data: impl Node<Context<'_>, Output = T>,
|
||||
) -> Result<RenderIntermediate, Interrupt> {
|
||||
let data = data.eval(&ctx.derived())?;
|
||||
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);
|
||||
match &render_params.render_output_type {
|
||||
Ok(match &render_params.render_output_type {
|
||||
RenderOutputTypeRequest::Vello => {
|
||||
let mut scene = vello::Scene::new();
|
||||
|
||||
@@ -70,11 +68,11 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
|
||||
metadata,
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn render<'a: 'n>(
|
||||
fn render<'a>(
|
||||
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
|
||||
data: RenderIntermediate,
|
||||
@@ -133,7 +131,6 @@ async fn render<'a: 'n>(
|
||||
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)
|
||||
}
|
||||
@@ -144,11 +141,13 @@ async fn render<'a: 'n>(
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
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 {
|
||||
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");
|
||||
|
||||
let render_output_type = match render_config.export_format {
|
||||
ExportFormat::Svg => RenderOutputTypeRequest::Svg,
|
||||
ExportFormat::Raster => RenderOutputTypeRequest::Vello,
|
||||
@@ -169,16 +168,78 @@ async fn create_context<'a: 'n>(
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
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;
|
||||
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))?;
|
||||
|
||||
result.metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale)));
|
||||
result
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope, VarArgsResult};
|
||||
use core_types::gnode::GNode;
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::{ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime};
|
||||
use graphene_application_io::TimingInformation;
|
||||
|
||||
struct ProbeNode;
|
||||
|
||||
impl<'a> GNode<ContextImpl<'a>> for ProbeNode {
|
||||
type Output = RenderOutput;
|
||||
|
||||
fn eval(&self, ctx: &ContextImpl<'a>) -> GPoll<RenderOutput> {
|
||||
let render_params = ctx.vararg(0).unwrap().downcast_ref::<RenderParams>().expect("the vararg chain must start with RenderParams");
|
||||
assert_eq!(render_params.scale, 2.0);
|
||||
assert!(matches!(ctx.vararg(1), Err(VarArgsResult::IndexOutOfBounds)), "the RenderConfig must not leak downstream");
|
||||
assert_eq!(ctx.footprint().transform, glam::DAffine2::from_scale(glam::DVec2::splat(2.0)) * Footprint::DEFAULT.transform);
|
||||
assert_eq!(ctx.try_real_time(), Some(1.5));
|
||||
assert_eq!(ctx.try_animation_time(), Some(2.0));
|
||||
assert_eq!(ctx.try_pointer_position(), Some(glam::DVec2::new(3.0, 4.0)));
|
||||
GPoll::Final(RenderOutput {
|
||||
data: RenderOutputType::Buffer { data: Vec::new(), width: 0, height: 0 },
|
||||
metadata: RenderMetadata::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_context_builds_the_render_context_from_the_root_vararg() {
|
||||
let arena = Arena::new(256);
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
let render_config = RenderConfig {
|
||||
scale: 2.0,
|
||||
time: TimingInformation {
|
||||
time: 1.5,
|
||||
animation_time: std::time::Duration::from_secs(2),
|
||||
},
|
||||
pointer: glam::DVec2::new(3.0, 4.0),
|
||||
..Default::default()
|
||||
};
|
||||
let varargs = VarArgLink {
|
||||
args: VarArgSlots::Single(&render_config),
|
||||
outer: None,
|
||||
};
|
||||
let ctx = root.with_varargs(&varargs);
|
||||
|
||||
let graph = CreateContextNode::new(ProbeNode);
|
||||
let GPoll::Final(result) = <CreateContextNode<ProbeNode> as GNode<ContextImpl>>::eval(&graph, &ctx) else {
|
||||
panic!("create_context must complete synchronously");
|
||||
};
|
||||
assert_eq!(result.data, RenderOutputType::Buffer { data: Vec::new(), width: 0, height: 0 });
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,22 @@
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use core_types::{Context, Ctx, DeriveCtx, ExtractAll};
|
||||
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::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache};
|
||||
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn render_pixel_preview<'a: 'n>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync,
|
||||
pub fn render_pixel_preview(
|
||||
ctx: impl Ctx + ExtractAll + DeriveCtx,
|
||||
#[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache,
|
||||
data: impl Node<Context<'static>, Output = RenderOutput> + Send + Sync,
|
||||
) -> RenderOutput {
|
||||
data: impl Node<Context<'_>, Output = RenderOutput>,
|
||||
) -> Result<RenderOutput, Interrupt> {
|
||||
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");
|
||||
let context = OwnedContextImpl::from(ctx).into_context();
|
||||
return data.eval(context).await;
|
||||
return data.eval(&ctx.derived());
|
||||
};
|
||||
let physical_scale = render_params.scale;
|
||||
|
||||
@@ -24,8 +24,7 @@ pub async fn render_pixel_preview<'a: 'n>(
|
||||
let viewport_zoom = footprint.scale_magnitudes().x;
|
||||
|
||||
if render_params.render_mode != RenderMode::PixelPreview || !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || viewport_zoom <= 1. {
|
||||
let context = OwnedContextImpl::from(ctx).into_context();
|
||||
return data.eval(context).await;
|
||||
return data.eval(&ctx.derived());
|
||||
}
|
||||
|
||||
let physical_resolution = footprint.resolution;
|
||||
@@ -51,31 +50,29 @@ pub async fn render_pixel_preview<'a: 'n>(
|
||||
quality: footprint.quality,
|
||||
};
|
||||
|
||||
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 scoped = ctx.push_vararg(&render_params);
|
||||
let mut result = data.eval(&scoped.ctx().with_footprint(&upstream_footprint))?;
|
||||
|
||||
let RenderOutputType::Texture(ref source_texture) = result.data else { return result };
|
||||
let RenderOutputType::Texture(ref source_texture) = result.data else { return Ok(result) };
|
||||
|
||||
let logical_transform = DAffine2::from_scale(DVec2::splat(1. / physical_scale)) * footprint.transform;
|
||||
let 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,
|
||||
})
|
||||
.await;
|
||||
let resampled = pipeline.run::<PixelPreview>(&PixelPreviewArgs {
|
||||
source: source_texture.as_ref(),
|
||||
transform: &transform,
|
||||
size: physical_resolution,
|
||||
});
|
||||
|
||||
result.data = RenderOutputType::Texture(resampled);
|
||||
|
||||
result.metadata.apply_transform(footprint.transform * DAffine2::from_translation(upstream_min));
|
||||
|
||||
result
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
async fn pixel_preview_pipeline<'a: 'n>(
|
||||
fn pixel_preview_pipeline<'a>(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Option<&'a WgpuExecutor>,
|
||||
#[data] pipeline: WgpuPipelineCache,
|
||||
@@ -97,7 +94,7 @@ pub struct PixelPreviewArgs<'a> {
|
||||
size: UVec2,
|
||||
}
|
||||
|
||||
impl AsyncWgpuPipeline for PixelPreview {
|
||||
impl WgpuPipeline for PixelPreview {
|
||||
type Args<'a> = PixelPreviewArgs<'a>;
|
||||
type Out = Texture;
|
||||
|
||||
@@ -169,11 +166,11 @@ impl AsyncWgpuPipeline for PixelPreview {
|
||||
PixelPreview { pipeline, bind_group_layout }
|
||||
}
|
||||
|
||||
async fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out {
|
||||
let context = &executor.context();
|
||||
let &PixelPreviewArgs { source, transform, size } = args;
|
||||
|
||||
let output = executor.request_texture(size).await;
|
||||
let output = executor.request_texture(size);
|
||||
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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;
|
||||
@@ -740,7 +741,7 @@ fn logical_not(
|
||||
|
||||
/// Evaluates either the "If True" or "If False" input branch based on whether the input condition is true or false.
|
||||
#[node_macro::node(category("Math: Logic"))]
|
||||
async fn switch<T, C: Send + 'n + Clone>(
|
||||
fn switch<T, C>(
|
||||
#[implementations(Context)] ctx: C,
|
||||
condition: bool,
|
||||
#[expose]
|
||||
@@ -781,8 +782,8 @@ async fn switch<T, C: Send + 'n + Clone>(
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
if_false: impl Node<C, Output = T>,
|
||||
) -> T {
|
||||
if condition { if_true.eval(ctx).await } else { if_false.eval(ctx).await }
|
||||
) -> GPoll<T> {
|
||||
if condition { if_true.eval(ctx) } else { if_false.eval(ctx) }
|
||||
}
|
||||
|
||||
/// Constructs a bool value which may be set to true or false.
|
||||
@@ -995,36 +996,36 @@ mod 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.);
|
||||
}
|
||||
|
||||
@@ -1036,26 +1037,228 @@ mod test {
|
||||
|
||||
#[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);
|
||||
assert_eq!(super::modulo(&(), -5_f64, 2_f64, false), -1_f64);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod graphene_test {
|
||||
use super::*;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope, ExtractIndex};
|
||||
use core_types::gnode::{BatchStatus, GNode};
|
||||
use core_types::gpoll::{Finality, GPoll};
|
||||
use core_types::wire::{EdgeHandle, ErasedGNode, resolve_and_wire};
|
||||
use std::mem::MaybeUninit;
|
||||
|
||||
struct SourceNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> GNode<Input> for SourceNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
struct IndexNode;
|
||||
|
||||
impl<Input: ExtractIndex> GNode<Input> for IndexNode {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<f64> {
|
||||
GPoll::Final(input.innermost_index() as f64)
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_fixture(arena: &Arena) -> EvalScope<'_> {
|
||||
EvalScope::new(None, None, None, &[], arena)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_add_evaluates_through_the_gnode_path() {
|
||||
let arena = Arena::new(64);
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph = AddNode::new(SourceNode(1.0f64), SourceNode(2.0f64));
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_add_batches_through_the_erased_edge() {
|
||||
let arena = Arena::new(64);
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let erased: Box<ErasedGNode<f64>> = Box::new(AddNode::new(IndexNode, SourceNode(10.0f64)));
|
||||
let mut scratch = [const { MaybeUninit::uninit() }; 4];
|
||||
let status = erased.eval_batch(&ctx, 2..6, Some(&mut scratch));
|
||||
let BatchStatus::Filled(lanes, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
assert_eq!(lanes, &[12.0, 13.0, 14.0, 15.0]);
|
||||
assert_eq!(finality, Finality::AllFinal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_wire_constructor_resolves_and_wires() {
|
||||
let arena = Arena::new(64);
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let entries = logical_or_entries();
|
||||
let value = EdgeHandle::new(Box::new(SourceNode(true)) as Box<ErasedGNode<bool>>);
|
||||
let other_value = EdgeHandle::new(Box::new(SourceNode(false)) as Box<ErasedGNode<bool>>);
|
||||
let wired = resolve_and_wire(&entries[0], vec![value, other_value]).unwrap().downcast::<bool>().unwrap();
|
||||
|
||||
assert_eq!(GNode::eval(&wired, &ctx), GPoll::Final(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_add_registers_one_entry_per_implementation() {
|
||||
let arena = Arena::new(64);
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let entries = add_entries();
|
||||
assert_eq!(entries.len(), 6);
|
||||
assert_eq!(entries[0].io.inputs, vec![core_types::concrete!(f64), core_types::concrete!(f64)]);
|
||||
assert_eq!(entries[0].io.output, core_types::concrete!(f64));
|
||||
assert_eq!(entries[3].io.inputs, vec![core_types::concrete!(DVec2), core_types::concrete!(DVec2)]);
|
||||
assert_eq!(entries[3].io.output, core_types::concrete!(DVec2));
|
||||
|
||||
let augend = EdgeHandle::new(Box::new(SourceNode(1.5f64)) as Box<ErasedGNode<f64>>);
|
||||
let addend = EdgeHandle::new(Box::new(SourceNode(2.5f64)) as Box<ErasedGNode<f64>>);
|
||||
let wired = resolve_and_wire(&entries[0], vec![augend, addend]).unwrap().downcast::<f64>().unwrap();
|
||||
|
||||
assert_eq!(GNode::eval(&wired, &ctx), GPoll::Final(4.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_switch_evaluates_only_the_taken_branch() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
struct CountingSource(Arc<AtomicU32>, f64);
|
||||
|
||||
impl<Input> GNode<Input> for CountingSource {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
GPoll::Final(self.1)
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64);
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let taken = Arc::new(AtomicU32::new(0));
|
||||
let untaken = Arc::new(AtomicU32::new(0));
|
||||
let graph = SwitchNode::new(SourceNode(true), CountingSource(taken.clone(), 1.0), CountingSource(untaken.clone(), 2.0));
|
||||
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Final(1.0));
|
||||
assert_eq!(taken.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(untaken.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_switch_passes_branch_status_through() {
|
||||
struct PendingSource;
|
||||
|
||||
impl<Input> GNode<Input> for PendingSource {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
GPoll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
struct PartialSource;
|
||||
|
||||
impl<Input> GNode<Input> for PartialSource {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
GPoll::Partial(7.0)
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64);
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let pending = SwitchNode::new(SourceNode(true), PendingSource, PartialSource);
|
||||
assert_eq!(GNode::eval(&pending, &ctx), GPoll::Pending);
|
||||
|
||||
let partial = SwitchNode::new(SourceNode(false), PendingSource, PartialSource);
|
||||
assert_eq!(GNode::eval(&partial, &ctx), GPoll::Partial(7.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_switch_merges_condition_status_into_the_branch_result() {
|
||||
struct PartialCondition;
|
||||
|
||||
impl<Input> GNode<Input> for PartialCondition {
|
||||
type Output = bool;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<bool> {
|
||||
GPoll::Partial(true)
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64);
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph = SwitchNode::new(PartialCondition, SourceNode(1.0f64), SourceNode(2.0f64));
|
||||
assert_eq!(GNode::eval(&graph, &ctx), GPoll::Partial(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_eval_computes_on_stand_in_and_traces_fallback() {
|
||||
struct FallbackNode;
|
||||
|
||||
impl<Input> GNode<Input> for FallbackNode {
|
||||
type Output = f64;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<f64> {
|
||||
GPoll::fallback(0.0, "upstream failed")
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64);
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let graph = AddNode::new(FallbackNode, SourceNode(5.0f64));
|
||||
let GPoll::Fallback(boxed) = GNode::eval(&graph, &ctx) else {
|
||||
panic!("fallback must propagate with the computed stand-in");
|
||||
};
|
||||
assert_eq!(boxed.0, 5.0);
|
||||
assert!(boxed.1.kind == "upstream failed");
|
||||
assert_eq!(boxed.1.trace, vec![0]);
|
||||
}
|
||||
}
|
||||
@@ -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)]
|
||||
async fn boolean_operation<I: graphic_types::IntoGraphicList>(
|
||||
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>)]
|
||||
|
||||
@@ -8,7 +8,7 @@ use raster_types::{CPU, Raster};
|
||||
use std::cmp::{max, min};
|
||||
|
||||
#[node_macro::node(category("Raster: Filter"))]
|
||||
async fn dehaze(_: impl Ctx, image_frame: List<Raster<CPU>>, strength: Percentage) -> List<Raster<CPU>> {
|
||||
fn dehaze(_: impl Ctx, image_frame: List<Raster<CPU>>, strength: Percentage) -> List<Raster<CPU>> {
|
||||
image_frame
|
||||
.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"))]
|
||||
async fn blur(
|
||||
fn blur(
|
||||
_: impl Ctx,
|
||||
/// The image to be blurred.
|
||||
image_frame: List<Raster<CPU>>,
|
||||
@@ -124,7 +124,7 @@ async fn blur(
|
||||
|
||||
/// Applies a median filter to reduce noise while preserving edges.
|
||||
#[node_macro::node(category("Raster: Filter"))]
|
||||
async fn median_filter(
|
||||
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"))]
|
||||
async fn gradient_map<T: Adjust<Color>>(
|
||||
fn gradient_map<T: Adjust<Color>>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Raster<CPU>>,
|
||||
|
||||
@@ -4,7 +4,7 @@ use core_types::list::{Item, List};
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
#[node_macro::node(category("Color"))]
|
||||
async fn image_color_palette(
|
||||
fn image_color_palette(
|
||||
_: impl Ctx,
|
||||
image: List<Raster<CPU>>,
|
||||
#[default(4)]
|
||||
|
||||
@@ -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<'a: 'n>(_: impl Ctx, resource: Resource) -> List<Raster<CPU>> {
|
||||
pub fn image(_: impl Ctx, resource: Resource) -> List<Raster<CPU>> {
|
||||
let image_data = resource.as_ref();
|
||||
|
||||
let Some(image) = ::image::load_from_memory(image_data).ok() else {
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
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, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, OwnedContextImpl};
|
||||
use core_types::{ATTR_TRANSFORM, Color, Ctx, DeriveCtx, InjectVarArgs};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::{Graphic, Vector};
|
||||
use raster_types::{CPU, Raster};
|
||||
use vector_types::GradientStops;
|
||||
|
||||
#[node_macro::node(category("Repeat"))]
|
||||
async fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
@@ -18,35 +19,35 @@ async fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
content: impl Node<Context<'_>, Output = List<T>>,
|
||||
#[default(1)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
reverse: bool,
|
||||
) -> List<T> {
|
||||
) -> Result<List<T>, Interrupt> {
|
||||
// Someday this node can have the option to generate infinitely instead of a fixed count (basically `std::iter::repeat`).
|
||||
|
||||
let count = count as usize;
|
||||
let count = count as u64;
|
||||
let spilled = ctx.index_head();
|
||||
|
||||
let mut result_list = List::new();
|
||||
|
||||
for index in 0..count {
|
||||
let index = if reverse { count - index - 1 } else { index };
|
||||
|
||||
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index);
|
||||
let generated_content = content.eval(new_ctx.into_context()).await;
|
||||
let generated_content = content.eval(&ctx.promoted(&spilled, index))?;
|
||||
|
||||
for generated_row in generated_content.into_iter() {
|
||||
result_list.push(generated_row);
|
||||
}
|
||||
}
|
||||
|
||||
result_list
|
||||
Ok(result_list)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Repeat"))]
|
||||
pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
pub fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
@@ -54,7 +55,7 @@ pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
content: impl Node<Context<'_>, 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,
|
||||
@@ -62,10 +63,11 @@ pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
#[default(5)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
) -> List<T> {
|
||||
) -> Result<List<T>, Interrupt> {
|
||||
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();
|
||||
|
||||
@@ -74,8 +76,7 @@ pub async 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 new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index as usize);
|
||||
let generated_content = content.eval(new_ctx.into_context()).await;
|
||||
let generated_content = content.eval(&ctx.promoted(&spilled, index as u64))?;
|
||||
|
||||
for row_index in 0..generated_content.len() {
|
||||
let Some(mut row) = generated_content.clone_item(row_index) else { continue };
|
||||
@@ -89,12 +90,12 @@ pub async fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
}
|
||||
}
|
||||
|
||||
result_list
|
||||
Ok(result_list)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Repeat"))]
|
||||
async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
@@ -102,7 +103,7 @@ async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
content: impl Node<Context<'_>, Output = List<T>>,
|
||||
start_angle: Angle,
|
||||
#[unit(" px")]
|
||||
#[default(5)]
|
||||
@@ -110,7 +111,8 @@ async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
#[default(5)]
|
||||
#[hard(1..)]
|
||||
count: u32,
|
||||
) -> List<T> {
|
||||
) -> Result<List<T>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
let mut result_list = List::new();
|
||||
|
||||
for index in 0..count {
|
||||
@@ -118,8 +120,7 @@ async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
let translation = DAffine2::from_translation(radius * DVec2::Y);
|
||||
let transform = angle * translation;
|
||||
|
||||
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index as usize);
|
||||
let generated_content = content.eval(new_ctx.into_context()).await;
|
||||
let generated_content = content.eval(&ctx.promoted(&spilled, index as u64))?;
|
||||
|
||||
for row_index in 0..generated_content.len() {
|
||||
let Some(mut row) = generated_content.clone_item(row_index) else { continue };
|
||||
@@ -133,12 +134,12 @@ async fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
}
|
||||
}
|
||||
|
||||
result_list
|
||||
Ok(result_list)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Repeat"), name("Repeat on Points"))]
|
||||
async fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs,
|
||||
fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
ctx: impl Ctx + DeriveCtx + InjectVarArgs,
|
||||
points: List<Vector>,
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
@@ -147,40 +148,36 @@ async fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
content: impl Node<Context<'_>, Output = List<T>>,
|
||||
reverse: bool,
|
||||
) -> List<T> {
|
||||
) -> Result<List<T>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
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 mut iteration = async |index, point| {
|
||||
let positions = points_element.point_domain.positions();
|
||||
let range: Box<dyn Iterator<Item = (usize, &DVec2)>> = match reverse {
|
||||
true => Box::new(positions.iter().enumerate().rev()),
|
||||
false => Box::new(positions.iter().enumerate()),
|
||||
};
|
||||
|
||||
for (index, &point) in range {
|
||||
let transformed_point = transform.transform_point2(point);
|
||||
|
||||
let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(transformed_point);
|
||||
let generated_content = content.eval(new_ctx.into_context()).await;
|
||||
let scoped = ctx.push_position(transformed_point);
|
||||
let generated_content = content.eval(&scoped.ctx().promoted(&spilled, index as u64))?;
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
let range = points_element.point_domain.positions().iter().enumerate();
|
||||
if reverse {
|
||||
for (index, &point) in range.rev() {
|
||||
iteration(index, point).await;
|
||||
}
|
||||
} else {
|
||||
for (index, &point) in range {
|
||||
iteration(index, point).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result_list
|
||||
Ok(result_list)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -7,10 +7,11 @@ 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::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, OwnedContextImpl};
|
||||
use core_types::{Context, Ctx, DeriveCtx, ExtractVarArgs};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
@@ -768,25 +769,25 @@ fn string_join(
|
||||
|
||||
/// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop.
|
||||
#[node_macro::node(category("Text"))]
|
||||
async fn map_string(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll,
|
||||
fn map_string(
|
||||
ctx: impl Ctx + DeriveCtx,
|
||||
strings: List<String>,
|
||||
#[expose]
|
||||
#[implementations(Context -> String)]
|
||||
mapped: impl Node<Context<'static>, Output = String>,
|
||||
) -> List<String> {
|
||||
mapped: impl Node<Context<'_>, Output = String>,
|
||||
) -> Result<List<String>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
let mut result = List::new();
|
||||
|
||||
for (i, row) in strings.into_iter().enumerate() {
|
||||
let string = row.into_element();
|
||||
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;
|
||||
let scoped = ctx.push_vararg(&string);
|
||||
let mapped_string = mapped.eval(&scoped.ctx().promoted(&spilled, i as u64))?;
|
||||
|
||||
result.push(Item::new_from_element(mapped_string));
|
||||
}
|
||||
|
||||
result
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Reads the current string from within a **Map String** node's loop.
|
||||
|
||||
@@ -2,7 +2,8 @@ use core::f64;
|
||||
use core_types::color::Color;
|
||||
use core_types::list::{List, ListDyn};
|
||||
use core_types::transform::{ApplyTransform, ScaleType, Transform};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, ModifyFootprint, OwnedContextImpl};
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::{ATTR_TRANSFORM, Context, Ctx, DeriveCtx, ExtractFootprint, InjectFootprint, ModifyFootprint};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::Vector;
|
||||
@@ -11,8 +12,8 @@ use vector_types::GradientStops;
|
||||
|
||||
/// Applies the specified transform to the input value, which may be a graphic type or another transform.
|
||||
#[node_macro::node(category("Math: Transform"))]
|
||||
async fn transform<T: ApplyTransform + 'n + 'static>(
|
||||
ctx: impl Ctx + CloneVarArgs + ExtractAll + ModifyFootprint,
|
||||
fn transform<T: ApplyTransform + 'static>(
|
||||
ctx: impl Ctx + ExtractFootprint + DeriveCtx + ModifyFootprint,
|
||||
#[implementations(
|
||||
Context -> DAffine2,
|
||||
Context -> DVec2,
|
||||
@@ -24,31 +25,24 @@ async fn transform<T: ApplyTransform + 'n + 'static>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = T>,
|
||||
content: impl Node<Context<'_>, Output = T>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: DVec2,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_rotation")] rotation: f64,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_scale")]
|
||||
#[default(1., 1.)]
|
||||
scale: DVec2,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_skew")] skew: DVec2,
|
||||
) -> T {
|
||||
) -> Result<T, Interrupt> {
|
||||
let trs = DAffine2::from_scale_angle_translation(scale, rotation.to_radians(), translation);
|
||||
let skew = DAffine2::from_cols_array(&[1., skew.y.to_radians().tan(), skew.x.to_radians().tan(), 1., 0., 0.]);
|
||||
let matrix = trs * skew;
|
||||
|
||||
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;
|
||||
let transformed = ctx.modify_footprint(|footprint| footprint.apply_transform(&matrix));
|
||||
let mut transform_target = content.eval(&transformed.ctx())?;
|
||||
|
||||
transform_target.left_apply_transform(&matrix);
|
||||
|
||||
transform_target
|
||||
Ok(transform_target)
|
||||
}
|
||||
|
||||
/// Resets the desired components of the input transform to their default values. If all components are reset, the output will be set to the identity transform.
|
||||
@@ -114,7 +108,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))]
|
||||
async fn extract_transform(_: impl Ctx, content: ListDyn) -> DAffine2 {
|
||||
fn extract_transform(_: impl Ctx, content: ListDyn) -> DAffine2 {
|
||||
content.attribute::<DAffine2>(ATTR_TRANSFORM, 0).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
|
||||
@@ -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(""))]
|
||||
async fn path_modify(_ctx: impl Ctx, mut vector: List<Vector>, modification: Box<VectorModification>, node_path: List<NodeId>) -> List<Vector> {
|
||||
fn path_modify(_ctx: impl Ctx, mut vector: List<Vector>, modification: Box<VectorModification>, node_path: List<NodeId>) -> List<Vector> {
|
||||
use core_types::list::Item;
|
||||
|
||||
if vector.is_empty() {
|
||||
@@ -35,7 +35,7 @@ async fn path_modify(_ctx: impl Ctx, mut vector: List<Vector>, modification: Box
|
||||
|
||||
/// Applies the vector path's local transformation to its geometry and resets the transform to the identity.
|
||||
#[node_macro::node(category("Vector"))]
|
||||
async fn apply_transform(_ctx: impl Ctx, mut vector: List<Vector>) -> List<Vector> {
|
||||
fn apply_transform(_ctx: impl Ctx, mut vector: List<Vector>) -> List<Vector> {
|
||||
let (elements, transforms) = vector.element_and_attribute_slices_mut::<DAffine2>(ATTR_TRANSFORM);
|
||||
for (element, transform) in elements.iter_mut().zip(transforms.iter_mut()) {
|
||||
for (_, point) in element.point_domain.positions_mut() {
|
||||
|
||||
@@ -7,9 +7,10 @@ use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, ItemAttributeValues, List,
|
||||
use core_types::registry::types::{Angle, Length, Multiplier, Percentage, PixelLength, Progression, SeedValue};
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::gpoll::Interrupt;
|
||||
use core_types::{
|
||||
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, CloneVarArgs,
|
||||
Color, Context, Ctx, ExtractAll, OwnedContextImpl,
|
||||
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color, Context,
|
||||
Ctx, DeriveCtx,
|
||||
};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::Vector;
|
||||
@@ -88,7 +89,7 @@ impl VectorListIterMut for List<Vector> {
|
||||
|
||||
/// Uniquely sets the fill and/or stroke style of every vector element to individual colors sampled along a chosen gradient.
|
||||
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector))]
|
||||
async fn assign_colors<T>(
|
||||
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>)]
|
||||
@@ -115,7 +116,7 @@ async fn assign_colors<T>(
|
||||
repeat_every: u32,
|
||||
) -> T
|
||||
where
|
||||
T: VectorListIterMut + 'n + Send,
|
||||
T: VectorListIterMut+ Send,
|
||||
{
|
||||
let Some(row) = gradient.into_iter().next() else { return content };
|
||||
|
||||
@@ -156,7 +157,7 @@ where
|
||||
|
||||
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
|
||||
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("fill_properties"))]
|
||||
async fn fill<V: VectorListIterMut + 'n + Send, F: IntoGraphicList + 'n + Send + 'static>(
|
||||
fn fill<V: VectorListIterMut+ Send, F: IntoGraphicList+ Send + 'static>(
|
||||
_: impl Ctx,
|
||||
/// The content with vector paths to apply the fill style to.
|
||||
#[implementations(
|
||||
@@ -251,7 +252,7 @@ impl IntoF64Vec for String {
|
||||
|
||||
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
|
||||
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("stroke_properties"))]
|
||||
async fn stroke<V, L: IntoF64Vec, P: IntoGraphicList + 'n + Send + 'static>(
|
||||
fn stroke<V, L: IntoF64Vec, P: IntoGraphicList+ Send + 'static>(
|
||||
_: impl Ctx,
|
||||
/// The content with vector paths to apply the stroke style to.
|
||||
#[implementations(
|
||||
@@ -323,7 +324,7 @@ async fn stroke<V, L: IntoF64Vec, P: IntoGraphicList + 'n + Send + 'static>(
|
||||
dash_offset: f64,
|
||||
) -> List<V>
|
||||
where
|
||||
List<V>: VectorListIterMut + 'n + Send,
|
||||
List<V>: VectorListIterMut+ Send,
|
||||
{
|
||||
let dash_lengths = dash_lengths.into_vec().into_iter().map(|length| length.max(0.)).collect();
|
||||
|
||||
@@ -356,7 +357,7 @@ where
|
||||
}
|
||||
|
||||
#[node_macro::node(name("Copy to Points"), category("Repeat"), path(core_types::vector))]
|
||||
async fn copy_to_points<I: 'n + Send + Clone>(
|
||||
fn copy_to_points<I: Send + Clone>(
|
||||
_: impl Ctx,
|
||||
points: List<Vector>,
|
||||
/// Artwork to be copied and placed at each point.
|
||||
@@ -440,7 +441,7 @@ async fn copy_to_points<I: 'n + Send + Clone>(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn round_corners(
|
||||
fn round_corners(
|
||||
_: impl Ctx,
|
||||
source: List<Vector>,
|
||||
#[hard(0..)]
|
||||
@@ -777,7 +778,7 @@ pub mod extrude_algorithms {
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn extrude(_: impl Ctx, mut source: List<Vector>, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) -> List<Vector> {
|
||||
fn extrude(_: impl Ctx, mut source: List<Vector>, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) -> List<Vector> {
|
||||
for vector in source.iter_element_values_mut() {
|
||||
extrude_algorithms::extrude(vector, direction, joining_algorithm);
|
||||
}
|
||||
@@ -785,7 +786,7 @@ async fn extrude(_: impl Ctx, mut source: List<Vector>, direction: DVec2, joinin
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn box_warp(_: impl Ctx, content: List<Vector>, #[expose] rectangle: List<Vector>) -> List<Vector> {
|
||||
fn box_warp(_: impl Ctx, content: List<Vector>, #[expose] rectangle: List<Vector>) -> List<Vector> {
|
||||
let Some(target) = rectangle.element(0).cloned() else { return content };
|
||||
let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
|
||||
@@ -870,7 +871,7 @@ fn bilinear_interpolate(t: DVec2, quad: &[DVec2; 4]) -> DVec2 {
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
|
||||
async fn pack_strips<T: 'n + Send + Clone>(
|
||||
fn pack_strips<T: Send + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
@@ -991,7 +992,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))]
|
||||
async fn auto_tangents(
|
||||
fn auto_tangents(
|
||||
_: impl Ctx,
|
||||
source: List<Vector>,
|
||||
/// The amount of spread for the auto-tangents, from 0 (sharp corner) to 1 (full spread).
|
||||
@@ -1145,7 +1146,7 @@ async fn auto_tangents(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn bounding_box(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
fn bounding_box(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
content
|
||||
.into_iter()
|
||||
.map(|mut row| {
|
||||
@@ -1170,7 +1171,7 @@ async fn bounding_box(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
|
||||
async fn dimensions(_: impl Ctx, content: List<Vector>) -> DVec2 {
|
||||
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)])
|
||||
@@ -1186,7 +1187,7 @@ fn as_vector(_: impl Ctx, value: List<Vector>) -> List<Vector> {
|
||||
|
||||
/// Creates a polyline from a series of vector points, replacing any existing segments and regions that may already exist.
|
||||
#[node_macro::node(category("Vector"), name("Points to Polyline"), path(core_types::vector))]
|
||||
async fn points_to_polyline(_: impl Ctx, mut points: List<Vector>, #[default(true)] closed: bool) -> List<Vector> {
|
||||
fn points_to_polyline(_: impl Ctx, mut points: List<Vector>, #[default(true)] closed: bool) -> List<Vector> {
|
||||
for vector in points.iter_element_values_mut() {
|
||||
let mut segment_domain = SegmentDomain::new();
|
||||
let mut next_id = SegmentId::ZERO;
|
||||
@@ -1214,7 +1215,7 @@ async fn points_to_polyline(_: impl Ctx, mut points: List<Vector>, #[default(tru
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector), properties("offset_path_properties"))]
|
||||
async fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: StrokeJoin, #[default(4.)] miter_limit: f64) -> List<Vector> {
|
||||
fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: StrokeJoin, #[default(4.)] miter_limit: f64) -> List<Vector> {
|
||||
content
|
||||
.into_iter()
|
||||
.map(|mut row| {
|
||||
@@ -1258,7 +1259,7 @@ async fn offset_path(_: impl Ctx, content: List<Vector>, distance: f64, join: St
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn solidify_stroke<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
fn solidify_stroke<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
// TODO: Make this node support stroke align, which it currently ignores
|
||||
|
||||
let graphic_list = content.into_graphic_list();
|
||||
@@ -1366,7 +1367,7 @@ async fn solidify_stroke<T: IntoGraphicList>(_: impl Ctx, #[implementations(List
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
content
|
||||
.into_iter()
|
||||
.flat_map(|row| {
|
||||
@@ -1397,7 +1398,7 @@ async fn separate_subpaths(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
|
||||
/// Determines if the subpath at the given index (across all vector element subpaths) is closed, meaning its ends are connected together forming a loop.
|
||||
#[node_macro::node(name("Path is Closed"), category("Vector: Measure"), path(core_types::vector))]
|
||||
async fn path_is_closed(
|
||||
fn path_is_closed(
|
||||
_: impl Ctx,
|
||||
/// The vector content whose subpaths are inspected.
|
||||
content: List<Vector>,
|
||||
@@ -1412,25 +1413,25 @@ async fn path_is_closed(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
|
||||
async fn map_points(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: List<Vector>, mapped: impl Node<Context<'static>, Output = DVec2>) -> List<Vector> {
|
||||
fn map_points(ctx: impl Ctx + DeriveCtx, content: List<Vector>, mapped: impl Node<Context<'_>, Output = DVec2>) -> Result<List<Vector>, Interrupt> {
|
||||
let spilled = ctx.index_head();
|
||||
let mut content = content;
|
||||
let mut index = 0;
|
||||
|
||||
for vector in content.iter_element_values_mut() {
|
||||
for (_, position) in vector.point_domain.positions_mut() {
|
||||
let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(*position);
|
||||
let scoped = ctx.push_position(*position);
|
||||
*position = mapped.eval(&scoped.ctx().promoted(&spilled, index))?;
|
||||
index += 1;
|
||||
|
||||
*position = mapped.eval(owned_ctx.into_context()).await;
|
||||
}
|
||||
}
|
||||
|
||||
content
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
// TODO: Rename to "Combine Paths" and make this happen per-element instead of flattening every element into a single path. The migration for this should then become a Flatten Vector -> Combine Paths pair of nodes.
|
||||
#[node_macro::node(category("Vector"), path(graphene_core::vector))]
|
||||
pub async fn flatten_path<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
pub fn flatten_path<T: IntoGraphicList>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
let graphic_list = content.into_graphic_list();
|
||||
let flattened = graphic_list.clone().into_flattened_list::<Vector>();
|
||||
|
||||
@@ -1486,7 +1487,7 @@ pub async fn flatten_path<T: IntoGraphicList>(_: impl Ctx, #[implementations(Lis
|
||||
|
||||
/// Convert vector geometry into a polyline composed of evenly spaced points.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector), properties("sample_polyline_properties"), memoize)]
|
||||
async fn sample_polyline(
|
||||
fn sample_polyline(
|
||||
_: impl Ctx,
|
||||
content: List<Vector>,
|
||||
spacing: PointSpacingType,
|
||||
@@ -1572,7 +1573,7 @@ async fn sample_polyline(
|
||||
|
||||
/// Simplifies vector paths by reducing the number of curve segments while preserving the overall shape within the given tolerance.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn simplify(
|
||||
fn simplify(
|
||||
_: impl Ctx,
|
||||
/// The vector paths to simplify.
|
||||
content: List<Vector>,
|
||||
@@ -1616,7 +1617,7 @@ async fn simplify(
|
||||
|
||||
/// Decimates vector paths into polylines by sampling any curves into line segments, then removing points that don't significantly contribute to the shape using the Ramer-Douglas-Peucker algorithm.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn decimate(
|
||||
fn decimate(
|
||||
_: impl Ctx,
|
||||
/// The vector paths to decimate.
|
||||
content: List<Vector>,
|
||||
@@ -1744,7 +1745,7 @@ async fn decimate(
|
||||
///
|
||||
/// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(graphene_core::vector))]
|
||||
async fn cut_path(
|
||||
fn cut_path(
|
||||
_: impl Ctx,
|
||||
/// The path to insert a cut into.
|
||||
mut content: List<Vector>,
|
||||
@@ -1795,7 +1796,7 @@ async fn cut_path(
|
||||
|
||||
/// Cuts path segments into separate disconnected pieces where each is a distinct subpath.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn cut_segments(_: impl Ctx, mut content: List<Vector>) -> List<Vector> {
|
||||
fn cut_segments(_: impl Ctx, mut content: List<Vector>) -> List<Vector> {
|
||||
// Iterate through every segment and make a copy of each of its endpoints, then reassign each segment's endpoints to its own unique point copy
|
||||
for vector in content.iter_element_values_mut() {
|
||||
let points_count = vector.point_domain.ids().len();
|
||||
@@ -1854,7 +1855,7 @@ async fn cut_segments(_: impl Ctx, mut content: List<Vector>) -> List<Vector> {
|
||||
///
|
||||
/// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it.
|
||||
#[node_macro::node(name("Position on Path"), category("Vector: Measure"), path(graphene_core::vector))]
|
||||
async fn position_on_path(
|
||||
fn position_on_path(
|
||||
_: impl Ctx,
|
||||
/// The path to traverse.
|
||||
content: List<Vector>,
|
||||
@@ -1892,7 +1893,7 @@ async fn position_on_path(
|
||||
///
|
||||
/// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it.
|
||||
#[node_macro::node(name("Tangent on Path"), category("Vector: Measure"), path(graphene_core::vector))]
|
||||
async fn tangent_on_path(
|
||||
fn tangent_on_path(
|
||||
_: impl Ctx,
|
||||
/// The path to traverse.
|
||||
content: List<Vector>,
|
||||
@@ -1940,7 +1941,7 @@ async fn tangent_on_path(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector), memoize)]
|
||||
async fn scatter_points(
|
||||
fn scatter_points(
|
||||
_: impl Ctx,
|
||||
content: List<Vector>,
|
||||
#[unit(" px")]
|
||||
@@ -1990,7 +1991,7 @@ async fn scatter_points(
|
||||
}
|
||||
|
||||
#[node_macro::node(name("Spline"), category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn spline(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
fn spline(_: impl Ctx, content: List<Vector>) -> List<Vector> {
|
||||
content
|
||||
.into_iter()
|
||||
.filter_map(|mut row| {
|
||||
@@ -2090,7 +2091,7 @@ fn apply_point_deltas(element: &mut Vector, deltas: &[DVec2], transform: DAffine
|
||||
|
||||
/// Perturbs the positions of anchor points in vector geometry by random amounts and directions.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn jitter_points(
|
||||
fn jitter_points(
|
||||
_: impl Ctx,
|
||||
/// The vector geometry with points to be jittered.
|
||||
content: List<Vector>,
|
||||
@@ -2140,7 +2141,7 @@ async fn jitter_points(
|
||||
/// Displaces anchor points along their normal direction (perpendicular to the path) by a set distance.
|
||||
/// 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))]
|
||||
async fn offset_points(
|
||||
fn offset_points(
|
||||
_: impl Ctx,
|
||||
/// The vector geometry with points to be offset.
|
||||
content: List<Vector>,
|
||||
@@ -2177,7 +2178,7 @@ async fn offset_points(
|
||||
///
|
||||
/// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn morph<I: IntoGraphicList>(
|
||||
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>)]
|
||||
@@ -3124,19 +3125,19 @@ fn point_inside(_: impl Ctx, source: List<Vector>, point: DVec2) -> bool {
|
||||
// TODO: Return u32, u64, or usize instead of f64 after #1621 is resolved and has allowed us to implement automatic type conversion in the node graph for nodes with generic type inputs.
|
||||
// TODO: (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))]
|
||||
async fn count_elements(_: impl Ctx, content: ListDyn) -> f64 {
|
||||
fn count_elements(_: impl Ctx, content: ListDyn) -> f64 {
|
||||
content.len() as f64
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), path(graphene_core::vector))]
|
||||
async fn count_points(_: impl Ctx, content: List<Vector>) -> f64 {
|
||||
fn count_points(_: impl Ctx, content: List<Vector>) -> f64 {
|
||||
content.iter_element_values().map(|vector| vector.point_domain.positions().len() as f64).sum()
|
||||
}
|
||||
|
||||
/// 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))]
|
||||
async fn index_points(
|
||||
fn index_points(
|
||||
_: impl Ctx,
|
||||
/// The vector element or elements containing the anchor points to be retrieved.
|
||||
content: List<Vector>,
|
||||
@@ -3170,7 +3171,7 @@ async fn index_points(
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
|
||||
async fn path_length(_: impl Ctx, source: List<Vector>) -> f64 {
|
||||
fn path_length(_: impl Ctx, source: List<Vector>) -> f64 {
|
||||
(0..source.len())
|
||||
.map(|index| {
|
||||
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
@@ -3189,26 +3190,24 @@ async fn path_length(_: impl Ctx, source: List<Vector>) -> f64 {
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
|
||||
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;
|
||||
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))?;
|
||||
|
||||
(0..vector.len())
|
||||
Ok((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))]
|
||||
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;
|
||||
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))?;
|
||||
|
||||
if vector.is_empty() {
|
||||
return DVec2::ZERO;
|
||||
return Ok(DVec2::ZERO);
|
||||
}
|
||||
|
||||
// All subpath centroid positions added together as if they were vectors from the origin.
|
||||
@@ -3234,7 +3233,7 @@ async fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<
|
||||
}
|
||||
|
||||
if sum > 0. {
|
||||
centroid / sum
|
||||
Ok(centroid / sum)
|
||||
}
|
||||
// Without a summed denominator, return the average of all positions instead
|
||||
else {
|
||||
@@ -3255,7 +3254,7 @@ async fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<
|
||||
.inspect(|_| count += 1)
|
||||
.sum::<DVec2>();
|
||||
|
||||
if count != 0 { summed_positions / (count as f64) } else { DVec2::ZERO }
|
||||
if count != 0 { Ok(summed_positions / (count as f64)) } else { Ok(DVec2::ZERO) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,882 +0,0 @@
|
||||
# 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.
|
||||
Reference in new issue
Block a user