mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
562e6602eb | ||
|
|
8fb18012cf | ||
|
|
2b3161773f | ||
|
|
167d733f02 | ||
|
|
ee499be31f | ||
|
|
d385f3c69b | ||
|
|
e372f78b7e | ||
|
|
8686b2c891 | ||
|
|
e3aa32bc83 | ||
|
|
77d439ec35 | ||
|
|
c30054579f | ||
|
|
81a319430b | ||
|
|
1fb6fcb447 | ||
|
|
32d244e700 | ||
|
|
0877f9d50e | ||
|
|
14c1dd0397 | ||
|
|
daf7b3e7b9 | ||
|
|
bdf53070f2 | ||
|
|
0d0ec96709 | ||
|
|
6feaf4ec9d | ||
|
|
5541769dc5 | ||
|
|
1fccb112cb |
No files matched your search
Generated
-4
@@ -4880,15 +4880,11 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-core",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"tokio",
|
||||
"vector-nodes",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
|
||||
@@ -246,10 +246,10 @@ fn test_nested_network_flattening() {
|
||||
#[test]
|
||||
fn test_metadata_preservation() {
|
||||
// Create a network with nodes that have non-default metadata
|
||||
let context_features = ContextDependencies {
|
||||
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
|
||||
..Default::default()
|
||||
};
|
||||
let context_features = ContextDependencies::new(
|
||||
core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
|
||||
core_types::context::ContextFeatures::empty(),
|
||||
);
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
|
||||
@@ -95,34 +95,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Append the hidden runtime and source-id inputs to async-source protonodes saved before their injection.
|
||||
/// Runs after the identifier replacement pass, so it matches only current identifier spellings.
|
||||
pub fn migrate_async_source_inputs(&mut self) {
|
||||
const PRE_INJECTION_ARITIES: [(&str, usize); 5] = [
|
||||
("graphene_std::platform_application_io::GetRequestNode", 4),
|
||||
("graphene_std::platform_application_io::PostRequestNode", 5),
|
||||
("graphene_std::platform_application_io::LoadResourceNode", 2),
|
||||
("graphene_std::platform_application_io::RasterizeNode", 3),
|
||||
("graphene_std::platform_application_io::ResourceNode", 2),
|
||||
];
|
||||
fix_network(self.document_network_mut());
|
||||
fn fix_network(network: &mut NodeNetwork) {
|
||||
for node in network.nodes.values_mut() {
|
||||
if let Some(network) = node.implementation.get_network_mut() {
|
||||
fix_network(network);
|
||||
}
|
||||
if let DocumentNodeImplementation::ProtoNode(protonode) = &node.implementation
|
||||
&& let Some(base) = protonode.as_str().split('<').next()
|
||||
&& let Some((_, arity)) = PRE_INJECTION_ARITIES.iter().find(|(identifier, _)| *identifier == base)
|
||||
&& node.inputs.len() == *arity
|
||||
{
|
||||
node.inputs.push(NodeInput::scope("graphene_std::runtime::RuntimeNode"));
|
||||
node.inputs.push(NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Public immutable getters for the network interface
|
||||
|
||||
@@ -1148,8 +1148,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
document.network_interface.migrate_async_source_inputs();
|
||||
|
||||
// The "Brush" wrapper network was replaced with the `brush` proto node directly. Convert old `Network("Brush")` instances to the proto node, forwarding all 3 inputs (Background, Trace, Cache) one-to-one.
|
||||
// This must run as a pre-pass before the recursive iteration below: replacing the outer Brush's network impl orphans its child paths, and the recursive iteration would log errors for those stale paths.
|
||||
let brush_layers: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
|
||||
@@ -17,7 +17,7 @@ use graphene_std::ops::ConvertAsync;
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
|
||||
use graphene_std::raster_types::Raster;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
|
||||
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner};
|
||||
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
|
||||
use graphene_std::transform::RenderQuality;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
@@ -142,8 +142,14 @@ impl Default for TokioSpawner {
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Spawner for TokioSpawner {
|
||||
fn spawn(&self, task: SourceFuture) {
|
||||
self.0.as_ref().expect("runtime lives until drop").spawn(task);
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
let runtime = self.0.as_ref().expect("runtime lives until drop");
|
||||
let _guard = runtime.enter();
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
runtime.spawn(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,8 +169,12 @@ pub struct WasmSpawner;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
impl Spawner for WasmSpawner {
|
||||
fn spawn(&self, task: SourceFuture) {
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,6 +227,11 @@ impl NodeRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn take_dirty(&self) -> bool {
|
||||
self.executor.take_dirty()
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) -> Option<Texture> {
|
||||
let mut preferences = None;
|
||||
let mut graph = None;
|
||||
|
||||
@@ -53,6 +53,27 @@ impl EditorTestUtils {
|
||||
}
|
||||
runtime.run().await;
|
||||
|
||||
// An async source reports `Pending` on the evaluation that starts it and marks the runtime dirty once
|
||||
// it completes, so the value only reaches the render on a follow-up evaluation. The superseded response's
|
||||
// `Pending` error is ignored, but its messages carry the incremental resolved-types delta and must be
|
||||
// dispatched, or the editor's type map desyncs permanently.
|
||||
while runtime.take_dirty() {
|
||||
let mut superseded_messages = VecDeque::new();
|
||||
let _ = editor.poll_node_graph_evaluation(&mut superseded_messages);
|
||||
for message in superseded_messages {
|
||||
editor.handle_message(message);
|
||||
}
|
||||
|
||||
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).unwrap();
|
||||
|
||||
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
|
||||
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
|
||||
}
|
||||
runtime.run().await;
|
||||
}
|
||||
|
||||
let mut messages = VecDeque::new();
|
||||
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
|
||||
return Err(format!("Graph should render\n\n{e}"));
|
||||
|
||||
@@ -1008,7 +1008,7 @@ impl NodeNetwork {
|
||||
DocumentNodeMetadata::SourceId => {
|
||||
let source_id = Self::source_id_for_path(path);
|
||||
if let Some(context_features) = context_features.as_deref_mut() {
|
||||
core_types::context::merge_sorted_sources(&mut context_features.sources, &[source_id]);
|
||||
context_features.add_sources(&[source_id]);
|
||||
}
|
||||
(TaggedValue::U64(source_id).into(), false)
|
||||
}
|
||||
|
||||
@@ -295,7 +295,7 @@ impl ProtoNetwork {
|
||||
}
|
||||
|
||||
pub fn source_ids(&self) -> Vec<SourceId> {
|
||||
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources.iter().copied()).collect()
|
||||
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources().iter().copied()).collect()
|
||||
}
|
||||
|
||||
/// Inserts context nullification nodes to optimize caching.
|
||||
@@ -374,10 +374,10 @@ impl ProtoNetwork {
|
||||
let mut combined_deps = ContextModification::default();
|
||||
let node_index = id.0 as usize;
|
||||
|
||||
let context_features = self.nodes[node_index].1.context_features.clone();
|
||||
let own_deps = ContextModification {
|
||||
features: context_features.extract,
|
||||
sources: context_features.sources.clone(),
|
||||
let (extract, inject, own_deps) = {
|
||||
let dependencies = &self.nodes[node_index].1.context_features;
|
||||
let own_deps = ContextModification::from_sources(dependencies.extract, dependencies.sources());
|
||||
(dependencies.extract, dependencies.inject, own_deps)
|
||||
};
|
||||
|
||||
let mut inputs = match &self.nodes[node_index].1.construction_args {
|
||||
@@ -397,7 +397,7 @@ impl ProtoNetwork {
|
||||
let mut new_deps = combined_deps.clone();
|
||||
|
||||
// Remove requirements which this node provides
|
||||
new_deps &= !context_features.inject;
|
||||
new_deps &= !inject;
|
||||
// Add requirements we have
|
||||
new_deps |= own_deps;
|
||||
|
||||
@@ -415,7 +415,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 = context_features.inject.difference(context_features.extract);
|
||||
let net_injections = inject.difference(extract);
|
||||
|
||||
// Which dependencies still need to be met after this node?
|
||||
let remaining_deps_from_children = combined_deps.features.difference(net_injections);
|
||||
@@ -1033,7 +1033,7 @@ mod test {
|
||||
let value::TaggedValue::ContextModification(modification) = &**value else {
|
||||
panic!("filter payload must be a context modification")
|
||||
};
|
||||
(*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources.clone())
|
||||
(*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources().to_vec())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1099,7 +1099,7 @@ mod test {
|
||||
identifier: ProtoNodeIdentifier::with_owned_string(name.to_string()),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]),
|
||||
context_features: ContextDependencies { sources, ..Default::default() },
|
||||
context_features: ContextDependencies::from_sources(&sources),
|
||||
..Default::default()
|
||||
};
|
||||
ProtoNetwork {
|
||||
|
||||
@@ -22,7 +22,7 @@ fn execute_until_final(executor: &DynamicExecutor, render_config: RenderConfig,
|
||||
GPoll::Final(value) => return Ok(value),
|
||||
GPoll::Fallback(boxed) => {
|
||||
let (value, error) = *boxed;
|
||||
log::error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||
log::warn!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
|
||||
return Ok(value);
|
||||
}
|
||||
GPoll::Partial(_) | GPoll::Pending => {
|
||||
|
||||
@@ -13,7 +13,7 @@ use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::load_network;
|
||||
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
|
||||
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner};
|
||||
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::error::Error;
|
||||
@@ -31,14 +31,20 @@ impl NodeGraphUpdateSender for UpdateLogger {
|
||||
struct TokioSpawner(Option<tokio::runtime::Runtime>);
|
||||
|
||||
impl TokioSpawner {
|
||||
fn new() -> Self {
|
||||
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
|
||||
fn new() -> Result<Self, std::io::Error> {
|
||||
Ok(Self(Some(tokio::runtime::Runtime::new()?)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Spawner for TokioSpawner {
|
||||
fn spawn(&self, task: SourceFuture) {
|
||||
self.0.as_ref().expect("runtime lives until drop").spawn(task);
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
let runtime = self.0.as_ref().expect("runtime lives until drop");
|
||||
let _guard = runtime.enter();
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
runtime.spawn(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,7 +208,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let preferences = EditorPreferences {
|
||||
max_render_region_size: EditorPreferences::default().max_render_region_size,
|
||||
};
|
||||
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()) as Box<DynSpawner>));
|
||||
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()?) as Box<DynSpawner>));
|
||||
let (completion_sender, completion_receiver) = std::sync::mpsc::channel();
|
||||
graph_runtime.set_notifier(Arc::new(move || {
|
||||
let _ = completion_sender.send(());
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use criterion::BenchmarkGroup;
|
||||
use criterion::measurement::Measurement;
|
||||
use futures::executor::block_on;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::{DEMO_ART, compile, load_from_name};
|
||||
use graphene_std::application_io::EditorApi;
|
||||
@@ -14,10 +13,12 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
let executor = block_on(DynamicExecutor::new(proto_network.clone())).unwrap();
|
||||
let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
|
||||
(executor, proto_network)
|
||||
}
|
||||
|
||||
// Some benches in this module's include set drive the demos themselves.
|
||||
#[allow(dead_code)]
|
||||
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
|
||||
where
|
||||
F: Fn(&str, &mut BenchmarkGroup<M>),
|
||||
|
||||
@@ -2,6 +2,7 @@ mod benchmark_util;
|
||||
|
||||
use benchmark_util::{bench_for_each_demo, setup_network};
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
|
||||
fn subsequent_evaluations(c: &mut Criterion) {
|
||||
@@ -9,9 +10,7 @@ fn subsequent_evaluations(c: &mut Criterion) {
|
||||
let context = RenderConfig::default();
|
||||
bench_for_each_demo(&mut group, |name, g| {
|
||||
let (executor, _) = setup_network(name);
|
||||
g.bench_function(name, |b| {
|
||||
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap())
|
||||
});
|
||||
g.bench_function(name, |b| b.iter(|| Executor::execute(&&executor, std::hint::black_box(context)).unwrap()));
|
||||
});
|
||||
group.finish();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod benchmark_util;
|
||||
|
||||
use benchmark_util::setup_network;
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
use gungraun::prelude::*;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -11,7 +12,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
|
||||
|
||||
// Warm up the cache by running once
|
||||
let context = RenderConfig::default();
|
||||
let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context));
|
||||
let _ = Executor::execute(&&executor, context);
|
||||
|
||||
executor
|
||||
}
|
||||
@@ -20,7 +21,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
|
||||
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
|
||||
let context = RenderConfig::default();
|
||||
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
|
||||
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
|
||||
@@ -9,14 +9,11 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
let network = load_from_name(name);
|
||||
let proto_network = compile(network);
|
||||
let empty = ProtoNetwork::default();
|
||||
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
||||
|
||||
c.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
|| (executor.clone(), proto_network.clone()),
|
||||
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|
||||
|| (DynamicExecutor::new(ProtoNetwork::default()).unwrap(), proto_network.clone()),
|
||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
@@ -33,10 +30,10 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
let network = load_from_name(name);
|
||||
let proto_network = compile(network);
|
||||
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(proto_network)).unwrap();
|
||||
let executor = DynamicExecutor::new(proto_network).unwrap();
|
||||
let footprint = Footprint::default();
|
||||
|
||||
c.bench_function(name, |b| b.iter(|| futures::executor::block_on((&executor).execute(footprint))));
|
||||
c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
|
||||
}
|
||||
fn run_once_demo(c: &mut Criterion) {
|
||||
let mut g = c.benchmark_group("Run Once no render");
|
||||
|
||||
@@ -2,6 +2,7 @@ mod benchmark_util;
|
||||
|
||||
use benchmark_util::{bench_for_each_demo, setup_network};
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
|
||||
fn run_once(c: &mut Criterion) {
|
||||
@@ -11,7 +12,7 @@ fn run_once(c: &mut Criterion) {
|
||||
g.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
|| setup_network(name),
|
||||
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap(),
|
||||
|(executor, _)| Executor::execute(&&executor, std::hint::black_box(context)).unwrap(),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod benchmark_util;
|
||||
|
||||
use benchmark_util::setup_network;
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io;
|
||||
use gungraun::prelude::*;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -15,7 +16,7 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
|
||||
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
|
||||
let context = application_io::RenderConfig::default();
|
||||
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
|
||||
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
|
||||
@@ -13,10 +13,10 @@ fn update_executor(c: &mut Criterion) {
|
||||
|| {
|
||||
let (_, proto_network) = setup_network(name);
|
||||
let empty = ProtoNetwork::default();
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
||||
let executor = DynamicExecutor::new(empty).unwrap();
|
||||
(executor, proto_network)
|
||||
},
|
||||
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
|
||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::hint::black_box;
|
||||
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let (_, proto_network) = setup_network(name);
|
||||
let empty = ProtoNetwork::default();
|
||||
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
|
||||
let executor = DynamicExecutor::new(empty).unwrap();
|
||||
(executor, proto_network)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
|
||||
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
|
||||
let (mut executor, network) = setup;
|
||||
let _ = black_box(futures::executor::block_on(executor.update(black_box(network))));
|
||||
let _ = black_box(executor.update(black_box(network)));
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
|
||||
@@ -17,6 +17,13 @@ use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const ARENA_CAPACITY: usize = 1 << 20;
|
||||
|
||||
fn new_arena() -> Arena {
|
||||
Arena::new(ARENA_CAPACITY).unwrap_or_else(|| {
|
||||
log::error!("arena generations exhausted; continuing without frame caching");
|
||||
Arena::parked()
|
||||
})
|
||||
}
|
||||
|
||||
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
|
||||
pub struct DynamicExecutor {
|
||||
output: NodeId,
|
||||
@@ -42,7 +49,7 @@ impl Default for DynamicExecutor {
|
||||
tree: Default::default(),
|
||||
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
||||
orphaned_nodes: HashSet::new(),
|
||||
arena: Mutex::new(Arena::new(ARENA_CAPACITY)),
|
||||
arena: Mutex::new(new_arena()),
|
||||
runtime: noop_runtime(),
|
||||
live_sources: Vec::new(),
|
||||
}
|
||||
@@ -78,7 +85,7 @@ impl DynamicExecutor {
|
||||
output,
|
||||
typing_context,
|
||||
orphaned_nodes: HashSet::new(),
|
||||
arena: Mutex::new(Arena::new(ARENA_CAPACITY)),
|
||||
arena: Mutex::new(new_arena()),
|
||||
runtime,
|
||||
live_sources: sources,
|
||||
})
|
||||
@@ -475,12 +482,14 @@ mod test {
|
||||
struct InertSpawner;
|
||||
|
||||
impl Spawner for InertSpawner {
|
||||
fn spawn(&self, _task: SourceFuture) {}
|
||||
fn spawn(&self, _task: SourceFuture) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_root_builds_the_bare_root_with_the_call_argument_as_vararg_0() {
|
||||
let mut arena = Arena::new(64);
|
||||
let mut arena = Arena::new(64).unwrap();
|
||||
let runtime = GraphRuntime::new(InertSpawner);
|
||||
let argument = 21.5f64;
|
||||
let result = eval_root(&mut arena, &runtime, &argument, |ctx| {
|
||||
@@ -492,7 +501,7 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn eval_root_resets_the_arena_at_eval_start() {
|
||||
let mut arena = Arena::new(64);
|
||||
let mut arena = Arena::new(64).unwrap();
|
||||
let runtime = GraphRuntime::new(InertSpawner);
|
||||
let cell = ArenaCell::new();
|
||||
eval_root(&mut arena, &runtime, &(), |ctx| {
|
||||
@@ -509,7 +518,7 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn a_panicking_eval_reports_the_error_and_resets_the_arena() {
|
||||
let mut arena = Arena::new(64);
|
||||
let mut arena = Arena::new(64).unwrap();
|
||||
let runtime = GraphRuntime::new(InertSpawner);
|
||||
let cell = ArenaCell::new();
|
||||
let result: GPoll<()> = eval_root(&mut arena, &runtime, &(), |ctx| {
|
||||
@@ -530,7 +539,7 @@ mod test {
|
||||
tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
|
||||
let _node = tree.get(NodeId(0)).unwrap();
|
||||
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
@@ -189,11 +189,16 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
// Context nullification
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => std::sync::Arc<PlatformEditorApi>, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RuntimeHandle, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => SourceId, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderOutput, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeDyn, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Option<DAffine2>, Context => graphene_std::ContextModification]),
|
||||
#[cfg(target_family = "wasm")]
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => CanvasHandle, Context => graphene_std::ContextModification]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => std::sync::Arc<PlatformEditorApi>, Context => graphene_std::ContextModification]),
|
||||
@@ -204,6 +209,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
// MEMO NODES
|
||||
// ==========
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ()]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RuntimeHandle]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => SourceId]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => bool]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Artboard>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Graphic>]),
|
||||
@@ -276,6 +283,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
|
||||
|
||||
@@ -30,22 +30,14 @@ 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 {
|
||||
extract: ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::INDEX,
|
||||
..Default::default()
|
||||
},
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, 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 {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::empty(),
|
||||
..Default::default()
|
||||
},
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
@@ -56,22 +48,14 @@ 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 {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::VARARGS,
|
||||
..Default::default()
|
||||
},
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, 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 {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
..Default::default()
|
||||
},
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
@@ -81,23 +65,18 @@ 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 {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::empty(),
|
||||
..Default::default()
|
||||
},
|
||||
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
|
||||
extract: ContextFeatures::INDEX | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
..Default::default()
|
||||
},
|
||||
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
|
||||
context_features: graphene_std::ContextDependencies::new(
|
||||
ContextFeatures::INDEX | ContextFeatures::VARARGS,
|
||||
ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
|
||||
@@ -4,6 +4,15 @@ 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,
|
||||
@@ -24,22 +33,66 @@ 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.
|
||||
// ordered by the Release/Acquire pair on the published handle word. Payloads are
|
||||
// `Send + Sync` by the bound on every allocating method.
|
||||
unsafe impl Sync for Arena {}
|
||||
unsafe impl Send for Arena {}
|
||||
|
||||
impl std::panic::UnwindSafe for Arena {}
|
||||
impl std::panic::RefUnwindSafe for Arena {}
|
||||
|
||||
/// Shared by all arenas, so a foreign handle misses like a stale one.
|
||||
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
static LIVE_ARENAS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// `None` past [`GENERATION_MASK`], where a reissued generation would let an ancient
|
||||
/// handle upgrade against a current arena. Recovered by `reset_generation_counter`.
|
||||
fn next_generation() -> Option<u64> {
|
||||
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
(generation <= GENERATION_MASK).then_some(generation)
|
||||
}
|
||||
|
||||
/// Rewinds the shared generation counter so previously issued values are reused.
|
||||
/// Returns `false` without rewinding when an [`Arena`] is live at the time of the
|
||||
/// check, which is a debugging aid rather than a guarantee.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No [`ArenaWeak`] minted before this call may be upgraded afterwards. Dropping
|
||||
/// every [`Arena`] is not sufficient, since nodes also hold handles in
|
||||
/// [`ArenaCell`]s; those nodes must be dropped too. No arena may be constructed
|
||||
/// concurrently either, since the live check and the rewind are separate steps.
|
||||
pub unsafe fn reset_generation_counter() -> bool {
|
||||
if LIVE_ARENAS.load(Ordering::Acquire) != 0 {
|
||||
return false;
|
||||
}
|
||||
NEXT_GENERATION.store(1, Ordering::Release);
|
||||
true
|
||||
}
|
||||
|
||||
impl Arena {
|
||||
pub fn new(capacity: usize) -> Self {
|
||||
pub fn new(capacity: usize) -> Option<Self> {
|
||||
let generation = next_generation()?;
|
||||
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
|
||||
Self {
|
||||
// Starts at 1 so the null handle word (0) can never upgrade.
|
||||
generation: AtomicU64::new(1),
|
||||
LIVE_ARENAS.fetch_add(1, Ordering::Release);
|
||||
Some(Self {
|
||||
generation: AtomicU64::new(generation),
|
||||
offset: AtomicUsize::new(0),
|
||||
buf,
|
||||
drops: Mutex::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
|
||||
/// An arena that refuses every allocation and resolves no handle, so a caller that
|
||||
/// cannot fail can degrade instead of propagating exhaustion.
|
||||
pub fn parked() -> Self {
|
||||
LIVE_ARENAS.fetch_add(1, Ordering::Release);
|
||||
Self {
|
||||
generation: AtomicU64::new(PARKED_GENERATION),
|
||||
offset: AtomicUsize::new(0),
|
||||
buf: Box::new([]),
|
||||
drops: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,8 +121,11 @@ impl Arena {
|
||||
Some(start)
|
||||
}
|
||||
|
||||
pub fn alloc<T>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
|
||||
pub fn alloc<T: Send + Sync>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
|
||||
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
|
||||
// Built before the write so an unencodable offset drops `value` here
|
||||
// rather than stranding it in the arena without drop glue.
|
||||
let weak = ArenaWeak::new(self.generation(), offset)?;
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
|
||||
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
|
||||
unsafe { ptr.write(value) };
|
||||
@@ -80,10 +136,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 }, ArenaWeak::new(self.generation(), offset)))
|
||||
Some((unsafe { &*ptr }, weak))
|
||||
}
|
||||
|
||||
pub fn alloc_slice_copy<T: Copy>(&self, src: &[T]) -> Option<&[T]> {
|
||||
pub fn alloc_slice_copy<T: Copy + Send + Sync>(&self, src: &[T]) -> Option<&[T]> {
|
||||
let buf = self.alloc_scratch::<T>(src.len())?;
|
||||
for (slot, &value) in buf.iter_mut().zip(src) {
|
||||
slot.write(value);
|
||||
@@ -95,7 +151,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>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
|
||||
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
|
||||
let size = size_of::<T>().checked_mul(len)?;
|
||||
let offset = self.reserve(size, align_of::<T>())?;
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
|
||||
@@ -104,21 +160,28 @@ impl Arena {
|
||||
Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
/// `false` once generations are exhausted, parking the arena on [`PARKED_GENERATION`]
|
||||
/// where every handle misses and further allocation is refused.
|
||||
pub fn reset(&mut self) -> bool {
|
||||
let base = self.base();
|
||||
for entry in self.drops.get_mut().unwrap().drain(..) {
|
||||
let entries = std::mem::take(self.drops.get_mut().unwrap());
|
||||
self.generation.store(PARKED_GENERATION, Ordering::Release);
|
||||
for entry in entries.into_iter().rev() {
|
||||
// SAFETY: registered at alloc time; insert-only means the region was
|
||||
// never overwritten within this generation.
|
||||
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
|
||||
}
|
||||
*self.offset.get_mut() = 0;
|
||||
self.generation.fetch_add(1, Ordering::Release);
|
||||
let Some(generation) = next_generation() else { return false };
|
||||
self.generation.store(generation, Ordering::Release);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Arena {
|
||||
fn drop(&mut self) {
|
||||
self.reset();
|
||||
LIVE_ARENAS.fetch_sub(1, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,20 +200,22 @@ impl<T> Copy for ArenaWeak<T> {}
|
||||
impl<T> ArenaWeak<T> {
|
||||
pub const NULL: Self = ArenaWeak { word: 0, _marker: PhantomData };
|
||||
|
||||
fn new(generation: u64, offset: usize) -> Self {
|
||||
debug_assert!(offset < u32::MAX as usize);
|
||||
Self {
|
||||
word: ((generation & 0xFFFF_FFFF) << 32) | offset as u64,
|
||||
/// `None` once either field leaves its encodable range, so an oversized or parked
|
||||
/// arena refuses to hand out a handle rather than truncating it to a live address.
|
||||
fn new(generation: u64, offset: usize) -> Option<Self> {
|
||||
let offset = u64::try_from(offset).ok().filter(|offset| *offset <= OFFSET_MASK)?;
|
||||
(generation <= GENERATION_MASK).then_some(Self {
|
||||
word: (generation << OFFSET_BITS) | offset,
|
||||
_marker: PhantomData,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn upgrade(self, arena: &Arena) -> Option<&T> {
|
||||
let generation = self.word >> 32;
|
||||
if generation != arena.generation() & 0xFFFF_FFFF {
|
||||
let generation = self.word >> OFFSET_BITS;
|
||||
if generation != arena.generation() {
|
||||
return None;
|
||||
}
|
||||
let offset = (self.word & 0xFFFF_FFFF) as usize;
|
||||
let offset = (self.word & OFFSET_MASK) as usize;
|
||||
// SAFETY: same generation means the entry was fully written before its
|
||||
// word was published (Release) and cannot move or be overwritten within
|
||||
// a generation (insert-only); the Acquire load that produced this word
|
||||
@@ -209,11 +274,13 @@ 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 mut arena = Arena::new(1024);
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let cell = ArenaCell::new();
|
||||
let (value, weak) = arena.alloc(41u32).unwrap();
|
||||
assert_eq!(*value, 41);
|
||||
@@ -225,7 +292,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn capacity_survives_reset() {
|
||||
let mut arena = Arena::new(64 + align_of::<u32>() - 1);
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut arena = Arena::new(64 + align_of::<u32>() - 1).unwrap();
|
||||
for _ in 0..10 {
|
||||
for _ in 0..16 {
|
||||
assert!(arena.alloc(0u32).is_some());
|
||||
@@ -237,6 +305,7 @@ 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>();
|
||||
|
||||
@@ -247,7 +316,7 @@ mod tests {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024);
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
let cell = ArenaCell::new();
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
let (_, weak) = arena.alloc(Probe("pre-panic".into())).unwrap();
|
||||
@@ -262,8 +331,84 @@ 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 {
|
||||
@@ -271,7 +416,7 @@ mod tests {
|
||||
DROPS.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024);
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
arena.alloc(Probe("owns heap".into())).unwrap();
|
||||
arena.alloc(Probe("me too".into())).unwrap();
|
||||
assert_eq!(DROPS.load(Ordering::Relaxed), 0);
|
||||
|
||||
@@ -199,17 +199,63 @@ impl ContextFeatures {
|
||||
pub struct ContextDependencies {
|
||||
pub extract: ContextFeatures,
|
||||
pub inject: ContextFeatures,
|
||||
/// Must stay sorted.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub sources: Vec<SourceId>,
|
||||
#[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,
|
||||
/// Must stay sorted.
|
||||
pub sources: Vec<SourceId>,
|
||||
#[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 {
|
||||
@@ -239,10 +285,12 @@ impl core::ops::BitAndAssign<ContextFeatures> for ContextModification {
|
||||
|
||||
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(),
|
||||
@@ -254,12 +302,12 @@ impl ContextModification {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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]) {
|
||||
for &id in other {
|
||||
if let Err(insert_at) = sources.binary_search(&id) {
|
||||
sources.insert(insert_at, id);
|
||||
}
|
||||
}
|
||||
sources.extend_from_slice(other);
|
||||
sources.sort_unstable();
|
||||
sources.dedup();
|
||||
}
|
||||
|
||||
impl From<&[ContextFeature]> for ContextDependencies {
|
||||
@@ -734,8 +782,8 @@ pub struct CtxSnapshot {
|
||||
real_time: Option<f64>,
|
||||
animation_time: Option<f64>,
|
||||
pointer_position: Option<DVec2>,
|
||||
index: Vec<usize>,
|
||||
positions: Vec<DVec2>,
|
||||
index: Option<Vec<usize>>,
|
||||
positions: Option<Vec<DVec2>>,
|
||||
varargs: Vec<Vec<OwnedSlot>>,
|
||||
generations: Vec<(SourceId, u64)>,
|
||||
}
|
||||
@@ -750,8 +798,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()).unwrap_or_default(),
|
||||
positions: ctx.try_position().map(|positions| positions.collect()).unwrap_or_default(),
|
||||
index: ctx.try_index().map(|levels| levels.collect()),
|
||||
positions: ctx.try_position().map(|positions| positions.collect()),
|
||||
varargs: std::iter::successors(ctx.varargs_head(), |link| link.outer)
|
||||
.map(|link| link.args.iter().map(|slot| slot.clone_slot()).collect())
|
||||
.collect(),
|
||||
@@ -762,10 +810,6 @@ 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 {
|
||||
@@ -794,13 +838,13 @@ impl ExtractPointerPosition for CtxSnapshot {
|
||||
|
||||
impl ExtractIndex for CtxSnapshot {
|
||||
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
|
||||
Some(self.index.iter().copied())
|
||||
self.index.as_ref().map(|levels| levels.iter().copied())
|
||||
}
|
||||
}
|
||||
|
||||
impl ExtractPosition for CtxSnapshot {
|
||||
fn try_position(&self) -> Option<impl Iterator<Item = DVec2>> {
|
||||
Some(self.positions.iter().copied())
|
||||
self.positions.as_ref().map(|positions| positions.iter().copied())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1125,7 +1169,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn equal_contexts_hash_equal() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [(0, 1), (1, 3)];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let a = ContextImpl::root(&scope);
|
||||
@@ -1135,7 +1179,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn each_axis_changes_the_hash() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [(0, 1)];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1159,7 +1203,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn index_level_order_matters() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1177,7 +1221,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn axis_boundaries_are_unambiguous() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1195,7 +1239,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn retain_scopes_generation_invalidation() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let initial = [(0, 1), (1, 3)];
|
||||
let bumped_unretained = [(0, 2), (1, 3)];
|
||||
let bumped_retained = [(0, 1), (1, 4)];
|
||||
@@ -1211,7 +1255,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn excluding_keys_ignore_own_source_bumps() {
|
||||
let arena = Arena::new(64);
|
||||
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)];
|
||||
@@ -1226,7 +1270,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn unretained_scope_sees_every_bump() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let initial = [(0, 1)];
|
||||
let bumped = [(0, 2)];
|
||||
let hash_with = |generations: &[(SourceId, u64)]| {
|
||||
@@ -1238,7 +1282,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn set_index_is_visible_and_keeps_outer_levels() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1251,7 +1295,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn vararg_chain_concatenates_innermost_first() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1282,7 +1326,7 @@ mod context_impl_tests {
|
||||
|
||||
#[test]
|
||||
fn snapshot_captures_vararg_levels() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -1325,9 +1369,35 @@ 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);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
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::MaybeUninit;
|
||||
use std::mem::{ManuallyDrop, MaybeUninit};
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
|
||||
|
||||
const SLOT_EMPTY: u8 = 0;
|
||||
@@ -17,6 +17,13 @@ struct FrameSlot<T> {
|
||||
value: UnsafeCell<MaybeUninit<T>>,
|
||||
}
|
||||
|
||||
// SAFETY: the key CAS reserves a slot for one writer, and the Release store of its
|
||||
// state publishes the value to every Acquire load in `lookup`, so concurrent access
|
||||
// is ordered. Sharing the table hands out `&T` and drops `T` on whichever thread
|
||||
// drops the table, which is what the `Send + Sync` bounds cover.
|
||||
unsafe impl<T: Send + Sync, const CAP: usize> Sync for FrameTable<T, CAP> {}
|
||||
unsafe impl<T: Send, const CAP: usize> Send for FrameTable<T, CAP> {}
|
||||
|
||||
pub enum Lookup<'t, T> {
|
||||
Hit(Finality, &'t T),
|
||||
Vacant(VacantSlot<'t, T>),
|
||||
@@ -45,8 +52,8 @@ impl<T, const CAP: usize> FrameTable<T, CAP> {
|
||||
}
|
||||
|
||||
pub fn lookup(&self, hash: u64) -> Lookup<'_, T> {
|
||||
// Keys are forced odd so the empty sentinel (0) can never collide.
|
||||
let key = hash | 1;
|
||||
// Only hash 0 is remapped, so distinct hashes stay distinct keys.
|
||||
let key = if hash == 0 { 1 } else { hash };
|
||||
for probe in 0..CAP {
|
||||
let slot = &self.slots[(key as usize).wrapping_add(probe) % CAP];
|
||||
let stored = slot.key.load(Ordering::Acquire);
|
||||
@@ -81,18 +88,27 @@ 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 { &*(*self.slot.value.get()).write(value) };
|
||||
let lent = unsafe { &*(*slot.value.get()).write(value) };
|
||||
let state = match finality {
|
||||
Finality::AllFinal => SLOT_FINAL,
|
||||
Finality::Partial => SLOT_PARTIAL,
|
||||
};
|
||||
self.slot.state.store(state, Ordering::Release);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -123,6 +139,33 @@ 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();
|
||||
|
||||
@@ -7,13 +7,48 @@ use std::ops::Range;
|
||||
#[derive(Debug)]
|
||||
pub enum BatchStatus<'a, T> {
|
||||
Lent(&'a [T], Finality),
|
||||
Filled(&'a mut [T], Finality),
|
||||
Filled(FilledBatch<'a, T>, Finality),
|
||||
Pending,
|
||||
Error(GraphError),
|
||||
NeedBuffer,
|
||||
InvalidRange,
|
||||
}
|
||||
|
||||
/// Owns the initialized prefix of a caller-supplied scratch buffer, dropping every
|
||||
/// lane unless [`FilledBatch::into_values`] hands the obligation back to the caller.
|
||||
#[derive(Debug)]
|
||||
pub struct FilledBatch<'a, T> {
|
||||
values: &'a mut [T],
|
||||
}
|
||||
|
||||
impl<'a, T> FilledBatch<'a, T> {
|
||||
/// # Safety
|
||||
///
|
||||
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
|
||||
pub unsafe fn new(scratch: &'a mut [MaybeUninit<T>], len: usize) -> Self {
|
||||
Self {
|
||||
values: unsafe { assume_init_prefix_mut(scratch, len) },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn values(&self) -> &[T] {
|
||||
self.values
|
||||
}
|
||||
|
||||
pub fn into_values(self) -> &'a mut [T] {
|
||||
let mut guard = std::mem::ManuallyDrop::new(self);
|
||||
std::mem::take(&mut guard.values)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for FilledBatch<'_, T> {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: every lane was initialized when the guard was built and none has
|
||||
// been moved out, since `into_values` consumes the guard instead.
|
||||
unsafe { std::ptr::drop_in_place(self.values as *mut [T]) }
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
///
|
||||
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
|
||||
@@ -43,7 +78,7 @@ pub trait Node<Input> {
|
||||
let Some(scratch) = scratch else {
|
||||
return BatchStatus::NeedBuffer;
|
||||
};
|
||||
let Some(len) = range.end.checked_sub(range.start).map(|len| len as usize) else {
|
||||
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
|
||||
return BatchStatus::InvalidRange;
|
||||
};
|
||||
if scratch.len() < len {
|
||||
@@ -76,7 +111,7 @@ pub trait Node<Input> {
|
||||
}
|
||||
}
|
||||
// SAFETY: all `len` lanes were written by the loop above.
|
||||
BatchStatus::Filled(unsafe { assume_init_prefix_mut(scratch, len) }, finality)
|
||||
BatchStatus::Filled(unsafe { FilledBatch::new(scratch, len) }, finality)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +129,10 @@ 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,
|
||||
@@ -116,6 +155,10 @@ 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,
|
||||
@@ -138,6 +181,10 @@ 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,
|
||||
@@ -239,28 +286,6 @@ impl<'a, N> LazyInput<'a, N> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Input, N> Node<Input> for LazyInput<'a, N>
|
||||
where
|
||||
N: Node<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::*;
|
||||
@@ -295,10 +320,37 @@ mod tests {
|
||||
let BatchStatus::Filled(lanes, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
assert_eq!(lanes, &[4, 6, 8, 10]);
|
||||
assert_eq!(lanes.values(), &[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 };
|
||||
@@ -330,7 +382,7 @@ mod tests {
|
||||
let BatchStatus::Filled(lanes, finality) = status else {
|
||||
panic!("expected filled, got {status:?}");
|
||||
};
|
||||
assert_eq!(lanes, &[0, 1, 2, 3]);
|
||||
assert_eq!(lanes.values(), &[0, 1, 2, 3]);
|
||||
assert_eq!(finality, Finality::Partial);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,8 @@ pub struct NodeMetadata {
|
||||
pub context_features: Vec<ContextFeature>,
|
||||
pub memoize: bool,
|
||||
pub inject_scope: bool,
|
||||
/// The macro appended its hidden `_runtime` and `_source` fields as the last two entries of `fields`.
|
||||
pub async_source_fields: bool,
|
||||
}
|
||||
|
||||
// Translation struct between macro and definition
|
||||
@@ -333,7 +335,7 @@ mod tests {
|
||||
|
||||
type ErasedSplitEdge = dyn for<'c> Node<ContextImpl<'c>, Output = SplitBorrow<'c>> + Send + Sync;
|
||||
|
||||
let arena = Arena::new(4096);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -391,7 +393,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(1024);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -443,7 +445,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(1024);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -493,7 +495,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn duplicated_edges_share_one_instance_and_outlive_each_other() {
|
||||
let arena = Arena::new(1024);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
@@ -16,7 +16,8 @@ pub type DynRuntime = dyn Runtime + Send + Sync;
|
||||
pub type DynRuntime = dyn Runtime;
|
||||
|
||||
pub trait Runtime {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture);
|
||||
/// Returns true when the future completed during the call, so its result is already observable.
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -40,7 +41,14 @@ impl graphene_hash::CacheHash for RuntimeHandle {
|
||||
}
|
||||
|
||||
pub trait Spawner {
|
||||
fn spawn(&self, task: SourceFuture);
|
||||
/// Returns true when the task completed during the call, so its result is already observable.
|
||||
fn spawn(&self, task: SourceFuture) -> bool;
|
||||
}
|
||||
|
||||
/// Polls `task` once with a no-op waker, returning true if it completed.
|
||||
pub fn poll_once(task: &mut SourceFuture) -> bool {
|
||||
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
|
||||
task.as_mut().poll(&mut context).is_ready()
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
@@ -54,17 +62,21 @@ pub type DynNotifier = dyn Fn() + Send + Sync;
|
||||
pub type DynNotifier = dyn Fn();
|
||||
|
||||
impl<S: Spawner + ?Sized> Spawner for Box<S> {
|
||||
fn spawn(&self, task: SourceFuture) {
|
||||
fn spawn(&self, task: SourceFuture) -> bool {
|
||||
(**self).spawn(task)
|
||||
}
|
||||
}
|
||||
|
||||
/// Dropped tasks never complete.
|
||||
/// Polls each task once inline. Tasks that are not immediately ready 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");
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
log::warn!("async source is not immediately ready and no host spawner is wired; the task is dropped");
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,21 +141,26 @@ impl<S> GraphRuntime<S> {
|
||||
}
|
||||
|
||||
impl<S: Spawner> Runtime for GraphRuntime<S> {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) {
|
||||
fn spawn(&self, source: SourceId, mut future: SourceFuture) -> bool {
|
||||
let generations = Arc::clone(&self.generations);
|
||||
let dirty = Arc::clone(&self.dirty);
|
||||
let notifier = Arc::clone(&self.notifier);
|
||||
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();
|
||||
let mut first = true;
|
||||
self.spawner.spawn(Box::pin(std::future::poll_fn(move |task_context| {
|
||||
let poll = future.as_mut().poll(task_context);
|
||||
if poll.is_ready() && !first {
|
||||
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(generation) = generations.get_mut(&source) {
|
||||
*generation += 1;
|
||||
dirty.store(true, Ordering::Release);
|
||||
drop(generations);
|
||||
let notifier = Arc::clone(¬ifier.lock().unwrap_or_else(PoisonError::into_inner));
|
||||
notifier();
|
||||
}
|
||||
}
|
||||
}));
|
||||
first = false;
|
||||
poll
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,8 +181,9 @@ mod tests {
|
||||
}
|
||||
|
||||
impl Runtime for MockRuntime {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) {
|
||||
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool {
|
||||
self.futures.lock().unwrap().push((source, future));
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,11 +207,34 @@ mod tests {
|
||||
}
|
||||
|
||||
impl Spawner for CollectSpawner {
|
||||
fn spawn(&self, task: SourceFuture) {
|
||||
fn spawn(&self, mut task: SourceFuture) -> bool {
|
||||
if poll_once(&mut task) {
|
||||
return true;
|
||||
}
|
||||
self.tasks.lock().unwrap().push(task);
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
struct YieldOnce(bool);
|
||||
|
||||
impl Future for YieldOnce {
|
||||
type Output = ();
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, task_context: &mut std::task::Context<'_>) -> std::task::Poll<()> {
|
||||
if self.0 {
|
||||
return std::task::Poll::Ready(());
|
||||
}
|
||||
self.0 = true;
|
||||
task_context.waker().wake_by_ref();
|
||||
std::task::Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
fn yield_once() -> YieldOnce {
|
||||
YieldOnce(false)
|
||||
}
|
||||
|
||||
impl CollectSpawner {
|
||||
fn drain(&self) -> usize {
|
||||
let tasks = std::mem::take(&mut *self.tasks.lock().unwrap());
|
||||
@@ -281,7 +322,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn async_source_spawns_once_and_lands_via_the_slot() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -301,7 +342,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn async_source_reports_the_placeholder_while_in_flight() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -316,7 +357,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn no_partial_maps_the_placeholder_frame_to_pending() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -331,7 +372,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn prologue_runs_sync_and_spawns_once() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -350,7 +391,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn prologue_interrupt_defers_the_spawn() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -369,7 +410,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn async_kernels_read_captured_varargs() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -390,7 +431,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn async_kernels_read_the_captured_context_snapshot() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -410,7 +451,7 @@ mod tests {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
|
||||
Runtime::spawn(&runtime, 7, Box::pin(async {}));
|
||||
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
|
||||
assert_eq!(runtime.snapshot(), vec![(7, 0)], "no bump before the future completes");
|
||||
assert!(!runtime.take_dirty());
|
||||
|
||||
@@ -431,7 +472,7 @@ mod tests {
|
||||
observed.store(dirty_at_notify.load(Ordering::Acquire), Ordering::Relaxed);
|
||||
}));
|
||||
|
||||
Runtime::spawn(&runtime, 7, Box::pin(async {}));
|
||||
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
assert!(observed_dirty.load(Ordering::Relaxed), "the notifier must observe the dirty flag already set");
|
||||
}
|
||||
@@ -444,7 +485,7 @@ mod tests {
|
||||
let flag = Arc::clone(¬ified);
|
||||
runtime.set_notifier(Arc::new(move || flag.store(true, Ordering::Relaxed)));
|
||||
|
||||
Runtime::spawn(&runtime, 7, Box::pin(async {}));
|
||||
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
|
||||
runtime.retain_sources(&[]);
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
assert!(!notified.load(Ordering::Relaxed));
|
||||
@@ -455,7 +496,7 @@ mod tests {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
|
||||
Runtime::spawn(&runtime, 7, Box::pin(async {}));
|
||||
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
|
||||
runtime.retain_sources(&[]);
|
||||
assert_eq!(runtime.spawner().drain(), 1);
|
||||
|
||||
@@ -467,7 +508,7 @@ mod tests {
|
||||
fn retain_sources_preserves_live_generations() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
Runtime::spawn(&runtime, 7, Box::pin(async {}));
|
||||
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
|
||||
runtime.spawner().drain();
|
||||
|
||||
runtime.retain_sources(&[7, 9]);
|
||||
@@ -479,12 +520,45 @@ mod tests {
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn epilogue_double(_: impl Ctx, value: f64) -> f64 {
|
||||
yield_once().await;
|
||||
value * 2.
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
async fn inline_double(_: impl Ctx, value: f64) -> f64 {
|
||||
value * 2.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_immediately_ready_task_completes_inline_without_invalidating() {
|
||||
let runtime = GraphRuntime::new(CollectSpawner::default());
|
||||
runtime.retain_sources(&[7]);
|
||||
|
||||
assert!(Runtime::spawn(&runtime, 7, Box::pin(async {})));
|
||||
assert_eq!(runtime.spawner().drain(), 0);
|
||||
assert_eq!(runtime.snapshot(), vec![(7, 0)], "inline completion must not bump the generation");
|
||||
assert!(!runtime.take_dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_immediately_ready_kernel_returns_final_on_the_first_eval() {
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
|
||||
runtime.retain_sources(&[13]);
|
||||
let graph = InlineDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(13u64));
|
||||
|
||||
let snapshot = runtime.snapshot();
|
||||
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
|
||||
assert!(!runtime.take_dirty());
|
||||
assert_eq!(runtime.snapshot(), vec![(13, 0)]);
|
||||
assert_eq!(runtime.spawner().drain(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_slot_lands_through_the_runtime_while_downstream_keys_invalidate() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
|
||||
runtime.retain_sources(&[11]);
|
||||
let graph = EpilogueDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(11u64));
|
||||
|
||||
@@ -367,7 +367,7 @@ pub fn simplify_identifier_name(ty: &str) -> String {
|
||||
/// Converts a Rust-internal type name to its user-facing form.
|
||||
pub fn make_type_user_readable(ty: &str) -> String {
|
||||
let ty = ty
|
||||
.replace("Option<Arc<OwnedContextImpl>>", "Context")
|
||||
.replace("ContextImpl", "Context")
|
||||
.replace("Raster<CPU>", "Raster")
|
||||
.replace("Raster<GPU>", "Raster")
|
||||
.replace("DAffine2", "Transform")
|
||||
|
||||
@@ -5,7 +5,7 @@ use core_types::shaders::buffer_struct::BufferStruct;
|
||||
use raster_types::{GPU, Raster};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use wgpu::util::{BufferInitDescriptor, DeviceExt};
|
||||
use wgpu::{
|
||||
BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingType, Buffer, BufferBinding, BufferBindingType, BufferUsages, ColorTargetState, Face,
|
||||
@@ -34,7 +34,7 @@ impl PerPixelAdjustShaderRuntime {
|
||||
|
||||
impl ShaderRuntime {
|
||||
pub fn run_per_pixel_adjust<T: BufferStruct>(&self, shaders: &Shaders<'_>, textures: List<Raster<GPU>>, args: Option<&T>) -> List<Raster<GPU>> {
|
||||
let mut cache = self.per_pixel_adjust.pipeline_cache.lock().unwrap();
|
||||
let mut cache = self.per_pixel_adjust.pipeline_cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let pipeline = cache
|
||||
.entry(shaders.fragment_shader_name.to_owned())
|
||||
.or_insert_with(|| PerPixelAdjustGraphicsPipeline::new(&self.context, shaders));
|
||||
|
||||
@@ -18,7 +18,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
fn_generics,
|
||||
input,
|
||||
output_type,
|
||||
is_async,
|
||||
fields,
|
||||
description,
|
||||
..
|
||||
@@ -113,7 +112,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
quote! { pub(super) #name: #r#gen }
|
||||
});
|
||||
|
||||
let async_source = *is_async || is_source_kernel(output_type);
|
||||
let async_source = parsed.injects_async_source_fields();
|
||||
let slot_value_type = 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>>>>> })
|
||||
@@ -356,6 +355,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
context_features: vec![#(ContextFeature::#context_features,)*],
|
||||
memoize: #memoize_flag,
|
||||
inject_scope: #inject_scope_flag,
|
||||
async_source_fields: #async_source,
|
||||
fields: vec![
|
||||
#(
|
||||
FieldMetadata {
|
||||
@@ -932,6 +932,22 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
},
|
||||
_ => quote!(#core_types::gpoll::GPoll::Final(__future.await)),
|
||||
};
|
||||
let spawn_tail = |completion: TokenStream2, fallback: TokenStream2| {
|
||||
quote! {
|
||||
self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(__key, None);
|
||||
let __slot = std::sync::Arc::clone(&self.slot);
|
||||
if _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));
|
||||
})) {
|
||||
let __entries = self.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(Some(__value)) = __entries.get(&__key) {
|
||||
return __cell.merge(__value.clone());
|
||||
}
|
||||
}
|
||||
#fallback
|
||||
}
|
||||
};
|
||||
let eval_tail = match (async_fn, future_kernel) {
|
||||
(false, false) => lift,
|
||||
(true, _) => {
|
||||
@@ -942,17 +958,12 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
.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);
|
||||
let tail = spawn_tail(completion, inflight.clone());
|
||||
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
|
||||
#tail
|
||||
}
|
||||
}
|
||||
(false, true) => {
|
||||
@@ -977,38 +988,20 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
_ => unreachable!("guarded by future_kernel"),
|
||||
};
|
||||
let completion = future_completion(&payload);
|
||||
let tail = spawn_tail(completion, spawn_return);
|
||||
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
|
||||
#tail
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let entries = entries_tokens(parsed, &struct_name, &data_field_generic_idents, ®ular_fields);
|
||||
let cfg = crate::shader_nodes::modify_cfg(&parsed.attributes);
|
||||
let entries_reexport = match entries.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! {
|
||||
#entries_reexport
|
||||
|
||||
#cfg
|
||||
#[automatically_derived]
|
||||
impl<#(#generics,)* #(#node_generics,)*> #core_types::node::Node<#ctx_ident> for #mod_name::#struct_name<#(#struct_type_params,)*>
|
||||
|
||||
@@ -998,7 +998,7 @@ 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::codegen::is_source_kernel(&parsed_node.output_type) {
|
||||
if parsed_node.injects_async_source_fields() {
|
||||
let core_types = crate_ident.gcore()?.clone();
|
||||
parsed_node.inject_async_source_fields(&core_types);
|
||||
}
|
||||
@@ -1030,6 +1030,10 @@ impl ParsedNodeFn {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn injects_async_source_fields(&self) -> bool {
|
||||
self.is_async || crate::codegen::is_source_kernel(&self.output_type)
|
||||
}
|
||||
|
||||
pub fn inject_async_source_fields(&mut self, core_types: &TokenStream2) {
|
||||
let hidden_field = |name: &str, ty: Type, value_source: ParsedValueSource| ParsedField {
|
||||
pat_ident: PatIdent {
|
||||
|
||||
@@ -231,9 +231,9 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
description: "".to_string(),
|
||||
widget_override: Default::default(),
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty: parse_quote!(std::sync::Arc<WgpuExecutor>),
|
||||
ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
|
||||
exposed: true,
|
||||
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorArcNode"))),
|
||||
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode"))),
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
|
||||
@@ -24,6 +24,15 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
fn validate_async_source(parsed: &ParsedNodeFn) {
|
||||
let snapshot_ctx = matches!(&parsed.input.ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "CtxSnapshot"));
|
||||
let future_kernel = crate::codegen::is_source_kernel(&parsed.output_type);
|
||||
if let Some(placeholder) = &parsed.attributes.placeholder
|
||||
&& !parsed.is_async
|
||||
&& !future_kernel
|
||||
{
|
||||
emit_error!(
|
||||
placeholder.span(),
|
||||
"`placeholder` applies only to async and source kernels; a synchronous node never reports `Partial`, so the stand-in is unused"
|
||||
);
|
||||
}
|
||||
if parsed.is_async && future_kernel {
|
||||
emit_error!(
|
||||
parsed.output_type.span(),
|
||||
|
||||
@@ -46,6 +46,6 @@ fn context_modification<T>(
|
||||
/// The parts of the context to keep when evaluating the input value. All other parts are nullified.
|
||||
modification: ContextModification,
|
||||
) -> GPoll<T> {
|
||||
let scope = ctx.scope().nullified(modification.features, Some(&modification.sources));
|
||||
let scope = ctx.scope().nullified(modification.features, Some(modification.sources()));
|
||||
value.eval(&ctx.nullified(modification.features, &scope))
|
||||
}
|
||||
@@ -41,7 +41,11 @@ where
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), skip_impl, extent(frame_memo_extent))]
|
||||
fn frame_memo<'e, T: Clone + 'static>(ctx: impl Ctx + CacheHash + ExtractArena<'e>, #[data] cell: ArenaCell<FrameTable<T, 32>>, content: impl Node<Context<'_>, Output = T>) -> GPoll<&'e T> {
|
||||
fn frame_memo<'e, T: Clone + 'static + Send + Sync>(
|
||||
ctx: impl Ctx + CacheHash + ExtractArena<'e>,
|
||||
#[data] cell: ArenaCell<FrameTable<T, 32>>,
|
||||
content: impl Node<Context<'_>, Output = T>,
|
||||
) -> GPoll<&'e T> {
|
||||
let arena = ctx.arena();
|
||||
let table = match cell.load(arena) {
|
||||
Some(table) => table,
|
||||
@@ -70,13 +74,13 @@ fn frame_memo<'e, T: Clone + 'static>(ctx: impl Ctx + CacheHash + ExtractArena<'
|
||||
|
||||
fn frame_memo_extent<C, T, NodeContent>(node: &FrameMemoNode<T, NodeContent>, ctx: &C) -> GPoll<Extent>
|
||||
where
|
||||
T: Clone + 'static,
|
||||
T: Clone + 'static + Send + Sync,
|
||||
NodeContent: Node<C, Output = T>,
|
||||
{
|
||||
node.content.extent(ctx)
|
||||
}
|
||||
|
||||
pub fn park<T>(arena: &Arena, result: GPoll<T>) -> GPoll<&T> {
|
||||
pub fn park<T: Send + Sync>(arena: &Arena, result: GPoll<T>) -> GPoll<&T> {
|
||||
match result {
|
||||
GPoll::Final(value) => match arena.alloc(value) {
|
||||
Some((parked, _)) => GPoll::Final(parked),
|
||||
@@ -126,8 +130,6 @@ fn serialize_monitor<T: Clone + 'static + Send + Sync>(io: &MonitorValue<T>) ->
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::SourceId;
|
||||
use core_types::Type;
|
||||
use core_types::concrete;
|
||||
use core_types::context::{ContextImpl, EvalScope};
|
||||
use core_types::registry::{EdgeHandle, ErasedLendNode, ErasedNode};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
@@ -168,7 +170,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn monitor_serialize_exposes_the_io_record_through_the_edge() {
|
||||
let arena = Arena::new(1024);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -186,7 +188,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn memoize_caches_across_evals() {
|
||||
let arena = Arena::new(1024);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -199,7 +201,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn memo_invalidates_on_generation_bump() {
|
||||
let arena = Arena::new(1024);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let source: SourceId = 7;
|
||||
let before = [(source, 1)];
|
||||
let after = [(source, 2)];
|
||||
@@ -215,7 +217,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn memo_replays_partiality_on_hit() {
|
||||
let arena = Arena::new(1024);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -228,7 +230,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn memoized_edges_stack_and_rewire() {
|
||||
let arena = Arena::new(1024);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
@@ -243,7 +245,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn frame_memo_turns_an_owned_edge_into_a_lending_edge() {
|
||||
let arena = Arena::new(4096);
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
@@ -221,7 +221,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn create_context_builds_the_render_context_from_the_root_vararg() {
|
||||
let arena = Arena::new(256);
|
||||
let arena = Arena::new(256).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
|
||||
@@ -989,8 +989,6 @@ fn normalize(_: impl Ctx, vector: DVec2) -> DVec2 {
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use core_types::Node;
|
||||
use core_types::generic::FnNode;
|
||||
|
||||
#[test]
|
||||
pub fn dot_product_function() {
|
||||
@@ -1029,12 +1027,6 @@ mod test {
|
||||
assert_eq!(result, 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn foo() {
|
||||
let fnn = FnNode::new(|(a, b)| (b, a));
|
||||
assert_eq!(fnn.eval((1u32, 2u32)), (2, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn add_vectors() {
|
||||
assert_eq!(super::add(&(), DVec2::ONE, DVec2::ONE), DVec2::ONE * 2.);
|
||||
@@ -1098,7 +1090,7 @@ mod graphene_test {
|
||||
|
||||
#[test]
|
||||
fn generated_add_evaluates_through_the_node_path() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
@@ -1108,7 +1100,7 @@ mod graphene_test {
|
||||
|
||||
#[test]
|
||||
fn generated_add_batches_through_the_erased_edge() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
@@ -1118,13 +1110,13 @@ mod graphene_test {
|
||||
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!(lanes.values(), &[12.0, 13.0, 14.0, 15.0]);
|
||||
assert_eq!(finality, Finality::AllFinal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_wire_constructor_resolves_and_wires() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
@@ -1148,16 +1140,16 @@ mod graphene_test {
|
||||
|
||||
#[test]
|
||||
fn generic_add_registers_one_entry_per_implementation() {
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let entries = add_entries();
|
||||
assert_eq!(entries.len(), 6);
|
||||
assert_eq!(entries[0].io.inputs, vec![core_types::concrete!(f64), core_types::concrete!(f64)]);
|
||||
assert_eq!(entries[0].io.output, core_types::concrete!(f64));
|
||||
assert_eq!(entries[0].io.return_value, core_types::concrete!(f64));
|
||||
assert_eq!(entries[3].io.inputs, vec![core_types::concrete!(DVec2), core_types::concrete!(DVec2)]);
|
||||
assert_eq!(entries[3].io.output, core_types::concrete!(DVec2));
|
||||
assert_eq!(entries[3].io.return_value, core_types::concrete!(DVec2));
|
||||
|
||||
let augend = EdgeHandle::new(Arc::new(SourceNode(1.5f64)) as Arc<ErasedNode<f64>>);
|
||||
let addend = EdgeHandle::new(Arc::new(SourceNode(2.5f64)) as Arc<ErasedNode<f64>>);
|
||||
@@ -1182,7 +1174,7 @@ mod graphene_test {
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
@@ -1217,7 +1209,7 @@ mod graphene_test {
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
@@ -1240,7 +1232,7 @@ mod graphene_test {
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
@@ -1260,7 +1252,7 @@ mod graphene_test {
|
||||
}
|
||||
}
|
||||
|
||||
let arena = Arena::new(64);
|
||||
let arena = Arena::new(64).unwrap();
|
||||
let scope = scope_fixture(&arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
|
||||
@@ -201,8 +201,8 @@ mod test {
|
||||
use raster_types::Image;
|
||||
use raster_types::Raster;
|
||||
|
||||
#[tokio::test]
|
||||
async fn color_overlay_multiply() {
|
||||
#[test]
|
||||
fn color_overlay_multiply() {
|
||||
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
|
||||
let image = Image::new(1, 1, image_color);
|
||||
|
||||
@@ -212,7 +212,7 @@ mod test {
|
||||
// 100% of the output should come from the multiplied value
|
||||
let opacity = 100.;
|
||||
|
||||
let result = super::color_overlay((), List::new_from_element(Raster::new_cpu(image.clone())), overlay_color, BlendMode::Multiply, opacity);
|
||||
let result = super::color_overlay(&(), List::new_from_element(Raster::new_cpu(image.clone())), overlay_color, BlendMode::Multiply, opacity);
|
||||
let result = result.element(0).unwrap().clone();
|
||||
|
||||
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
|
||||
|
||||
@@ -68,7 +68,7 @@ mod test {
|
||||
#[test]
|
||||
fn test_image_color_palette() {
|
||||
let result = image_color_palette(
|
||||
(),
|
||||
&(),
|
||||
List::new_from_element(Raster::new_cpu(Image {
|
||||
width: 100,
|
||||
height: 100,
|
||||
@@ -77,6 +77,6 @@ mod test {
|
||||
})),
|
||||
1,
|
||||
);
|
||||
assert_eq!(futures::executor::block_on(result), List::new_from_element(Color::from_rgbaf32(0., 0., 0., 1.).unwrap()));
|
||||
assert_eq!(result, List::new_from_element(Color::from_rgbaf32(0., 0., 0., 1.).unwrap()));
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,3 @@ log = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
graphene-core = { workspace = true }
|
||||
vector-nodes = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt"] }
|
||||
kurbo = { workspace = true }
|
||||
@@ -179,3 +179,145 @@ fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
|
||||
|
||||
Ok(result_list)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, EvalScope, ExtractIndex, ExtractPosition};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::Item;
|
||||
use core_types::node::{LazyInput, Node, StatusCell};
|
||||
use vector_types::subpath::Subpath;
|
||||
|
||||
const TEST_POSITION: &str = "test-position";
|
||||
|
||||
struct ValueNode<T>(T);
|
||||
|
||||
impl<T: Clone, Input> Node<Input> for ValueNode<T> {
|
||||
type Output = T;
|
||||
|
||||
fn eval(&self, _input: &Input) -> GPoll<T> {
|
||||
GPoll::Final(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns one default `Vector` whose transform records the innermost context index in its x translation.
|
||||
struct IndexProbe;
|
||||
|
||||
impl<Input: ExtractIndex> Node<Input> for IndexProbe {
|
||||
type Output = List<Vector>;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<List<Vector>> {
|
||||
let index = input.try_index().and_then(|mut levels| levels.next()).expect("repeat must push an index level");
|
||||
let mut list = List::new();
|
||||
list.push(Item::new_from_element(Vector::default()).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(index as f64, 0.))));
|
||||
GPoll::Final(list)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns one default `Vector` recording the innermost context position under `TEST_POSITION`.
|
||||
struct PositionProbe;
|
||||
|
||||
impl<Input: ExtractPosition> Node<Input> for PositionProbe {
|
||||
type Output = List<Vector>;
|
||||
|
||||
fn eval(&self, input: &Input) -> GPoll<List<Vector>> {
|
||||
let position = input.try_position().and_then(|mut positions| positions.next()).expect("repeat_on_points must push a position level");
|
||||
let mut list = List::new();
|
||||
list.push(Item::new_from_element(Vector::default()).with_attribute(TEST_POSITION, DAffine2::from_translation(position)));
|
||||
GPoll::Final(list)
|
||||
}
|
||||
}
|
||||
|
||||
fn single_default_vector() -> List<Vector> {
|
||||
List::new_from_element(Vector::default())
|
||||
}
|
||||
|
||||
fn row_translations(list: &List<Vector>, key: &str) -> Vec<DVec2> {
|
||||
(0..list.len()).map(|index| list.attribute_cloned_or_default::<DAffine2>(key, index).translation).collect()
|
||||
}
|
||||
|
||||
macro_rules! test_ctx {
|
||||
($ctx:ident, $cell:ident) => {
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let $ctx = ContextImpl::root(&scope);
|
||||
let $cell = StatusCell::default();
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_pushes_the_iteration_index_in_order() {
|
||||
test_ctx!(ctx, cell);
|
||||
|
||||
let x_translations = |values: [f64; 3]| values.map(|x| DVec2::new(x, 0.)).to_vec();
|
||||
|
||||
let forward = super::repeat(&ctx, LazyInput::new(&IndexProbe, &cell, 0), 3, false).unwrap();
|
||||
assert_eq!(row_translations(&forward, ATTR_TRANSFORM), x_translations([0., 1., 2.]));
|
||||
|
||||
let reversed = super::repeat(&ctx, LazyInput::new(&IndexProbe, &cell, 0), 3, true).unwrap();
|
||||
assert_eq!(row_translations(&reversed, ATTR_TRANSFORM), x_translations([2., 1., 0.]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_array_spaces_copies_along_the_direction() {
|
||||
test_ctx!(ctx, cell);
|
||||
let direction = DVec2::new(1.5, 0.);
|
||||
let count = 3;
|
||||
|
||||
let content = ValueNode(single_default_vector());
|
||||
let repeated = super::repeat_array(&ctx, LazyInput::new(&content, &cell, 0), direction, 0., count).unwrap();
|
||||
|
||||
assert_eq!(repeated.len(), count as usize);
|
||||
for (index, translation) in row_translations(&repeated, ATTR_TRANSFORM).into_iter().enumerate() {
|
||||
let expected = index as f64 * direction / (count - 1) as f64;
|
||||
assert!(translation.abs_diff_eq(expected, 1e-10), "copy {index}: {translation:?} != {expected:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_array_single_copy_stays_finite() {
|
||||
test_ctx!(ctx, cell);
|
||||
|
||||
let content = ValueNode(single_default_vector());
|
||||
let repeated = super::repeat_array(&ctx, LazyInput::new(&content, &cell, 0), DVec2::new(12., 10.), 45., 1).unwrap();
|
||||
|
||||
assert_eq!(repeated.len(), 1);
|
||||
let transform: DAffine2 = repeated.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
assert!(transform.abs_diff_eq(DAffine2::IDENTITY, 1e-10), "single copy must not divide by zero: {transform:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_radial_rotates_copies_around_the_center() {
|
||||
test_ctx!(ctx, cell);
|
||||
let (radius, count) = (5., 4);
|
||||
|
||||
let content = ValueNode(single_default_vector());
|
||||
let repeated = super::repeat_radial(&ctx, LazyInput::new(&content, &cell, 0), 0., radius, count).unwrap();
|
||||
|
||||
assert_eq!(repeated.len(), count as usize);
|
||||
for index in 0..count as usize {
|
||||
let transform: DAffine2 = repeated.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let expected = DAffine2::from_angle((TAU / count as f64) * index as f64) * DAffine2::from_translation(radius * DVec2::Y);
|
||||
assert!(transform.abs_diff_eq(expected, 1e-10), "copy {index}: {transform:?} != {expected:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeat_on_points_pushes_each_point_as_the_position() {
|
||||
test_ctx!(ctx, cell);
|
||||
let positions = [DVec2::new(40., 20.), DVec2::ONE, DVec2::new(-42., 9.), DVec2::new(10., 345.)];
|
||||
let points = List::new_from_element(Vector::from_subpath(Subpath::from_anchors(positions, false)));
|
||||
|
||||
let generated = super::repeat_on_points(&ctx, points.clone(), LazyInput::new(&PositionProbe, &cell, 0), false).unwrap();
|
||||
assert_eq!(row_translations(&generated, ATTR_TRANSFORM), positions.to_vec());
|
||||
assert_eq!(row_translations(&generated, TEST_POSITION), positions.to_vec());
|
||||
|
||||
let reversed = super::repeat_on_points(&ctx, points, LazyInput::new(&PositionProbe, &cell, 0), true).unwrap();
|
||||
let mut expected = positions.to_vec();
|
||||
expected.reverse();
|
||||
assert_eq!(row_translations(&reversed, ATTR_TRANSFORM), expected);
|
||||
}
|
||||
}
|
||||
@@ -411,11 +411,11 @@ mod tests {
|
||||
#[test]
|
||||
fn isometric_grid_test() {
|
||||
// Doesn't crash with weird angles
|
||||
grid((), (), GridType::Isometric, 0., 5, 5, (0., 0.).into());
|
||||
grid((), (), GridType::Isometric, 90., 5, 5, (90., 90.).into());
|
||||
grid(&(), (), GridType::Isometric, 0., 5, 5, (0., 0.).into());
|
||||
grid(&(), (), GridType::Isometric, 90., 5, 5, (90., 90.).into());
|
||||
|
||||
// Works properly
|
||||
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (30., 30.).into());
|
||||
let grid = grid(&(), (), GridType::Isometric, 10., 5, 5, (30., 30.).into());
|
||||
assert_eq!(grid.element(0).unwrap().point_domain.ids().len(), 5 * 5);
|
||||
assert_eq!(grid.element(0).unwrap().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
|
||||
for (_, bezier, _, _) in grid.element(0).unwrap().segment_bezier_iter() {
|
||||
@@ -430,7 +430,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn skew_isometric_grid_test() {
|
||||
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (40., 30.).into());
|
||||
let grid = grid(&(), (), GridType::Isometric, 10., 5, 5, (40., 30.).into());
|
||||
assert_eq!(grid.element(0).unwrap().point_domain.ids().len(), 5 * 5);
|
||||
assert_eq!(grid.element(0).unwrap().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
|
||||
for (_, bezier, _, _) in grid.element(0).unwrap().segment_bezier_iter() {
|
||||
@@ -443,7 +443,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn qr_code_test() {
|
||||
let qr = qr_code((), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
|
||||
let qr = qr_code(&(), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
|
||||
assert!(qr.element(0).unwrap().point_domain.ids().len() > 0);
|
||||
assert!(qr.element(0).unwrap().segment_domain.ids().len() > 0);
|
||||
}
|
||||
|
||||
@@ -3261,24 +3261,10 @@ fn centroid(ctx: impl Ctx + DeriveCtx, content: impl Node<Context<'_>, Output =
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use core_types::Node;
|
||||
use kurbo::{CubicBez, Ellipse, Point, Rect};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use vector_types::vector::algorithms::bezpath_algorithms::{TValue, trim_pathseg};
|
||||
use vector_types::vector::misc::pathseg_abs_diff_eq;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FutureWrapperNode<T: Clone>(T);
|
||||
|
||||
impl<'i, T: 'i + Clone + Send> Node<'i, Footprint> for FutureWrapperNode<T> {
|
||||
type Output = Pin<Box<dyn Future<Output = T> + 'i + Send>>;
|
||||
fn eval(&'i self, _input: Footprint) -> Self::Output {
|
||||
let value = self.0.clone();
|
||||
Box::pin(async move { value })
|
||||
}
|
||||
}
|
||||
|
||||
fn vector_node_from_bezpath(bezpath: BezPath) -> List<Vector> {
|
||||
List::new_from_element(Vector::from_bezpath(bezpath))
|
||||
}
|
||||
@@ -3289,9 +3275,9 @@ mod test {
|
||||
Item::new_from_element(row).with_attribute(ATTR_TRANSFORM, transform)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bounding_box() {
|
||||
let bounding_box = super::bounding_box((), vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))).await;
|
||||
#[test]
|
||||
fn bounding_box() {
|
||||
let bounding_box = super::bounding_box(&(), vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY)));
|
||||
let bounding_box = bounding_box.element(0).unwrap();
|
||||
assert_eq!(bounding_box.region_manipulator_groups().count(), 1);
|
||||
let manipulator_groups_anchors = bounding_box
|
||||
@@ -3309,7 +3295,7 @@ mod test {
|
||||
let square = Vector::from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY));
|
||||
let mut square = List::new_from_element(square);
|
||||
square.with_attribute_mut_or_default(ATTR_TRANSFORM, 0, |t: &mut DAffine2| *t *= DAffine2::from_angle(std::f64::consts::FRAC_PI_4));
|
||||
let bounding_box = BoundingBoxNode { content: FutureWrapperNode(square) }.eval(Footprint::default()).await;
|
||||
let bounding_box = super::bounding_box(&(), square);
|
||||
let bounding_box = bounding_box.element(0).unwrap();
|
||||
assert_eq!(bounding_box.region_manipulator_groups().count(), 1);
|
||||
let manipulator_groups_anchors = bounding_box
|
||||
@@ -3326,15 +3312,15 @@ mod test {
|
||||
assert_eq!(manipulator_groups_anchors[i], expected_bounding_box[i]);
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn copy_to_points() {
|
||||
#[test]
|
||||
fn copy_to_points() {
|
||||
let points = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY);
|
||||
let element = Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY);
|
||||
|
||||
let expected_points = Vector::from_bezpath(points.clone()).point_domain.positions().to_vec();
|
||||
|
||||
let copy_to_points = super::copy_to_points(Footprint::default(), vector_node_from_bezpath(points), vector_node_from_bezpath(element), 1., 1., 0., 0, 0., 0).await;
|
||||
let flatten_path = super::flatten_path(Footprint::default(), copy_to_points).await;
|
||||
let copy_to_points = super::copy_to_points(&Footprint::default(), vector_node_from_bezpath(points), vector_node_from_bezpath(element), 1., 1., 0., 0, 0., 0);
|
||||
let flatten_path = super::flatten_path(&Footprint::default(), copy_to_points);
|
||||
let flattened_copy_to_points = flatten_path.element(0).unwrap();
|
||||
|
||||
assert_eq!(flattened_copy_to_points.region_manipulator_groups().count(), expected_points.len());
|
||||
@@ -3349,35 +3335,34 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sample_polyline() {
|
||||
#[test]
|
||||
fn sample_polyline() {
|
||||
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
|
||||
let sample_polyline = super::sample_polyline(Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 30., 0, 0., 0., false).await;
|
||||
let sample_polyline = super::sample_polyline(&Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 30., 0, 0., 0., false);
|
||||
let sample_polyline = sample_polyline.element(0).unwrap();
|
||||
assert_eq!(sample_polyline.point_domain.positions().len(), 4);
|
||||
for (pos, expected) in sample_polyline.point_domain.positions().iter().zip([DVec2::X * 0., DVec2::X * 30., DVec2::X * 60., DVec2::X * 90.]) {
|
||||
assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}");
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn sample_polyline_adaptive_spacing() {
|
||||
#[test]
|
||||
fn sample_polyline_adaptive_spacing() {
|
||||
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
|
||||
let sample_polyline = super::sample_polyline(Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 18., 0, 45., 10., true).await;
|
||||
let sample_polyline = super::sample_polyline(&Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 18., 0, 45., 10., true);
|
||||
let sample_polyline = sample_polyline.element(0).unwrap();
|
||||
assert_eq!(sample_polyline.point_domain.positions().len(), 4);
|
||||
for (pos, expected) in sample_polyline.point_domain.positions().iter().zip([DVec2::X * 45., DVec2::X * 60., DVec2::X * 75., DVec2::X * 90.]) {
|
||||
assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}");
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn poisson() {
|
||||
#[test]
|
||||
fn poisson() {
|
||||
let poisson_points = super::scatter_points(
|
||||
Footprint::default(),
|
||||
&Footprint::default(),
|
||||
vector_node_from_bezpath(Ellipse::from_rect(Rect::new(-50., -50., 50., 50.)).to_path(DEFAULT_ACCURACY)),
|
||||
10. * std::f64::consts::SQRT_2,
|
||||
0,
|
||||
)
|
||||
.await;
|
||||
);
|
||||
let poisson_points = poisson_points.element(0).unwrap();
|
||||
assert!(
|
||||
(20..=40).contains(&poisson_points.point_domain.positions().len()),
|
||||
@@ -3388,33 +3373,33 @@ mod test {
|
||||
assert!(point.length() < 50. + 1., "Expected point in circle {point}")
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn path_length() {
|
||||
#[test]
|
||||
fn path_length() {
|
||||
let bezpath = Rect::new(100., 100., 201., 201.).to_path(DEFAULT_ACCURACY);
|
||||
let transform = DAffine2::from_scale(DVec2::new(2., 2.));
|
||||
let row = create_vector_item(bezpath, transform);
|
||||
let list = (0..5).map(|_| row.clone()).collect::<List<Vector>>();
|
||||
|
||||
let length = super::path_length(Footprint::default(), list).await;
|
||||
let length = super::path_length(&Footprint::default(), list);
|
||||
|
||||
// 101 (each rectangle edge length) * 4 (rectangle perimeter) * 2 (scale) * 5 (number of rows)
|
||||
assert_eq!(length, 101. * 4. * 2. * 5.);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn spline() {
|
||||
let spline = super::spline(Footprint::default(), vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY))).await;
|
||||
#[test]
|
||||
fn spline() {
|
||||
let spline = super::spline(&Footprint::default(), vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)));
|
||||
let spline = spline.element(0).unwrap();
|
||||
assert_eq!(spline.stroke_bezpath_iter().count(), 1);
|
||||
assert_eq!(spline.point_domain.positions(), &[DVec2::ZERO, DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)]);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn morph() {
|
||||
#[test]
|
||||
fn morph() {
|
||||
let mut rectangles = vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
|
||||
let mut second_rectangle = rectangles.clone_item(0).unwrap();
|
||||
*second_rectangle.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM) *= DAffine2::from_translation((-100., -100.).into());
|
||||
rectangles.push(second_rectangle);
|
||||
|
||||
let morphed = super::morph(Footprint::default(), rectangles, 0.5, false, InterpolationDistribution::default(), List::default()).await;
|
||||
let morphed = super::morph(&Footprint::default(), rectangles, 0.5, false, InterpolationDistribution::default(), List::default());
|
||||
let morphed_element = morphed.element(0).unwrap();
|
||||
// Geometry stays in local space (original rectangle coordinates)
|
||||
assert_eq!(
|
||||
@@ -3425,8 +3410,8 @@ mod test {
|
||||
assert!((morphed.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0).translation - DVec2::new(-50., -50.)).length() < 1e-3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn morph_interpolates_fill() {
|
||||
#[test]
|
||||
fn morph_interpolates_fill() {
|
||||
let rect = || {
|
||||
let mut v = Vector::default();
|
||||
v.append_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
|
||||
@@ -3443,7 +3428,7 @@ mod test {
|
||||
let mut content = List::new_from_item(item_a);
|
||||
content.push(item_b);
|
||||
|
||||
let morphed = super::morph(Footprint::default(), content, 0.5, false, InterpolationDistribution::default(), List::default()).await;
|
||||
let morphed = super::morph(&Footprint::default(), content, 0.5, false, InterpolationDistribution::default(), List::default());
|
||||
|
||||
let fill = graphic_list_at(&morphed, 0, ATTR_FILL).expect("Morph should keep the fill paint at the midpoint");
|
||||
|
||||
@@ -3470,10 +3455,10 @@ mod test {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bevel_rect() {
|
||||
#[test]
|
||||
fn bevel_rect() {
|
||||
let source = Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY);
|
||||
let beveled = super::bevel(Footprint::default(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
|
||||
let beveled = super::bevel(&Footprint::default(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
|
||||
let beveled = beveled.element(0).unwrap();
|
||||
|
||||
assert_eq!(beveled.point_domain.positions().len(), 8);
|
||||
@@ -3492,8 +3477,8 @@ mod test {
|
||||
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(0., 90.))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bevel_open_curve() {
|
||||
#[test]
|
||||
fn bevel_open_curve() {
|
||||
let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.)));
|
||||
|
||||
let mut source = BezPath::new();
|
||||
@@ -3501,7 +3486,7 @@ mod test {
|
||||
source.line_to(Point::ZERO);
|
||||
source.push(curve.as_path_el());
|
||||
|
||||
let beveled = super::bevel((), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
|
||||
let beveled = super::bevel(&(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
|
||||
let beveled = beveled.element(0).unwrap();
|
||||
|
||||
assert_eq!(beveled.point_domain.positions().len(), 4);
|
||||
@@ -3516,8 +3501,8 @@ mod test {
|
||||
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start())));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bevel_with_transform() {
|
||||
#[test]
|
||||
fn bevel_with_transform() {
|
||||
let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.)));
|
||||
|
||||
let mut source = BezPath::new();
|
||||
@@ -3530,7 +3515,7 @@ mod test {
|
||||
|
||||
vector_list.set_attribute(ATTR_TRANSFORM, 0, DAffine2::from_scale_angle_translation(DVec2::splat(10.), 1., DVec2::new(99., 77.)));
|
||||
|
||||
let beveled = super::bevel((), List::new_from_element(vector), 2_f64.sqrt() * 10.);
|
||||
let beveled = super::bevel(&(), List::new_from_element(vector), 2_f64.sqrt() * 10.);
|
||||
let beveled = beveled.element(0).unwrap();
|
||||
|
||||
assert_eq!(beveled.point_domain.positions().len(), 4);
|
||||
@@ -3545,15 +3530,15 @@ mod test {
|
||||
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start())));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bevel_too_high() {
|
||||
#[test]
|
||||
fn bevel_too_high() {
|
||||
let mut source = BezPath::new();
|
||||
source.move_to(Point::ZERO);
|
||||
source.line_to(Point::new(100., 0.));
|
||||
source.line_to(Point::new(100., 100.));
|
||||
source.line_to(Point::new(0., 100.));
|
||||
|
||||
let beveled = super::bevel(Footprint::default(), vector_node_from_bezpath(source), 999.);
|
||||
let beveled = super::bevel(&Footprint::default(), vector_node_from_bezpath(source), 999.);
|
||||
let beveled = beveled.element(0).unwrap();
|
||||
|
||||
assert_eq!(beveled.point_domain.positions().len(), 6);
|
||||
@@ -3569,15 +3554,15 @@ mod test {
|
||||
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.))));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bevel_repeated_point() {
|
||||
#[test]
|
||||
fn bevel_repeated_point() {
|
||||
let line = PathSeg::Line(Line::new(Point::ZERO, Point::new(100., 0.)));
|
||||
let point = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::ZERO, Point::ZERO, Point::new(100., 0.)));
|
||||
let curve = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::new(110., 0.), Point::new(110., 200.), Point::new(200., 0.)));
|
||||
|
||||
let subpath = BezPath::from_path_segments([line, point, curve].into_iter());
|
||||
|
||||
let beveled_list = super::bevel(Footprint::default(), vector_node_from_bezpath(subpath), 5.);
|
||||
let beveled_list = super::bevel(&Footprint::default(), vector_node_from_bezpath(subpath), 5.);
|
||||
let beveled = beveled_list.element(0).unwrap();
|
||||
|
||||
assert_eq!(beveled.point_domain.positions().len(), 6);
|
||||
|
||||
@@ -116,7 +116,13 @@ impl Preprocessor {
|
||||
for (id, metadata) in core_types::registry::NODE_METADATA.lock().unwrap().iter() {
|
||||
let id = id.clone();
|
||||
|
||||
let NodeMetadata { fields, memoize, inject_scope, .. } = metadata;
|
||||
let NodeMetadata {
|
||||
fields,
|
||||
memoize,
|
||||
inject_scope,
|
||||
async_source_fields,
|
||||
..
|
||||
} = metadata;
|
||||
let Some(implementations) = node_registry.get(&id) else { continue };
|
||||
let valid_call_args: HashSet<_> = implementations.iter().map(|entry| entry.io.call_argument.clone()).collect();
|
||||
let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
|
||||
@@ -131,16 +137,20 @@ impl Preprocessor {
|
||||
input_type = &const { generic!(D) };
|
||||
}
|
||||
|
||||
let inputs: Vec<_> = node_inputs(fields, first_node_io);
|
||||
let input_count = inputs.len();
|
||||
let network_inputs = (0..input_count).map(|i| NodeInput::node(NodeId(i as u64), 0)).collect();
|
||||
let mut inputs: Vec<_> = node_inputs(fields, first_node_io);
|
||||
let wrapper_input_count = inputs.len() - if *async_source_fields { 2 } else { 0 };
|
||||
|
||||
// The injected fields must not surface as wrapper inputs, and the `_source` reflection must sit on
|
||||
// the kernel itself so the source id lands on a node that survives flattening.
|
||||
let injected_inputs = inputs.split_off(wrapper_input_count);
|
||||
let network_inputs = (0..wrapper_input_count).map(|i| NodeInput::node(NodeId(i as u64), 0)).chain(injected_inputs).collect();
|
||||
|
||||
let passthrough_node = ops::passthrough::IDENTIFIER;
|
||||
|
||||
let mut generated_nodes = 0;
|
||||
let mut nodes: HashMap<_, _, _> = node_io_types
|
||||
.iter()
|
||||
.take(input_count)
|
||||
.take(wrapper_input_count)
|
||||
.enumerate()
|
||||
.map(|(i, inputs)| {
|
||||
(
|
||||
@@ -185,7 +195,7 @@ impl Preprocessor {
|
||||
})
|
||||
.collect();
|
||||
|
||||
if generated_nodes == 0 && !memoize && !inject_scope {
|
||||
if generated_nodes == 0 && !memoize && !inject_scope && !async_source_fields {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -199,13 +209,14 @@ impl Preprocessor {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
nodes.insert(NodeId(input_count as u64), document_node);
|
||||
let main_node_id = NodeId(wrapper_input_count as u64);
|
||||
nodes.insert(main_node_id, document_node);
|
||||
|
||||
// If memoize is requested, append a Memoize node after the main node and redirect the export through it
|
||||
let export_node_id = if *memoize {
|
||||
let memoize_node_id = NodeId(input_count as u64 + 1);
|
||||
let memoize_node_id = NodeId(wrapper_input_count as u64 + 1);
|
||||
let memoize_node = DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(input_count as u64), 0)],
|
||||
inputs: vec![NodeInput::node(main_node_id, 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::memo::memoize::IDENTIFIER.clone()),
|
||||
visible: true,
|
||||
..Default::default()
|
||||
@@ -213,7 +224,7 @@ impl Preprocessor {
|
||||
nodes.insert(memoize_node_id, memoize_node);
|
||||
memoize_node_id
|
||||
} else {
|
||||
NodeId(input_count as u64)
|
||||
main_node_id
|
||||
};
|
||||
|
||||
let node = DocumentNode {
|
||||
|
||||
Reference in new issue
Block a user