mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c403654745 | ||
|
|
6c3232ee8c | ||
|
|
30164b921e | ||
|
|
b10aa51efb | ||
|
|
5d00e45354 | ||
|
|
69c0dd140d | ||
|
|
9a8269c953 | ||
|
|
76361baaa1 | ||
|
|
f569120bf6 | ||
|
|
0df1e16233 | ||
|
|
65bb0ff838 | ||
|
|
d5a7504e3a | ||
|
|
fa65c1f8dc | ||
|
|
264d8493ef | ||
|
|
68b7c25f52 | ||
|
|
10b57c9719 | ||
|
|
b1c0b6c173 | ||
|
|
16fc449a3c | ||
|
|
411d9f64b3 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/38176c494d7cf0bde3bdf45e6a318ae6a9d89229.tar.gz
|
||||
2ae24506ff786b2b684f5d23bd326a69f5f4551855f19e4ef2b0324f9ec14e5d
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/9d0fa5caefd7d28f51b55220b405b7d76d05a991.tar.gz
|
||||
a146abe79fa20b6d96f8009279a5a3342dd01596e5eb6a43e4c1f5e1199f1d9f
|
||||
Generated
+13
@@ -2679,6 +2679,7 @@ dependencies = [
|
||||
"rendering",
|
||||
"repeat-nodes",
|
||||
"reqwest",
|
||||
"svg-convert",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
@@ -7163,6 +7164,18 @@ version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "svg-convert"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"usvg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "svgtypes"
|
||||
version = "0.16.2"
|
||||
|
||||
@@ -99,6 +99,7 @@ graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
|
||||
brush-types = { path = "node-graph/libraries/brush-types" }
|
||||
rendering = { path = "node-graph/libraries/rendering" }
|
||||
svg-convert = { path = "node-graph/libraries/svg-convert" }
|
||||
brush-nodes = { path = "node-graph/nodes/brush" }
|
||||
blending-nodes = { path = "node-graph/nodes/blending" }
|
||||
graphene-core = { path = "node-graph/nodes/gcore" }
|
||||
|
||||
Generated
BIN
Binary file not shown.
@@ -52,9 +52,11 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod branch_simulation;
|
||||
mod crdt;
|
||||
mod history_simulation;
|
||||
mod projection;
|
||||
mod round_trip;
|
||||
mod sessions;
|
||||
mod simulation;
|
||||
}
|
||||
@@ -382,7 +382,8 @@ fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, k
|
||||
if !visited.insert(current) {
|
||||
return None;
|
||||
}
|
||||
let (in_network, input) = match registry.removed_nodes.get(¤t) {
|
||||
// A placeholder knows nothing of the node's network or primary input, so what history kept decides instead
|
||||
let (in_network, input) = match registry.removed_nodes.get(¤t).filter(|tombstone| !tombstone.placeholder) {
|
||||
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
|
||||
None => known.primary.get(¤t).cloned()?,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Deterministic simulation of a document whose chains branch off inputs past the primary one, with every history
|
||||
//! operation mixed in. After every operation nothing may name a node the document no longer has.
|
||||
|
||||
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
||||
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
|
||||
|
||||
/// A slot that can name a node.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
enum Place {
|
||||
Export(u32),
|
||||
Input(NodeId, u32),
|
||||
}
|
||||
|
||||
fn place_value(registry: &Registry, place: Place) -> Option<NodeInput> {
|
||||
match place {
|
||||
Place::Input(id, index) => registry.node_instances.get(&id)?.inputs.get(index as usize).map(|slot| slot.input.clone()),
|
||||
Place::Export(index) => registry.networks.get(&ROOT_NETWORK)?.exports.get(index as usize)?.target.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_place(place: Place, input: NodeInput) -> RegistryDelta {
|
||||
match place {
|
||||
Place::Input(id, index) => RegistryDelta::ChangeNodeInput { id, index, new_input: input },
|
||||
Place::Export(index) => RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index,
|
||||
export: Some(input),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Every slot naming a node, and the node it names, in a fixed order.
|
||||
fn naming_places(registry: &Registry) -> Vec<(Place, NodeId)> {
|
||||
let mut places = Vec::new();
|
||||
for (&id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = slot.input {
|
||||
places.push((Place::Input(id, index as u32), named));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(network) = registry.networks.get(&ROOT_NETWORK) {
|
||||
for (index, slot) in network.exports.iter().enumerate() {
|
||||
if let Some(NodeInput::Node { id: named, .. }) = slot.target {
|
||||
places.push((Place::Export(index as u32), named));
|
||||
}
|
||||
}
|
||||
}
|
||||
places.sort();
|
||||
places
|
||||
}
|
||||
|
||||
/// The slot naming `node`, of which a document built this way has one.
|
||||
fn consumer_place(registry: &Registry, node: NodeId) -> Option<Place> {
|
||||
naming_places(registry).into_iter().find(|(_, named)| *named == node).map(|(place, _)| place)
|
||||
}
|
||||
|
||||
/// Every node under `place`, through any input.
|
||||
fn under(registry: &Registry, place: Place) -> Vec<NodeId> {
|
||||
let mut seen: Vec<NodeId> = Vec::new();
|
||||
let mut queue: Vec<NodeId> = Vec::new();
|
||||
if let Some(NodeInput::Node { id, .. }) = place_value(registry, place) {
|
||||
queue.push(id);
|
||||
}
|
||||
while let Some(id) = queue.pop() {
|
||||
if seen.contains(&id) || !registry.node_instances.contains_key(&id) {
|
||||
continue;
|
||||
}
|
||||
seen.push(id);
|
||||
for slot in ®istry.node_instances[&id].inputs {
|
||||
if let NodeInput::Node { id: next, .. } = slot.input {
|
||||
queue.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// Nodes chained off the export and off inputs past the primary one.
|
||||
struct Branching;
|
||||
|
||||
impl Scenario for Branching {
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
|
||||
let registry = session.registry().clone();
|
||||
let layers = stack(®istry);
|
||||
let nodes = under(®istry, Place::Export(0));
|
||||
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
|
||||
id: LEAF,
|
||||
network: Network::default(),
|
||||
});
|
||||
let make = |first: NodeInput, second: NodeInput| {
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
|
||||
node.inputs[0].input = first;
|
||||
node.inputs[1].input = second;
|
||||
node
|
||||
};
|
||||
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
|
||||
let plain: Vec<NodeId> = nodes
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| !matches!(place_value(®istry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
|
||||
.collect();
|
||||
|
||||
match random.below(12) {
|
||||
// Draw a node on top of the chain off the export
|
||||
0..=2 => {
|
||||
let id = session.next_node_id();
|
||||
let node = make(layers.first().map_or_else(|| value(0), |&top| on(top)), value(random.below(100)));
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(id)),
|
||||
},
|
||||
]);
|
||||
if let Some(&under) = layers.first() {
|
||||
ops.push(super::crdt::change_node_attribute(under, "position", serde_json::json!(random.below(100))));
|
||||
}
|
||||
ops
|
||||
}
|
||||
// Hang a node on an input past the primary one, over whatever is there already
|
||||
3..=5 => {
|
||||
let Some(host) = random.pick(&nodes) else { return Vec::new() };
|
||||
let id = session.next_node_id();
|
||||
let first = match place_value(®istry, Place::Input(host, 1)) {
|
||||
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
|
||||
_ => value(0),
|
||||
};
|
||||
let node = make(first, value(random.below(100)));
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: host,
|
||||
index: 1,
|
||||
new_input: on(id),
|
||||
},
|
||||
]);
|
||||
ops
|
||||
}
|
||||
// Delete a node, reconnecting everything that named it to what it rested on
|
||||
6..=7 => {
|
||||
let Some(node) = random.pick(&plain) else { return Vec::new() };
|
||||
let snapshot = registry.node_instances[&node].clone();
|
||||
let mut ops: Vec<RegistryDelta> = naming_places(®istry)
|
||||
.into_iter()
|
||||
.filter(|(_, named)| *named == node)
|
||||
.map(|(place, _)| set_place(place, below(®istry, node)))
|
||||
.collect();
|
||||
ops.push(RegistryDelta::RemoveNode { id: node, snapshot });
|
||||
ops
|
||||
}
|
||||
// Move a node to the top of the chain off the export
|
||||
8 => {
|
||||
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
|
||||
let Some(place) = consumer_place(®istry, layer) else { return Vec::new() };
|
||||
vec![
|
||||
set_place(place, below(®istry, layer)),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 0,
|
||||
new_input: on(layers[0]),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(layer)),
|
||||
},
|
||||
]
|
||||
}
|
||||
// Change a node's value
|
||||
9..=10 => {
|
||||
let Some(node) = random.pick(&plain) else { return Vec::new() };
|
||||
vec![RegistryDelta::ChangeNodeInput {
|
||||
id: node,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
// Cut the chain off an input past the primary one, taking its nodes with it
|
||||
_ => {
|
||||
let hosts: Vec<NodeId> = nodes
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| matches!(place_value(®istry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
|
||||
.collect();
|
||||
let Some(host) = random.pick(&hosts) else { return Vec::new() };
|
||||
let mut gone = under(®istry, Place::Input(host, 1));
|
||||
// Nothing outside the cut may name a node inside it, or taking them would leave that naming nothing
|
||||
let held = naming_places(®istry)
|
||||
.into_iter()
|
||||
.any(|(place, named)| gone.contains(&named) && place != Place::Input(host, 1) && !matches!(place, Place::Input(owner, _) if gone.contains(&owner)));
|
||||
if held {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ops = vec![RegistryDelta::ChangeNodeInput {
|
||||
id: host,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}];
|
||||
gone.sort();
|
||||
for id in gone {
|
||||
ops.push(RegistryDelta::RemoveNode {
|
||||
id,
|
||||
snapshot: registry.node_instances[&id].clone(),
|
||||
});
|
||||
}
|
||||
ops
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing names a node the document no longer has, every node is built from a network it still has, and no node
|
||||
/// input holds the empty export's value. A node may feed nothing or more than one input.
|
||||
fn assert_well_formed(context: &str, registry: &Registry) {
|
||||
for (place, named) in naming_places(registry) {
|
||||
assert!(registry.node_instances.contains_key(&named), "{context}: {place:?} names {named:?}, which is gone");
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
if let Implementation::Network(network) = &node.implementation {
|
||||
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
|
||||
}
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
assert_ne!(slot.input, empty_export(), "{context}: input {index} of {id:?} holds the empty export's value");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_operations_keep_a_branching_document_whole() {
|
||||
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
|
||||
for seed in 0..seeds {
|
||||
simulate::<Branching>(seed, steps, &mut Vec::new());
|
||||
}
|
||||
}
|
||||
@@ -1,64 +1,12 @@
|
||||
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation the History
|
||||
//! panel offers mixed in: undo, redo, going back, removing a step and bringing one back. After every operation the
|
||||
//! document must still be a well-formed stack, the snapshot must be what history folds to, and a peer following the
|
||||
//! head moves must hold the same document.
|
||||
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation mixed in.
|
||||
//! After every operation the document must still be a well-formed stack.
|
||||
//!
|
||||
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
|
||||
|
||||
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
|
||||
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
||||
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// What every layer's implementation names, so nodes need no proto-node declarations. The first layer drawn brings it,
|
||||
/// as the editor's first layer brings the subgraph every later one is built from.
|
||||
const LEAF: NetworkId = NetworkId(1);
|
||||
|
||||
/// What the export holds while the stack is empty, of another type than what the bottom layer rests on.
|
||||
fn empty_export() -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!("empty")),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A small xorshift generator, so a seed fixes the run.
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn new(seed: u64) -> Self {
|
||||
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
|
||||
}
|
||||
|
||||
fn below(&mut self, bound: usize) -> usize {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 % bound as u64) as usize
|
||||
}
|
||||
|
||||
fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
|
||||
(!options.is_empty()).then(|| options[self.below(options.len())])
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers from the top of the stack down, following each layer's first input.
|
||||
fn stack(registry: &Registry) -> Vec<NodeId> {
|
||||
let mut layers = Vec::new();
|
||||
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
|
||||
while let Some(NodeInput::Node { id, .. }) = below {
|
||||
if layers.contains(&id) || layers.len() > registry.node_instances.len() {
|
||||
break;
|
||||
}
|
||||
layers.push(id);
|
||||
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
|
||||
}
|
||||
layers
|
||||
}
|
||||
|
||||
/// What feeds into `layer` from below.
|
||||
fn below(registry: &Registry, layer: NodeId) -> NodeInput {
|
||||
registry.node_instances[&layer].inputs[0].input.clone()
|
||||
}
|
||||
|
||||
/// Points what sits directly above `layer`, a layer or the export, at `input`.
|
||||
fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> RegistryDelta {
|
||||
let layers = stack(registry);
|
||||
@@ -76,365 +24,124 @@ fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> Registr
|
||||
}
|
||||
}
|
||||
|
||||
fn on(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
/// A single stack of layers off the export.
|
||||
struct Stack;
|
||||
|
||||
fn value(number: usize) -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(number)),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One interaction's ops, as the editor would stage them for a random edit of the stack.
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
|
||||
let registry = session.registry().clone();
|
||||
let layers = stack(®istry);
|
||||
match random.below(10) {
|
||||
// Draw a layer on top
|
||||
0..=3 => {
|
||||
let id = session.next_node_id();
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
|
||||
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
|
||||
node.inputs[1].input = value(random.below(100));
|
||||
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
|
||||
id: LEAF,
|
||||
network: Network::default(),
|
||||
});
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(id)),
|
||||
},
|
||||
]);
|
||||
// The layer below moves into the stack under the new one, as the editor records with its position
|
||||
if let Some(&below) = layers.first() {
|
||||
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
|
||||
}
|
||||
ops
|
||||
}
|
||||
// Delete a layer, reconnecting what was above it to what was below
|
||||
4..=5 => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
let snapshot = registry.node_instances[&layer].clone();
|
||||
vec![rewire_above(®istry, layer, below(®istry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
|
||||
}
|
||||
// Move a layer to the top
|
||||
6 => {
|
||||
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
|
||||
vec![
|
||||
rewire_above(®istry, layer, below(®istry, layer)),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 0,
|
||||
new_input: on(layers[0]),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(layer)),
|
||||
},
|
||||
]
|
||||
}
|
||||
// Change a layer's value
|
||||
_ => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
vec![RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ops of an edit, short enough to read in a failing run's log.
|
||||
fn summarize(ops: &[RegistryDelta]) -> String {
|
||||
let short = |id: &NodeId| id.0 % 1000;
|
||||
let input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => format!("{}", short(id)),
|
||||
_ => "value".to_string(),
|
||||
};
|
||||
ops.iter()
|
||||
.map(|op| match op {
|
||||
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
|
||||
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
|
||||
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
|
||||
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
|
||||
other => format!("{other:?}"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// The revs closing each interaction on the head's line, newest first.
|
||||
fn line_steps(session: &Session) -> Vec<Rev> {
|
||||
let mut steps = Vec::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
if delta.is_interaction_end() {
|
||||
steps.push(delta.id);
|
||||
}
|
||||
current = delta.parent;
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The revs closing interactions left behind on branches.
|
||||
fn branch_steps(session: &Session) -> Vec<Rev> {
|
||||
let line: HashSet<Rev> = {
|
||||
let mut line = HashSet::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
line.insert(delta.id);
|
||||
current = delta.parent;
|
||||
}
|
||||
line
|
||||
};
|
||||
let mut steps: Vec<Rev> = session
|
||||
.history()
|
||||
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
|
||||
.map(|delta| delta.id)
|
||||
.collect();
|
||||
steps.sort();
|
||||
steps
|
||||
}
|
||||
|
||||
/// The layers the interaction ending at `end` added and deleted, by what it did in all.
|
||||
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
|
||||
let (mut added, mut removed) = (Vec::new(), Vec::new());
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddNode { id, .. } => added.push(*id),
|
||||
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
|
||||
_ => {}
|
||||
}
|
||||
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
|
||||
}
|
||||
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
|
||||
(net(&added, &removed), net(&removed, &added))
|
||||
}
|
||||
|
||||
/// The layers the step ending at `end` added that a newer deletion on its own line had taken again.
|
||||
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
|
||||
let mut lost = HashSet::new();
|
||||
let mut added_at = std::collections::HashMap::new();
|
||||
let mut line = Vec::new();
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
line.push(delta);
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
|
||||
added_at.entry(*id).or_insert(delta.timestamp);
|
||||
}
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
|
||||
&& added.contains(id)
|
||||
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
|
||||
{
|
||||
lost.insert(*id);
|
||||
}
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// The layers live on the line just before the interaction ending at `end`.
|
||||
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
let mut line = Vec::new();
|
||||
while let Some(delta) = current {
|
||||
line.push(delta.clone());
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
line.reverse();
|
||||
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
|
||||
replayed.retired_registry().node_instances.keys().copied().collect()
|
||||
}
|
||||
|
||||
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
|
||||
/// left drawn by nothing.
|
||||
fn assert_well_formed(context: &str, registry: &Registry) {
|
||||
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
|
||||
let export = exports.first().and_then(|slot| slot.target.clone());
|
||||
if let Some(NodeInput::Node { id, .. }) = &export {
|
||||
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = &slot.input {
|
||||
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut stacked_on = HashSet::new();
|
||||
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
|
||||
for input in primary_inputs.chain(export.iter()) {
|
||||
if let NodeInput::Node { id, .. } = input {
|
||||
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
|
||||
}
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
if let Implementation::Network(network) = &node.implementation {
|
||||
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
|
||||
}
|
||||
}
|
||||
let layers = stack(registry);
|
||||
if let Some(bottom) = layers.last() {
|
||||
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
|
||||
}
|
||||
let unique: HashSet<NodeId> = layers.iter().copied().collect();
|
||||
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
|
||||
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
|
||||
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
|
||||
}
|
||||
|
||||
fn assert_consistent(context: &str, session: &Session) {
|
||||
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
|
||||
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
|
||||
let folded = session.snapshot_from_history().expect("history folds");
|
||||
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
|
||||
assert_well_formed(context, session.retired_registry());
|
||||
}
|
||||
|
||||
/// Closes the open interaction and retires it as one step.
|
||||
fn retire_step(session: &mut Session) {
|
||||
session.end_interaction().expect("close");
|
||||
for interaction in session.closed_interactions() {
|
||||
session.retire_interaction(&interaction).expect("retire");
|
||||
}
|
||||
}
|
||||
|
||||
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
|
||||
fn catch_up(follower: &mut Session, host: &Session) {
|
||||
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
|
||||
follower.follow(missing, host.head_rev()).expect("follow");
|
||||
}
|
||||
|
||||
/// A peer that joins now and holds what the host holds.
|
||||
fn fresh_follower(host: &Session) -> Session {
|
||||
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
|
||||
}
|
||||
|
||||
fn simulate(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
|
||||
let mut random = Random::new(seed);
|
||||
let mut host = Session::with_identity(PeerId(1), UserId(1));
|
||||
let document = [
|
||||
RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(empty_export()),
|
||||
},
|
||||
];
|
||||
host.stage_ops(document).expect("stage the document");
|
||||
retire_step(&mut host);
|
||||
let mut follower = fresh_follower(&host);
|
||||
|
||||
for step in 0..steps {
|
||||
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
|
||||
match random.below(12) {
|
||||
0..=5 => {
|
||||
let ops = random_edit(&mut random, &mut host);
|
||||
if ops.is_empty() {
|
||||
continue;
|
||||
impl Scenario for Stack {
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
|
||||
let registry = session.registry().clone();
|
||||
let layers = stack(®istry);
|
||||
match random.below(10) {
|
||||
// Draw a layer on top
|
||||
0..=3 => {
|
||||
let id = session.next_node_id();
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
|
||||
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
|
||||
node.inputs[1].input = value(random.below(100));
|
||||
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
|
||||
id: LEAF,
|
||||
network: Network::default(),
|
||||
});
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(id)),
|
||||
},
|
||||
]);
|
||||
// The layer below moves into the stack under the new one, as the editor records with its position
|
||||
if let Some(&below) = layers.first() {
|
||||
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
|
||||
}
|
||||
log.push(format!("{step}: edit {}", summarize(&ops)));
|
||||
host.stage_ops(ops).expect("stage");
|
||||
retire_step(&mut host);
|
||||
catch_up(&mut follower, &host);
|
||||
ops
|
||||
}
|
||||
6 if host.can_undo() => {
|
||||
log.push(format!("{step}: undo"));
|
||||
host.undo().expect("undo");
|
||||
follower = fresh_follower(&host);
|
||||
// Delete a layer, reconnecting what was above it to what was below
|
||||
4..=5 => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
let snapshot = registry.node_instances[&layer].clone();
|
||||
vec![rewire_above(®istry, layer, below(®istry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
|
||||
}
|
||||
7 if host.can_redo() => {
|
||||
log.push(format!("{step}: redo"));
|
||||
host.redo().expect("redo");
|
||||
follower = fresh_follower(&host);
|
||||
// Move a layer to the top
|
||||
6 => {
|
||||
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
|
||||
vec![
|
||||
rewire_above(®istry, layer, below(®istry, layer)),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 0,
|
||||
new_input: on(layers[0]),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(layer)),
|
||||
},
|
||||
]
|
||||
}
|
||||
8 => {
|
||||
// Not the newest step, which going back to would leave everything as it is
|
||||
let Some(target) = random.pick(&line_steps(&host)[1.min(line_steps(&host).len())..]) else {
|
||||
continue;
|
||||
};
|
||||
log.push(format!("{step}: go back to {target:?}"));
|
||||
let (moved, _) = host.move_head_to(target).expect("go back");
|
||||
follower.apply_head_move(&moved).expect("follow the move");
|
||||
// Change a layer's value
|
||||
_ => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
vec![RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
9 => {
|
||||
let steps = line_steps(&host);
|
||||
// The first step makes the document, which nothing can do without
|
||||
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
|
||||
log.push(format!("{step}: remove {target:?}"));
|
||||
let (mut added, _) = added_and_removed(&host, target);
|
||||
// A layer the line had before the step stays
|
||||
let earlier = live_before(&host, target);
|
||||
added.retain(|id| !earlier.contains(id));
|
||||
let (moved, _) = host.drop_interaction(target).expect("remove the step");
|
||||
follower.apply_head_move(&moved).expect("follow the removal");
|
||||
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the removed step's layers {kept:?} are still there"), log));
|
||||
}
|
||||
10 | 11 => {
|
||||
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
|
||||
log.push(format!("{step}: bring back {target:?}"));
|
||||
let (mut added, removed) = added_and_removed(&host, target);
|
||||
// A layer the line already had from this step and deleted since stays deleted
|
||||
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
|
||||
// As does one a newer deletion took on the step's own line
|
||||
let lost = lost_on_its_line(&host, target, &added);
|
||||
added.retain(|id| !lost.contains(id));
|
||||
host.restore_interaction(target).expect("bring back");
|
||||
catch_up(&mut follower, &host);
|
||||
let registry = host.retired_registry();
|
||||
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
|
||||
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
|
||||
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's layers {missing:?} are missing"), log));
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the layers {kept:?} the brought back step deleted are still there"), log));
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
let what = log.last().cloned().unwrap_or_default();
|
||||
assert_consistent(&context(&what, log), &host);
|
||||
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
|
||||
assert!(
|
||||
follower.retired_registry().value_equal(host.retired_registry()),
|
||||
"{}",
|
||||
context("the follower holds another document", log)
|
||||
);
|
||||
}
|
||||
host
|
||||
|
||||
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
|
||||
/// left drawn by nothing.
|
||||
fn assert_well_formed(context: &str, registry: &Registry) {
|
||||
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
|
||||
let export = exports.first().and_then(|slot| slot.target.clone());
|
||||
if let Some(NodeInput::Node { id, .. }) = &export {
|
||||
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = &slot.input {
|
||||
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut stacked_on = HashSet::new();
|
||||
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
|
||||
for input in primary_inputs.chain(export.iter()) {
|
||||
if let NodeInput::Node { id, .. } = input {
|
||||
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
|
||||
}
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
if let Implementation::Network(network) = &node.implementation {
|
||||
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
|
||||
}
|
||||
}
|
||||
let layers = stack(registry);
|
||||
if let Some(bottom) = layers.last() {
|
||||
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
|
||||
}
|
||||
let unique: HashSet<NodeId> = layers.iter().copied().collect();
|
||||
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
|
||||
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
|
||||
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_operations_keep_the_stack_whole_and_peers_converged() {
|
||||
let seeds: u64 = std::env::var("SEEDS").ok().and_then(|seeds| seeds.parse().ok()).unwrap_or(200);
|
||||
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
|
||||
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
|
||||
for seed in 0..seeds {
|
||||
simulate(seed, steps, &mut Vec::new());
|
||||
simulate::<Stack>(seed, steps, &mut Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// A seed fixes the run, so one that fails can be replayed.
|
||||
#[test]
|
||||
fn a_seed_fixes_the_history_run() {
|
||||
let histories = |seed| simulate(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
|
||||
let histories = |seed| simulate::<Stack>(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
|
||||
for seed in 0..5 {
|
||||
assert_eq!(histories(seed), histories(seed), "seed {seed}");
|
||||
}
|
||||
@@ -443,9 +150,7 @@ fn a_seed_fixes_the_history_run() {
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn inspect_seed() {
|
||||
let seed = std::env::var("SEED").ok().and_then(|seed| seed.parse().ok()).unwrap_or(0);
|
||||
let mut log = Vec::new();
|
||||
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
|
||||
let host = simulate(seed, steps, &mut log);
|
||||
let host = simulate::<Stack>(from_env("SEED", 0), from_env("STEPS", 80), &mut log);
|
||||
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
|
||||
}
|
||||
@@ -1033,6 +1033,33 @@ fn deleting_a_node_without_inputs_gives_the_input_it_fed_its_earlier_value() {
|
||||
assert_eq!(registry.node_instances[&consumer].inputs()[1].input, earlier_value);
|
||||
}
|
||||
|
||||
/// Bringing back a step that writes to a node the line never had reconnects an input naming that node to what history
|
||||
/// holds as its primary input, though the write leaves only a placeholder of it.
|
||||
#[test]
|
||||
fn bringing_back_a_step_reconnects_past_a_node_the_line_never_had() {
|
||||
let (source, consumer) = (NodeId(1), NodeId(2));
|
||||
let source_value = NodeInput::Value {
|
||||
value: Value::from(serde_json::json!("under the source")),
|
||||
exposed: false,
|
||||
};
|
||||
let mut source_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
|
||||
source_node.inputs[0].input = source_value.clone();
|
||||
let mut consumer_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
|
||||
consumer_node.inputs[0].input = NodeInput::Node { id: source, index: 0 };
|
||||
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
let base = step(&mut session, add_network(5));
|
||||
step(&mut session, RegistryDelta::AddNode { id: source, node: source_node });
|
||||
session.commit_op_for_test(RegistryDelta::AddNode { id: consumer, node: consumer_node }).expect("commit");
|
||||
let consumed = step(&mut session, change_node_attribute(source, "position", serde_json::json!(1)));
|
||||
session.move_head_to(base).expect("go back to before the source");
|
||||
|
||||
session.restore_interaction(consumed).expect("bring the consumer back");
|
||||
let registry = session.retired_registry();
|
||||
assert!(registry.removed_nodes.get(&source).is_some_and(|tombstone| tombstone.placeholder));
|
||||
assert_eq!(registry.node_instances[&consumer].inputs()[0].input, source_value);
|
||||
}
|
||||
|
||||
/// Undo of a retired step names the person's latest step, not the device's. A fresh copy of the document under a new
|
||||
/// peer id still undoes what its user did from the old one, and nobody else's.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
//! Shared harness of the deterministic history simulations: a seeded generator, every history operation the History
|
||||
//! panel offers, and the checks each run makes after every operation.
|
||||
|
||||
use crate::{Network, NetworkId, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// What every node's implementation names, so nodes need no proto-node declarations. The first node drawn brings it,
|
||||
/// as the editor's first layer brings the subgraph every later one is built from.
|
||||
pub(super) const LEAF: NetworkId = NetworkId(1);
|
||||
|
||||
/// What the export holds while the document is empty, of another type than what a chain's bottom rests on.
|
||||
pub(super) fn empty_export() -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!("empty")),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A small xorshift generator, so a seed fixes the run.
|
||||
pub(super) struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn new(seed: u64) -> Self {
|
||||
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
|
||||
}
|
||||
|
||||
pub(super) fn below(&mut self, bound: usize) -> usize {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 % bound as u64) as usize
|
||||
}
|
||||
|
||||
pub(super) fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
|
||||
(!options.is_empty()).then(|| options[self.below(options.len())])
|
||||
}
|
||||
}
|
||||
|
||||
/// A kind of document the simulation edits.
|
||||
pub(super) trait Scenario {
|
||||
/// One interaction's ops for a random edit, as the editor would stage them.
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta>;
|
||||
|
||||
/// Panics with `context` when `registry` is not a document this scenario allows.
|
||||
fn assert_well_formed(context: &str, registry: &Registry);
|
||||
}
|
||||
|
||||
/// The nodes down the chain off the export, following each one's primary input.
|
||||
pub(super) fn stack(registry: &Registry) -> Vec<NodeId> {
|
||||
let mut nodes = Vec::new();
|
||||
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
|
||||
while let Some(NodeInput::Node { id, .. }) = below {
|
||||
if nodes.contains(&id) {
|
||||
break;
|
||||
}
|
||||
nodes.push(id);
|
||||
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
|
||||
}
|
||||
nodes
|
||||
}
|
||||
|
||||
/// What feeds into `node` from below.
|
||||
pub(super) fn below(registry: &Registry, node: NodeId) -> NodeInput {
|
||||
registry.node_instances[&node].inputs[0].input.clone()
|
||||
}
|
||||
|
||||
pub(super) fn on(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
|
||||
pub(super) fn value(number: usize) -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(number)),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a number from the environment variable `name`, so a run can be widened or replayed.
|
||||
pub(super) fn from_env<T: std::str::FromStr>(name: &str, default: T) -> T {
|
||||
std::env::var(name).ok().and_then(|text| text.parse().ok()).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// The ops of an edit, short enough to read in a failing run's log.
|
||||
fn summarize(ops: &[RegistryDelta]) -> String {
|
||||
let short = |id: &NodeId| id.0 % 1000;
|
||||
let input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => format!("{}", short(id)),
|
||||
_ => "value".to_string(),
|
||||
};
|
||||
ops.iter()
|
||||
.map(|op| match op {
|
||||
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
|
||||
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
|
||||
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
|
||||
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
|
||||
other => format!("{other:?}"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// The revs closing each interaction on the head's line, newest first.
|
||||
fn line_steps(session: &Session) -> Vec<Rev> {
|
||||
let mut steps = Vec::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
if delta.is_interaction_end() {
|
||||
steps.push(delta.id);
|
||||
}
|
||||
current = delta.parent;
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The revs closing interactions left behind on branches.
|
||||
fn branch_steps(session: &Session) -> Vec<Rev> {
|
||||
let line: HashSet<Rev> = {
|
||||
let mut line = HashSet::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
line.insert(delta.id);
|
||||
current = delta.parent;
|
||||
}
|
||||
line
|
||||
};
|
||||
let mut steps: Vec<Rev> = session
|
||||
.history()
|
||||
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
|
||||
.map(|delta| delta.id)
|
||||
.collect();
|
||||
steps.sort();
|
||||
steps
|
||||
}
|
||||
|
||||
/// The nodes the interaction ending at `end` added and deleted, by what it did in all.
|
||||
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
|
||||
let (mut added, mut removed) = (Vec::new(), Vec::new());
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddNode { id, .. } => added.push(*id),
|
||||
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
|
||||
_ => {}
|
||||
}
|
||||
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
|
||||
}
|
||||
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
|
||||
(net(&added, &removed), net(&removed, &added))
|
||||
}
|
||||
|
||||
/// The nodes the step ending at `end` added that a newer deletion on its own line had taken again.
|
||||
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
|
||||
let mut lost = HashSet::new();
|
||||
let mut added_at = HashMap::new();
|
||||
let mut line = Vec::new();
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
line.push(delta);
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
|
||||
added_at.entry(*id).or_insert(delta.timestamp);
|
||||
}
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
|
||||
&& added.contains(id)
|
||||
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
|
||||
{
|
||||
lost.insert(*id);
|
||||
}
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// The nodes live on the line just before the interaction ending at `end`.
|
||||
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
let mut line = Vec::new();
|
||||
while let Some(delta) = current {
|
||||
line.push(delta.clone());
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
line.reverse();
|
||||
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
|
||||
replayed.retired_registry().node_instances.keys().copied().collect()
|
||||
}
|
||||
|
||||
fn assert_consistent<S: Scenario>(context: &str, session: &Session) {
|
||||
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
|
||||
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
|
||||
let folded = session.snapshot_from_history().expect("history folds");
|
||||
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
|
||||
S::assert_well_formed(context, session.retired_registry());
|
||||
}
|
||||
|
||||
/// Closes the open interaction and retires it as one step.
|
||||
fn retire_step(session: &mut Session) {
|
||||
session.end_interaction().expect("close");
|
||||
for interaction in session.closed_interactions() {
|
||||
session.retire_interaction(&interaction).expect("retire");
|
||||
}
|
||||
}
|
||||
|
||||
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
|
||||
fn catch_up(follower: &mut Session, host: &Session) {
|
||||
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
|
||||
follower.follow(missing, host.head_rev()).expect("follow");
|
||||
}
|
||||
|
||||
/// A peer that joins now and holds what the host holds.
|
||||
fn fresh_follower(host: &Session) -> Session {
|
||||
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
|
||||
}
|
||||
|
||||
/// Runs `steps` random edits and history operations from `seed`. After each one the document must be well formed, the
|
||||
/// snapshot must be what history folds to, and a peer following the host must hold the same document.
|
||||
pub(super) fn simulate<S: Scenario>(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
|
||||
let mut random = Random::new(seed);
|
||||
let mut host = Session::with_identity(PeerId(1), UserId(1));
|
||||
let document = [
|
||||
RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(empty_export()),
|
||||
},
|
||||
];
|
||||
host.stage_ops(document).expect("stage the document");
|
||||
retire_step(&mut host);
|
||||
let mut follower = fresh_follower(&host);
|
||||
|
||||
for step in 0..steps {
|
||||
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
|
||||
match random.below(12) {
|
||||
0..=5 => {
|
||||
let ops = S::random_edit(&mut random, &mut host);
|
||||
if ops.is_empty() {
|
||||
continue;
|
||||
}
|
||||
log.push(format!("{step}: edit {}", summarize(&ops)));
|
||||
host.stage_ops(ops).expect("stage");
|
||||
retire_step(&mut host);
|
||||
catch_up(&mut follower, &host);
|
||||
}
|
||||
6 if host.can_undo() => {
|
||||
log.push(format!("{step}: undo"));
|
||||
host.undo().expect("undo");
|
||||
follower = fresh_follower(&host);
|
||||
}
|
||||
7 if host.can_redo() => {
|
||||
log.push(format!("{step}: redo"));
|
||||
host.redo().expect("redo");
|
||||
follower = fresh_follower(&host);
|
||||
}
|
||||
8 => {
|
||||
let steps = line_steps(&host);
|
||||
// Not the newest step, which going back to would leave everything as it is
|
||||
let Some(target) = random.pick(&steps[1.min(steps.len())..]) else { continue };
|
||||
log.push(format!("{step}: go back to {target:?}"));
|
||||
let (moved, _) = host.move_head_to(target).expect("go back");
|
||||
follower.apply_head_move(&moved).expect("follow the move");
|
||||
}
|
||||
9 => {
|
||||
let steps = line_steps(&host);
|
||||
// The first step makes the document, which nothing can do without
|
||||
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
|
||||
log.push(format!("{step}: remove {target:?}"));
|
||||
let (mut added, _) = added_and_removed(&host, target);
|
||||
// A node the line had before the step stays
|
||||
let earlier = live_before(&host, target);
|
||||
added.retain(|id| !earlier.contains(id));
|
||||
let (moved, _) = host.drop_interaction(target).expect("remove the step");
|
||||
follower.apply_head_move(&moved).expect("follow the removal");
|
||||
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the removed step's nodes {kept:?} are still there"), log));
|
||||
}
|
||||
10 | 11 => {
|
||||
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
|
||||
log.push(format!("{step}: bring back {target:?}"));
|
||||
let (mut added, removed) = added_and_removed(&host, target);
|
||||
// A node the line already had from this step and deleted since stays deleted
|
||||
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
|
||||
// As does one a newer deletion took on the step's own line
|
||||
let lost = lost_on_its_line(&host, target, &added);
|
||||
added.retain(|id| !lost.contains(id));
|
||||
host.restore_interaction(target).expect("bring back");
|
||||
catch_up(&mut follower, &host);
|
||||
let registry = host.retired_registry();
|
||||
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
|
||||
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
|
||||
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's nodes {missing:?} are missing"), log));
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the nodes {kept:?} the brought back step deleted are still there"), log));
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
let what = log.last().cloned().unwrap_or_default();
|
||||
assert_consistent::<S>(&context(&what, log), &host);
|
||||
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
|
||||
assert!(
|
||||
follower.retired_registry().value_equal(host.retired_registry()),
|
||||
"{}",
|
||||
context("the follower holds another document", log)
|
||||
);
|
||||
}
|
||||
host
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
TransferCurve(Vec<[f64; 2]>),
|
||||
TypeDefault(Type),
|
||||
}
|
||||
|
||||
/// Frozen mirror of the `Type` a paint input's lack of a paint stores.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Type {
|
||||
Concrete(TypeDescriptor),
|
||||
Item(Box<Type>),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypeDescriptor {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// 'Bevel & Emboss' gained a texture with its depth, and a gloss contour and a slope contour with its range, set to no texture and straight contours across the whole slope to keep the bevel as it was.
|
||||
#[migration("blending_nodes::effects::BevelAndEmbossNode"@1 => @2)]
|
||||
pub fn bevel_and_emboss_v1(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// The texture, its depth, the slope contour's range, the gloss and slope contours' antialiasing, and the gloss and slope contours.
|
||||
fn added_inputs() -> [NodeInput; 7] {
|
||||
let straight = || literal(Tagged::TransferCurve(vec![[0., 0.], [1., 1.]]));
|
||||
let no_paint = Tagged::TypeDefault(Type::Item(Box::new(Type::Concrete(TypeDescriptor {
|
||||
name: "graphic_types::graphic::Graphic".to_string(),
|
||||
}))));
|
||||
|
||||
[
|
||||
literal(no_paint),
|
||||
literal(Tagged::Number(100.)),
|
||||
literal(Tagged::Number(100.)),
|
||||
literal(Tagged::Bool(false)),
|
||||
literal(Tagged::Bool(false)),
|
||||
straight(),
|
||||
straight(),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(13, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BevelAndEmbossV1, &contract());
|
||||
check_undo(&BevelAndEmbossV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_options_that_leave_the_bevel_as_it_was() {
|
||||
let inputs: Vec<_> = (0..13).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&BevelAndEmbossV1);
|
||||
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&BevelAndEmbossV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, bevel), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Drop Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
|
||||
#[migration("blending_nodes::effects::DropShadowNode"@1 => @2)]
|
||||
pub fn drop_shadow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&DropShadowV1, &contract());
|
||||
check_undo(&DropShadowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&DropShadowV1);
|
||||
let drop_shadow = fixture.add(decl!("blending_nodes::effects::DropShadowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&DropShadowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, drop_shadow), Some(decl!("blending_nodes::effects::DropShadowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, drop_shadow), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Inner Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
|
||||
#[migration("blending_nodes::effects::InnerGlowNode"@1 => @2)]
|
||||
pub fn inner_glow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&InnerGlowV1, &contract());
|
||||
check_undo(&InnerGlowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&InnerGlowV1);
|
||||
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&InnerGlowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Inner Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
|
||||
#[migration("blending_nodes::effects::InnerShadowNode"@1 => @2)]
|
||||
pub fn inner_shadow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&InnerShadowV1, &contract());
|
||||
check_undo(&InnerShadowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&InnerShadowV1);
|
||||
let inner_shadow = fixture.add(decl!("blending_nodes::effects::InnerShadowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&InnerShadowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, inner_shadow), Some(decl!("blending_nodes::effects::InnerShadowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, inner_shadow), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
MaskMode(MaskMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MaskMode {
|
||||
Luminance,
|
||||
}
|
||||
|
||||
/// 'Mask' became an effect masking any graphic by any other, keeping its content and mask and gaining its mode, density, feather, and invert at their defaults.
|
||||
#[migration("raster_nodes::std_nodes::MaskNode"@1 => "blending_nodes::masks::MaskNode"@2)]
|
||||
pub fn mask_by_any_graphic(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::MaskMode(MaskMode::Luminance)));
|
||||
inputs.push(literal(Tagged::Number(100.)));
|
||||
inputs.push(literal(Tagged::Number(0.)));
|
||||
inputs.push(literal(Tagged::Bool(false)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MaskByAnyGraphic, &contract());
|
||||
check_undo(&MaskByAnyGraphic, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_content_and_mask_and_adds_the_defaults() {
|
||||
let (content, stencil) = (literal(1.), literal(2.));
|
||||
|
||||
let mut fixture = Fixture::new(&MaskByAnyGraphic);
|
||||
let mask = fixture.add(decl!("raster_nodes::std_nodes::MaskNode"@1), vec![content.clone(), stencil.clone()]);
|
||||
let migrated = fixture.migrate(&MaskByAnyGraphic).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, mask), Some(decl!("blending_nodes::masks::MaskNode"@2)));
|
||||
let defaults = [
|
||||
literal(Tagged::MaskMode(MaskMode::Luminance)),
|
||||
literal(Tagged::Number(100.)),
|
||||
literal(Tagged::Number(0.)),
|
||||
literal(Tagged::Bool(false)),
|
||||
];
|
||||
assert_eq!(fixture.inputs(&migrated, mask), [[content, stencil].as_slice(), &defaults].concat());
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,13 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod bevel_and_emboss_v1;
|
||||
mod drop_shadow_v1;
|
||||
mod inner_glow_v1;
|
||||
mod inner_shadow_v1;
|
||||
mod mask_by_any_graphic;
|
||||
mod outer_glow_v1;
|
||||
mod outline_v1;
|
||||
mod outline_v2;
|
||||
mod paint_overlay_from_color_overlay;
|
||||
mod renames;
|
||||
mod satin_v1;
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Outer Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
|
||||
#[migration("blending_nodes::effects::OuterGlowNode"@1 => @2)]
|
||||
pub fn outer_glow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OuterGlowV1, &contract());
|
||||
check_undo(&OuterGlowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OuterGlowV1);
|
||||
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&OuterGlowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Outline' gained a blend mode after its color, set to Normal, which composites the outline as before.
|
||||
#[migration("blending_nodes::effects::OutlineNode"@1 => @2)]
|
||||
pub fn outline_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OutlineV1, &contract());
|
||||
check_undo(&OutlineV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OutlineV1);
|
||||
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&OutlineV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// 'Outline' takes its color as any paint now, and gained a Contour Gradient option, set off to keep painting by the paint's own placement.
|
||||
#[migration("blending_nodes::effects::OutlineNode"@2 => @3)]
|
||||
pub fn outline_v2(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::Bool(false)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OutlineV2, &contract());
|
||||
check_undo(&OutlineV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_contour_gradient_off() {
|
||||
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OutlineV2);
|
||||
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&OutlineV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.push(literal(Tagged::Bool(false)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Node, migration};
|
||||
|
||||
/// 'Color Overlay' became the 'Paint Overlay' effect, which takes its color as a solid paint. A name it stored as its default would misname it.
|
||||
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => "blending_nodes::effects::PaintOverlayNode"@2)]
|
||||
pub fn paint_overlay_from_color_overlay(node: &Node, attributes: &mut Attributes) {
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Color Overlay") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::TimeStamp;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
let contract = SourceContract {
|
||||
display_names: &["Color Overlay"],
|
||||
..SourceContract::new(4, |random, _| literal(random.below(10) as f64))
|
||||
};
|
||||
check_commutation(&PaintOverlayFromColorOverlay, &contract);
|
||||
check_undo(&PaintOverlayFromColorOverlay, &contract);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_old_default_name_is_cleared() {
|
||||
for (name, kept) in [("Color Overlay", None), ("Tint", Some("Tint"))] {
|
||||
let mut fixture = Fixture::new(&PaintOverlayFromColorOverlay);
|
||||
let overlay = fixture.add(decl!("raster_nodes::blending_nodes::ColorOverlayNode"@1), Vec::new());
|
||||
let attributes = fixture.registry.node_instances.get_mut(&overlay).unwrap().attributes_mut();
|
||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let migrated = fixture.migrate(&PaintOverlayFromColorOverlay).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@2)));
|
||||
assert_eq!(migrated.node_instances[&overlay].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Satin' gained a blend mode after its color, set to Normal to keep compositing the shading as before.
|
||||
#[migration("blending_nodes::effects::SatinNode"@1 => @2)]
|
||||
pub fn satin_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&SatinV1, &contract());
|
||||
check_undo(&SatinV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&SatinV1);
|
||||
let satin = fixture.add(decl!("blending_nodes::effects::SatinNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&SatinV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, satin), Some(decl!("blending_nodes::effects::SatinNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, satin), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
//! Migrations of the nodes in `graphene_std`.
|
||||
|
||||
mod rasterize_v1;
|
||||
mod renames;
|
||||
@@ -1,68 +0,0 @@
|
||||
use migration_core::{Inputs, MigrationError, NodeInput, migration};
|
||||
use serde::Serialize;
|
||||
|
||||
const EXECUTOR: u32 = 2;
|
||||
const EXECUTOR_SCOPE: &str = "graphene_std::platform_application_io::WgpuExecutorNode";
|
||||
|
||||
/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses.
|
||||
#[derive(Serialize)]
|
||||
enum Reflected {
|
||||
DocumentNodePath,
|
||||
}
|
||||
|
||||
/// Rasterize gained an input holding its own document node path. Nodes stored without the executor input get it first, so the path lands after it.
|
||||
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
|
||||
pub fn rasterize_v1(inputs: &mut Inputs) -> Result<(), MigrationError> {
|
||||
if inputs.len() < EXECUTOR as usize {
|
||||
return Err(MigrationError::invariant("Rasterize has Data and Footprint inputs"));
|
||||
}
|
||||
if inputs.len() == EXECUTOR as usize {
|
||||
inputs.push(NodeInput::Scope(EXECUTOR_SCOPE.into()));
|
||||
}
|
||||
|
||||
inputs.push_reflection(Reflected::DocumentNodePath);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
fn migrate(inputs: Vec<NodeInput>) -> Vec<NodeInput> {
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let rasterize = fixture.add(decl!("graphene_std::platform_application_io::RasterizeNode"@1), inputs);
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let own_path = &migrated.node_instances[&rasterize].inputs()[3];
|
||||
assert_eq!(own_path.attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
|
||||
|
||||
fixture.inputs(&migrated, rasterize)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RasterizeV1, &contract());
|
||||
check_undo(&RasterizeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gives_the_node_its_path() {
|
||||
let inputs = vec![literal(1.), literal(2.), NodeInput::Scope(EXECUTOR_SCOPE.into())];
|
||||
|
||||
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Reflection]].concat());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_stored_without_its_executor_gets_it_before_its_path() {
|
||||
let inputs = vec![literal(1.), literal(2.)];
|
||||
|
||||
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Scope(EXECUTOR_SCOPE.into()), NodeInput::Reflection]].concat());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
use migration_core::attr::node::ui::POSITION;
|
||||
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, Inputs, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Integer(i64),
|
||||
DVec2([f64; 2]),
|
||||
MandelbrotFractal(MandelbrotFractal),
|
||||
MandelbrotExterior(MandelbrotExterior),
|
||||
MandelbrotInterior(MandelbrotInterior),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MandelbrotFractal {
|
||||
ClassicMandelbrot,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MandelbrotExterior {
|
||||
SmoothEscape,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MandelbrotInterior {
|
||||
Flat,
|
||||
}
|
||||
|
||||
/// How far the old unit square, which spanned the complex plane from -2 to 1, placed the plane's origin from the pattern's.
|
||||
const OLD_ORIGIN: [f64; 2] = [2. / 3., 0.5];
|
||||
|
||||
/// 'Mandelbrot' gained a scale and settings for its fractal, its slice toward the Julia set, and its interior and exterior, and the complex plane's origin moved to the pattern's.
|
||||
/// A third of a unit's scale and a Transform moving the pattern back to the old origin keep its look.
|
||||
#[migration("raster_nodes::std_nodes::MandelbrotNode"@2 => @3)]
|
||||
pub fn mandelbrot_v2(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) {
|
||||
for input in new_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
|
||||
let consumers = downstream.consumers(0);
|
||||
if consumers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let origin = downstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
inputs: vec![
|
||||
NodeInput::Node { id: node.id(), index: 0 },
|
||||
literal(Tagged::DVec2(OLD_ORIGIN)),
|
||||
literal(Tagged::Number(0.)),
|
||||
literal(Tagged::DVec2([1., 1.])),
|
||||
literal(Tagged::DVec2([0., 0.])),
|
||||
],
|
||||
},
|
||||
"origin",
|
||||
);
|
||||
for consumer in consumers {
|
||||
downstream.connect(OutputConnector { node: origin, output: 0 }, consumer);
|
||||
}
|
||||
|
||||
// The Transform takes the pattern's place, with the pattern before it
|
||||
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
|
||||
attributes.set(origin, POSITION, &stored);
|
||||
}
|
||||
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
|
||||
}
|
||||
|
||||
/// The settings 'Mandelbrot' gained, in the order of its parameters, with the scale matching the old unit square's three units of the plane.
|
||||
fn new_inputs() -> [NodeInput; 10] {
|
||||
[
|
||||
literal(Tagged::MandelbrotFractal(MandelbrotFractal::ClassicMandelbrot)),
|
||||
literal(Tagged::MandelbrotExterior(MandelbrotExterior::SmoothEscape)),
|
||||
literal(Tagged::MandelbrotInterior(MandelbrotInterior::Flat)),
|
||||
literal(Tagged::Integer(1)),
|
||||
literal(Tagged::Number(1. / 3.)),
|
||||
literal(Tagged::Integer(256)),
|
||||
literal(Tagged::Number(2.)),
|
||||
literal(Tagged::Number(0.)),
|
||||
literal(Tagged::DVec2([0., 0.])),
|
||||
literal(Tagged::DVec2([-0.8, 0.156])),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(1, |_, _| literal(Tagged::None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MandelbrotV2, &contract());
|
||||
check_undo(&MandelbrotV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_primary_input_and_adds_the_settings() {
|
||||
let mut fixture = Fixture::new(&MandelbrotV2);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@2), vec![literal(Tagged::None)]);
|
||||
let migrated = fixture.migrate(&MandelbrotV2).unwrap();
|
||||
|
||||
let mut expected = vec![literal(Tagged::None)];
|
||||
expected.extend(new_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, mandelbrot), Some(decl!("raster_nodes::std_nodes::MandelbrotNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, mandelbrot), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whatever_read_the_pattern_reads_it_moved_back_to_the_old_origin() {
|
||||
let mut fixture = Fixture::new(&MandelbrotV2);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@2), vec![literal(Tagged::None)]);
|
||||
let consumer = fixture.add(decl!("migration_testing::consumer"@1), vec![NodeInput::Node { id: mandelbrot, index: 0 }]);
|
||||
let migrated = fixture.migrate(&MandelbrotV2).unwrap();
|
||||
|
||||
let NodeInput::Node { id: origin, .. } = fixture.inputs(&migrated, consumer)[0] else {
|
||||
panic!("the consumer should read a node")
|
||||
};
|
||||
assert_eq!(fixture.declaration_of(&migrated, origin), Some(decl!("transform_nodes::transform_nodes::TransformNode"@1)));
|
||||
|
||||
let inputs = fixture.inputs(&migrated, origin);
|
||||
assert_eq!(inputs[0], NodeInput::Node { id: mandelbrot, index: 0 });
|
||||
assert_eq!(inputs[1], literal(Tagged::DVec2(OLD_ORIGIN)));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Migrations of the nodes in `raster_nodes`.
|
||||
|
||||
mod mandelbrot_v1;
|
||||
mod mandelbrot_v2;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod pattern_square;
|
||||
|
||||
@@ -6,3 +6,5 @@ rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_n
|
||||
// Version 2 only adds `InjectFootprint` to the context bounds, so stored nodes keep their layout
|
||||
rename!("core_types::vector::AreaNode"@1 => @2);
|
||||
rename!("core_types::vector::CentroidNode"@1 => @2);
|
||||
// Version 2 only lets its output carry an error, so stored nodes keep their layout
|
||||
rename!("core_types::vector::ScatterPointsNode"@1 => @2);
|
||||
@@ -18,7 +18,8 @@ pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.;
|
||||
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
|
||||
pub const VIEWPORT_ZOOM_MOUSE_RATE: f64 = 1. / 400.;
|
||||
pub const VIEWPORT_ZOOM_SCALE_MIN: f64 = 0.000_000_1;
|
||||
pub const VIEWPORT_ZOOM_SCALE_MAX: f64 = 10_000.;
|
||||
/// Deep enough to reach the limits of 64-bit precision, which still places each pixel precisely around document coordinates in the thousands.
|
||||
pub const VIEWPORT_ZOOM_SCALE_MAX: f64 = 10_000_000_000.;
|
||||
pub const VIEWPORT_ZOOM_MIN_FRACTION_COVER: f64 = 0.01;
|
||||
pub const VIEWPORT_ZOOM_LEVELS: [f64; 74] = [
|
||||
0.0001, 0.000125, 0.00016, 0.0002, 0.00025, 0.00032, 0.0004, 0.0005, 0.00064, 0.0008, 0.001, 0.0016, 0.002, 0.0025, 0.0032, 0.004, 0.005, 0.0064, 0.008, 0.01, 0.01125, 0.015, 0.02, 0.025, 0.03,
|
||||
|
||||
@@ -16,8 +16,8 @@ use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
use graphene_std::raster::{
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior,
|
||||
NoiseType, RedGreenBlue, RelativeAbsolute, SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::text::TextAlign;
|
||||
@@ -33,7 +33,10 @@ use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowTechnique, Graphic};
|
||||
use graphene_std::{
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
|
||||
MaskMode,
|
||||
};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::ops::Range;
|
||||
@@ -436,6 +439,9 @@ macro_rules! inspectable_types {
|
||||
List<CellularDistanceFunction>,
|
||||
List<CellularReturnType>,
|
||||
List<DomainWarpType>,
|
||||
List<MandelbrotFractal>,
|
||||
List<MandelbrotExterior>,
|
||||
List<MandelbrotInterior>,
|
||||
List<RealTimeMode>,
|
||||
List<GridType>,
|
||||
List<GridTopology>,
|
||||
@@ -493,6 +499,9 @@ macro_rules! inspectable_types {
|
||||
Item<CellularDistanceFunction>,
|
||||
Item<CellularReturnType>,
|
||||
Item<DomainWarpType>,
|
||||
Item<MandelbrotFractal>,
|
||||
Item<MandelbrotExterior>,
|
||||
Item<MandelbrotInterior>,
|
||||
Item<RealTimeMode>,
|
||||
Item<GridType>,
|
||||
Item<GridTopology>,
|
||||
@@ -1259,8 +1268,13 @@ macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
Cover,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
BevelStyle,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
@@ -1291,6 +1305,9 @@ impl_table_item_layout_for_choice_enum!(
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
MandelbrotFractal,
|
||||
MandelbrotExterior,
|
||||
MandelbrotInterior,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
GridTopology,
|
||||
@@ -1437,6 +1454,11 @@ macro_rules! known_item_types {
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
@@ -1472,6 +1494,9 @@ macro_rules! known_item_types {
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
MandelbrotFractal,
|
||||
MandelbrotExterior,
|
||||
MandelbrotInterior,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
GridTopology,
|
||||
|
||||
@@ -319,9 +319,6 @@ pub enum DocumentMessage {
|
||||
UpdateTextFrames {
|
||||
text_frames: HashMap<NodeId, DAffine2>,
|
||||
},
|
||||
UpdateFootprintAreas {
|
||||
footprint_areas: HashMap<NodeId, DAffine2>,
|
||||
},
|
||||
UpdateClipTargets {
|
||||
clip_targets: HashSet<NodeId>,
|
||||
},
|
||||
|
||||
@@ -1914,9 +1914,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_text_frames(layer_text_frames);
|
||||
}
|
||||
DocumentMessage::UpdateFootprintAreas { footprint_areas } => {
|
||||
self.network_interface.update_footprint_areas(footprint_areas);
|
||||
}
|
||||
DocumentMessage::UpdateClipTargets { clip_targets } => {
|
||||
self.network_interface.update_clip_targets(clip_targets);
|
||||
}
|
||||
@@ -2159,15 +2156,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
} else {
|
||||
self.network_interface.document_bounds_document_space(true)
|
||||
};
|
||||
if let Some(bounds) = bounds {
|
||||
if self.document_ptz.flip {
|
||||
responses.add(NavigationMessage::CanvasFlip);
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
|
||||
responses.add(NavigationMessage::FitViewportToBounds { bounds, prevent_zoom_past_100: true });
|
||||
} else {
|
||||
warn!("Cannot zoom due to no bounds")
|
||||
// With nothing to frame, like a generator's pattern filling the plane, a tiny area at the origin is framed, which centers the origin at 100%
|
||||
let bounds = bounds.unwrap_or([DVec2::splat(-1.), DVec2::splat(1.)]);
|
||||
|
||||
if self.document_ptz.flip {
|
||||
responses.add(NavigationMessage::CanvasFlip);
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
|
||||
responses.add(NavigationMessage::FitViewportToBounds { bounds, prevent_zoom_past_100: true });
|
||||
}
|
||||
DocumentMessage::Noop => (),
|
||||
}
|
||||
@@ -4730,8 +4726,8 @@ pub fn navigation_controls(ptz: &PTZ, navigation_handler: &NavigationMessageHand
|
||||
vec![
|
||||
NumberInput::new(Some(navigation_handler.snapped_zoom(ptz.zoom()) * 100.))
|
||||
.unit("%")
|
||||
.min(0.000001)
|
||||
.max(1000000.)
|
||||
.min(crate::consts::VIEWPORT_ZOOM_SCALE_MIN * 100.)
|
||||
.max(crate::consts::VIEWPORT_ZOOM_SCALE_MAX * 100.)
|
||||
.tooltip_label(if node_graph { "Node Graph Zoom" } else { "Canvas Zoom" })
|
||||
.sizing(WidgetSizing::default().min_width(80))
|
||||
.on_update(|number_input: &NumberInput| {
|
||||
@@ -4798,6 +4794,69 @@ mod document_message_handler_tests {
|
||||
use crate::messages::portfolio::document::utility_types::misc::GridType;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn zooming_to_fit_nothing_centers_the_origin_at_100_percent() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
|
||||
|
||||
// Zoomed, panned, and tilted away in a document with nothing to frame
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 7. }).await;
|
||||
editor.handle_message(NavigationMessage::CanvasPan { delta: DVec2::new(300., -200.) }).await;
|
||||
editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 0.5 }).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::ZoomCanvasToFitAll).await;
|
||||
|
||||
let ptz = editor.active_document().document_ptz;
|
||||
assert_eq!(ptz.zoom(), 1.);
|
||||
assert_eq!(ptz.tilt(), 0.);
|
||||
assert!(ptz.pan.length() < 1e-9, "the view is panned by {}", ptz.pan);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn zooming_to_100_percent_reaches_it_with_only_a_tiny_shape_in_the_document() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
|
||||
|
||||
// A shape about a millionth of a unit across, drawn while zoomed far in
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 10_000_000. }).await;
|
||||
editor.draw_ellipse(100., 100., 110., 110.).await;
|
||||
assert!(editor.active_document().network_interface.document_bounds_document_space(true).is_some());
|
||||
|
||||
editor.handle_message(DocumentMessage::ZoomCanvasTo100Percent).await;
|
||||
assert_eq!(editor.active_document().document_ptz.zoom(), 1.);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wheeling_in_at_the_deepest_zoom_leaves_the_view_in_place() {
|
||||
use crate::consts::VIEWPORT_ZOOM_SCALE_MAX;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta};
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: VIEWPORT_ZOOM_SCALE_MAX }).await;
|
||||
let pan = editor.active_document().document_ptz.pan;
|
||||
|
||||
// Ctrl+wheel zooming in, which heads toward the pointer away from the viewport's center
|
||||
let editor_mouse_state = EditorPointerState {
|
||||
editor_position: DVec2::new(100., 100.),
|
||||
scroll_delta: ScrollDelta { x: 0., y: -100., z: 0. },
|
||||
..Default::default()
|
||||
};
|
||||
editor
|
||||
.input(InputPreprocessorMessage::WheelScroll {
|
||||
editor_mouse_state,
|
||||
modifier_keys: ModifierKeys::CONTROL,
|
||||
})
|
||||
.await;
|
||||
|
||||
let ptz = editor.active_document().document_ptz;
|
||||
assert_eq!(ptz.zoom(), VIEWPORT_ZOOM_SCALE_MAX);
|
||||
assert_eq!(ptz.pan, pan);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deleting_the_bottom_layer_leaves_the_layer_above_it_the_empty_stack_value() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -211,22 +211,36 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
}
|
||||
NavigationMessage::CanvasZoomDecrease { center_on_mouse } => {
|
||||
let document_bounds = if !graph_view_overlay_open {
|
||||
// TODO: Cache this in node graph coordinates and apply the transform to the rectangle to get viewport coordinates
|
||||
network_interface.document_bounds_viewport_space(true)
|
||||
} else {
|
||||
network_interface.graph_bounds_viewport_space(breadcrumb_network_path)
|
||||
};
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let new_scale = *VIEWPORT_ZOOM_LEVELS.iter().rev().find(|scale| **scale < ptz.zoom()).unwrap_or(&ptz.zoom());
|
||||
let new_scale = zoom_levels().take_while(|&scale| scale < ptz.zoom()).last().unwrap_or(ptz.zoom());
|
||||
let new_scale = (new_scale * Self::clamp_zoom(new_scale, document_bounds, old_zoom, viewport)).clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
|
||||
if center_on_mouse {
|
||||
responses.add(self.center_zoom(viewport.size().into(), new_scale / ptz.zoom(), ipp.mouse.position));
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasZoomSet { zoom_factor: new_scale });
|
||||
}
|
||||
NavigationMessage::CanvasZoomIncrease { center_on_mouse } => {
|
||||
let document_bounds = if !graph_view_overlay_open {
|
||||
// TODO: Cache this in node graph coordinates and apply the transform to the rectangle to get viewport coordinates
|
||||
network_interface.document_bounds_viewport_space(true)
|
||||
} else {
|
||||
network_interface.graph_bounds_viewport_space(breadcrumb_network_path)
|
||||
};
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let new_scale = *VIEWPORT_ZOOM_LEVELS.iter().find(|scale| **scale > ptz.zoom()).unwrap_or(&ptz.zoom());
|
||||
let new_scale = zoom_levels().find(|&scale| scale > ptz.zoom()).unwrap_or(ptz.zoom());
|
||||
let new_scale = (new_scale * Self::clamp_zoom(new_scale, document_bounds, old_zoom, viewport)).clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
|
||||
if center_on_mouse {
|
||||
responses.add(self.center_zoom(viewport.size().into(), new_scale / ptz.zoom(), ipp.mouse.position));
|
||||
}
|
||||
@@ -250,25 +264,18 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
|
||||
zoom_factor *= Self::clamp_zoom(ptz.zoom() * zoom_factor, document_bounds, old_zoom, viewport);
|
||||
|
||||
responses.add(self.center_zoom(viewport.size().into(), zoom_factor, ipp.mouse.position));
|
||||
responses.add(NavigationMessage::CanvasZoomSet {
|
||||
zoom_factor: ptz.zoom() * zoom_factor,
|
||||
});
|
||||
// Held to the zoom range before panning toward the pointer, so wheeling against a limit leaves the view in place
|
||||
let zoom = (ptz.zoom() * zoom_factor).clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
|
||||
responses.add(self.center_zoom(viewport.size().into(), zoom / ptz.zoom(), ipp.mouse.position));
|
||||
responses.add(NavigationMessage::CanvasZoomSet { zoom_factor: zoom });
|
||||
}
|
||||
// Sets exactly the zoom asked for, since the steps and gestures that keep the content from shrinking out of sight do so before sending it
|
||||
NavigationMessage::CanvasZoomSet { zoom_factor } => {
|
||||
let document_bounds = if !graph_view_overlay_open {
|
||||
// TODO: Cache this in node graph coordinates and apply the transform to the rectangle to get viewport coordinates
|
||||
network_interface.document_bounds_viewport_space(true)
|
||||
} else {
|
||||
network_interface.graph_bounds_viewport_space(breadcrumb_network_path)
|
||||
};
|
||||
let Some(ptz) = get_ptz_mut(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
log::error!("Could not get mutable PTZ in CanvasZoomSet");
|
||||
return;
|
||||
};
|
||||
let zoom = zoom_factor.clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX);
|
||||
let zoom = zoom * Self::clamp_zoom(zoom, document_bounds, old_zoom, viewport);
|
||||
ptz.set_zoom(zoom);
|
||||
ptz.set_zoom(zoom_factor.clamp(VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_SCALE_MAX));
|
||||
if graph_view_overlay_open {
|
||||
responses.add(NodeGraphMessage::UpdateGraphBarRight);
|
||||
} else {
|
||||
@@ -591,8 +598,31 @@ impl NavigationMessageHandler {
|
||||
|
||||
pub fn snapped_zoom(navigation_operation: &NavigationOperation, zoom: f64) -> f64 {
|
||||
if matches!(navigation_operation, NavigationOperation::Zoom { snap: true, .. }) {
|
||||
*VIEWPORT_ZOOM_LEVELS.iter().min_by(|a, b| (**a - zoom).abs().partial_cmp(&(**b - zoom).abs()).unwrap()).unwrap_or(&zoom)
|
||||
zoom_levels().min_by(|a, b| (a - zoom).abs().total_cmp(&(b - zoom).abs())).unwrap_or(zoom)
|
||||
} else {
|
||||
zoom
|
||||
}
|
||||
}
|
||||
|
||||
/// The preset zoom levels, ascending: the listed ones, then 1, 1.25, and 1.5625 times each power of two (as the list ends with) up to the deepest zoom.
|
||||
fn zoom_levels() -> impl Iterator<Item = f64> {
|
||||
let last_listed = VIEWPORT_ZOOM_LEVELS[VIEWPORT_ZOOM_LEVELS.len() - 1];
|
||||
let doubling_steps = (0..).flat_map(|power| [1., 1.25, 1.5625].map(|step| 2_f64.powi(power) * step));
|
||||
|
||||
VIEWPORT_ZOOM_LEVELS
|
||||
.into_iter()
|
||||
.chain(doubling_steps.skip_while(move |&level| level <= last_listed).take_while(|&level| level < VIEWPORT_ZOOM_SCALE_MAX))
|
||||
.chain([VIEWPORT_ZOOM_SCALE_MAX])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_zoom_levels_step_up_evenly_to_the_deepest_zoom() {
|
||||
let levels: Vec<f64> = zoom_levels().collect();
|
||||
assert!(levels.windows(2).all(|pair| pair[1] > pair[0] && pair[1] / pair[0] <= 1.6), "{levels:?}");
|
||||
assert_eq!(levels.last(), Some(&VIEWPORT_ZOOM_SCALE_MAX));
|
||||
}
|
||||
}
|
||||
@@ -5,19 +5,16 @@ use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
|
||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
|
||||
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
|
||||
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
@@ -40,6 +37,11 @@ impl NodeInspectorContext<'_> {
|
||||
let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
|
||||
let widget_override = input_inspector_row.widget_override.clone()?;
|
||||
|
||||
// Older documents store number and Vec2 widget settings this way, but they come from the definition's parameter
|
||||
if matches!(widget_override.as_str(), "number" | "vec2") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
|
||||
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||
return None;
|
||||
@@ -51,11 +53,11 @@ impl NodeInspectorContext<'_> {
|
||||
}
|
||||
|
||||
/// Input position of the location parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
/// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::DimensionsInput::INDEX;
|
||||
/// Input position of the control path parameter on the "Blend" network node template.
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = graphene_std::subgraphs::blend::PathInput::INDEX;
|
||||
|
||||
/// The key used to access definitions for a network node or proto node.
|
||||
/// For proto nodes, this is their [`ProtoNodeIdentifier`].
|
||||
@@ -107,8 +109,7 @@ pub struct DocumentNodeDefinition {
|
||||
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
|
||||
pub identifier: &'static str,
|
||||
|
||||
/// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly.
|
||||
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
|
||||
/// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
|
||||
pub version: u32,
|
||||
|
||||
/// The default [`NodeTemplate`] this definition instantiates.
|
||||
@@ -136,541 +137,9 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
|
||||
|
||||
/// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry).
|
||||
/// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built.
|
||||
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
||||
/// A proto node within a definition takes its input and output metadata from the node macro in NODE_METADATA, and its display name too unless the definition gives one.
|
||||
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let custom = vec![
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Custom Node",
|
||||
version: 1,
|
||||
category: "Routing",
|
||||
icon: Some("NodeCustomNode"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
nodes: [
|
||||
// Primary (bottom) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
// Secondary (left) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of layers below this one, which the content is placed above.").into(),
|
||||
("Content", "The artwork this layer adds to the stack as a single item.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Artboard",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
|
||||
NodeInput::import(item!(TaggedValue), 2),
|
||||
NodeInput::import(item!(TaggedValue), 3),
|
||||
NodeInput::import(item!(TaggedValue), 4),
|
||||
NodeInput::import(item!(TaggedValue), 5),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Artboard), true),
|
||||
NodeInput::type_default(list!(Graphic), true),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
|
||||
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of artboards below this one, which this artboard is placed above.").into(),
|
||||
("Content", "Graphics to include within the artboard.").into(),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Location",
|
||||
"Coordinate of the top-left corner of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "X".to_string(),
|
||||
y: "Y".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Dimensions",
|
||||
"Width and height of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "W".to_string(),
|
||||
y: "H".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())),
|
||||
("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Blend",
|
||||
version: 1,
|
||||
category: "Vector: Deform",
|
||||
icon: Some("NodeBlend"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(16), 0)],
|
||||
nodes: [
|
||||
// 0: Separate Paths (split the vector into its individual paths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::separate_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Count (number of subpaths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::count::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Max (clamp subpath count to at least 1 for empty path case)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Number (the integer count enters the network's decimal math)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(item!(i64), 1)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Multiply (total_instances = count × subpath_count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Subtract (count - 1, open subpath denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Read Index (current repetition index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Divide (index / count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
|
||||
..Default::default()
|
||||
},
|
||||
// 8: Floor (floor(index / count) = subpath index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(7), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 9: Modulo (index % count = local index within subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 10: Path Is Closed (check if current subpath is closed)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::switch::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
|
||||
..Default::default()
|
||||
},
|
||||
// 12: Divide (local_index / denominator = within-subpath fraction)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 14: Add (subpath_index + clamped fraction = progression)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::add::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 15: Morph (content, progression, reverse, distribution, path)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::morph::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::node(NodeId(14), 0),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
|
||||
NodeInput::import(item!(Vector), 4),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
|
||||
..Default::default()
|
||||
},
|
||||
// 16: Repeat
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 17: Max (clamp count to at least 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::Integer(10), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Content", "The vector objects to create intermediate shapes between.").into(),
|
||||
(
|
||||
"Count",
|
||||
"The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.",
|
||||
)
|
||||
.into(),
|
||||
("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(),
|
||||
("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(),
|
||||
(
|
||||
"Path",
|
||||
"An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.",
|
||||
)
|
||||
.into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Origins to Polyline",
|
||||
version: 1,
|
||||
category: "Vector: Path",
|
||||
icon: Some("NodeOriginsToPolyline"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(7), 0)],
|
||||
nodes: [
|
||||
// 0: Read Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Extract Transform
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::extract_transform::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Decompose Translation
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::decompose_translation::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Vector (auto-converts the decomposed translation into a single-anchor List<Vector>)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::as_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Flatten Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Map
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Combine Paths
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Points to Polyline
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::points_to_polyline::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::value(TaggedValue::Bool(false), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Vector), true)],
|
||||
input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()],
|
||||
output_names: vec!["Vector".to_string()],
|
||||
output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Load Image",
|
||||
version: 1,
|
||||
category: "Data: I/O",
|
||||
icon: Some("NodeLoadImage"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
|
||||
input_metadata: vec![
|
||||
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
|
||||
("URL", "The web address or local asset path of the image to load.").into(),
|
||||
],
|
||||
output_names: vec!["Image".to_string()],
|
||||
output_descriptions: vec!["The loaded image.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Loads an image from a given URL."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Regex Find",
|
||||
version: 1,
|
||||
category: "String: Regex",
|
||||
icon: Some("NodeRegexFind"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![
|
||||
// Primary output: the whole match (String)
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
// Secondary output: capture groups (List<String>), each item carries `start`/`end`/`name` attributes from `regex_find`
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
nodes: [
|
||||
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(item!(String), 0),
|
||||
NodeInput::import(item!(String), 1),
|
||||
NodeInput::import(item!(i64), 2),
|
||||
NodeInput::import(item!(bool), 3),
|
||||
NodeInput::import(item!(bool), 4),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::String(String::new()), true),
|
||||
NodeInput::value(TaggedValue::String(String::new()), false),
|
||||
NodeInput::value(TaggedValue::Integer(0), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("String", "The string to search within.").into(),
|
||||
("Pattern", "The regular expression pattern to search for.").into(),
|
||||
(
|
||||
"Match Index",
|
||||
"Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.",
|
||||
)
|
||||
.into(),
|
||||
("Case Insensitive", "Match letters regardless of case.").into(),
|
||||
("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(),
|
||||
],
|
||||
output_names: vec!["Match".to_string(), "Captures".to_string()],
|
||||
output_descriptions: vec![
|
||||
"The whole portion of the string matching the pattern, or empty if there is no match.".to_string(),
|
||||
"The text matched by each capture group in the pattern, in order.".to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed(
|
||||
r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#,
|
||||
),
|
||||
inspector: None,
|
||||
},
|
||||
];
|
||||
|
||||
document_node_derive::post_process_nodes(custom)
|
||||
document_node_derive::derive_definitions()
|
||||
}
|
||||
|
||||
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
|
||||
@@ -738,91 +207,10 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"number".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
if let Some(unit) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
{
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
if let Some(min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.min(min);
|
||||
}
|
||||
if let Some(max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.max(max);
|
||||
}
|
||||
if let Some(step) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "step", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.step(step);
|
||||
}
|
||||
if let Some(mode) = context.network_interface.input_data(&node_id, index, "mode", context.selection_network_path).map(|value| {
|
||||
let mode: NumberInputMode = serde_json::from_value(value.clone()).unwrap();
|
||||
mode
|
||||
}) {
|
||||
number_input = number_input.mode(mode);
|
||||
}
|
||||
if let Some(range_min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_min(Some(range_min));
|
||||
}
|
||||
if let Some(range_max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_max(Some(range_max));
|
||||
}
|
||||
if let Some(is_integer) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
{
|
||||
number_input = number_input.is_integer(is_integer);
|
||||
}
|
||||
let blank_assist = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "blank_assist", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get blank assist when displaying number input for node {node_id}, index {index}");
|
||||
true
|
||||
});
|
||||
|
||||
Ok(vec![LayoutGroup::row(node_inspector::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context),
|
||||
number_input,
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// The custom number input settings are only available on proto nodes
|
||||
"optional_f64".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
if let Some(field) = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
{
|
||||
if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) {
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
@@ -872,61 +260,51 @@ fn static_input_inspector() -> InputInspector {
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// A range slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them
|
||||
"wrapping_range_slider".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
let field = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().ok()?.get(proto_node_identifier)?.fields.get(index).cloned());
|
||||
|
||||
let mut number_input = NumberInput::default().mode_increment();
|
||||
let mut period = None;
|
||||
if let Some(field) = field {
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
if let Some(display_decimal_places) = field.number_display_decimal_places {
|
||||
number_input = number_input.display_decimal_places(display_decimal_places);
|
||||
}
|
||||
if let Some(number_step) = field.number_step {
|
||||
number_input = number_input.step(number_step);
|
||||
}
|
||||
period = field.number_soft_min.zip(field.number_soft_max);
|
||||
}
|
||||
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
let row = match period {
|
||||
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
|
||||
let default = node_inspector::definition_default_number(¶meter_widgets_info);
|
||||
node_inspector::wrapping_range_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
|
||||
}
|
||||
_ => {
|
||||
log::error!("A wrapping range slider needs finite soft bounds at both ends");
|
||||
node_inspector::number_widget(parameter_widgets_info, number_input)
|
||||
}
|
||||
};
|
||||
Ok(vec![LayoutGroup::row(row)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
|
||||
"type_choice".to_string(),
|
||||
Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
|
||||
);
|
||||
map.insert(
|
||||
"vec2".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let x = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "x", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get x for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let y = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "y", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get y for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let unit = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get unit for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let min = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64());
|
||||
let is_integer = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
&x,
|
||||
&y,
|
||||
&unit,
|
||||
min,
|
||||
is_integer,
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_scale".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -1077,6 +455,51 @@ fn static_input_inspector() -> InputInspector {
|
||||
Ok(vec![cellular_return_type])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"mandelbrot_inspector_frequency".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let tendrils_or_rays = node_inspector::query_mandelbrot_tendrils_or_rays(node_id, context)?;
|
||||
let frequency = node_inspector::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default().min(1.).max(64.).is_integer(true).disabled(!tendrils_or_rays),
|
||||
);
|
||||
Ok(vec![frequency.into()])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"mandelbrot_inspector_mandelbrot_slice".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mandelbrot_to_julia = node_inspector::query_mandelbrot_to_julia(node_id, context)?;
|
||||
let mandelbrot_slice = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
mandelbrot_slice,
|
||||
"X",
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"mandelbrot_inspector_julia_slice".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mandelbrot_to_julia = node_inspector::query_mandelbrot_to_julia(node_id, context)?;
|
||||
let julia_slice = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
julia_slice,
|
||||
"X",
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_cellular_jitter".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -1178,6 +601,8 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
" px",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
@@ -1192,6 +617,8 @@ fn static_input_inspector() -> InputInspector {
|
||||
"H",
|
||||
"x",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
@@ -1311,7 +738,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"vec2_uv".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false)])
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)])
|
||||
}),
|
||||
);
|
||||
map
|
||||
@@ -1559,6 +986,18 @@ mod test {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// A `#[graph]` node with an inner node that has no definition is left out of the catalog with only a logged error
|
||||
#[test]
|
||||
fn every_registered_graph_has_a_definition() {
|
||||
// Released before resolving, since building the catalog locks the registry too
|
||||
let identifiers: Vec<&str> = graphene_std::registry::GRAPH_METADATA.lock().unwrap().iter().map(|graph| graph.identifier).collect();
|
||||
assert!(!identifiers.is_empty(), "the `#[graph]` nodes in `graphene_std::subgraphs` should be registered");
|
||||
|
||||
for identifier in identifiers {
|
||||
assert!(resolve_network_node_type(identifier).is_some(), "the '{identifier}' graph should have a definition");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||
use glam::{DAffine2, UVec2};
|
||||
@@ -1699,21 +1138,36 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn every_definition_default_value_satisfies_its_constraint() {
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
let name = &definition.node_template.display_name;
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name);
|
||||
// Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too
|
||||
fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec<String>) {
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name);
|
||||
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() {
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() {
|
||||
if let Some(value) = input.as_value()
|
||||
&& !constraint.accepts_default_value(&value.ty())
|
||||
{
|
||||
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty()));
|
||||
}
|
||||
|
||||
let takes_nothing = matches!(constraint, InputTypeConstraint::Limited(types) if !types.is_empty() && types.iter().all(|ty| ty == "()"));
|
||||
if takes_nothing && matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }) {
|
||||
violations.push(format!("{name} input {index}: a wire feeds it, but it takes nothing"));
|
||||
}
|
||||
}
|
||||
|
||||
if let NodeTemplateImplementation::Network(network) = &node_template.implementation {
|
||||
for (node_id, inner) in &network.nodes {
|
||||
check(inner, &format!("{name}, node {node_id}"), violations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
check(&definition.node_template, &definition.node_template.display_name, &mut violations);
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1730,7 +1184,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(String)));
|
||||
@@ -1744,7 +1198,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode2() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
|
||||
@@ -1753,8 +1207,8 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn network() {
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let inner_network = NodeNetworkTemplate {
|
||||
|
||||
+421
-30
@@ -1,11 +1,17 @@
|
||||
use super::DocumentNodeDefinition;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride,
|
||||
};
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::registry::*;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
/// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs.
|
||||
pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let mut definitions_map = HashMap::new();
|
||||
|
||||
// Add the protonodes from the macro.
|
||||
@@ -75,16 +81,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
inputs,
|
||||
call_argument: input_type.clone(),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
||||
// TODO: Store information for input overrides in the node macro
|
||||
input_metadata: fields
|
||||
.iter()
|
||||
.map(|f| match f.widget_override {
|
||||
RegistryWidgetOverride::None => (f.name, f.description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
|
||||
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
|
||||
})
|
||||
.collect(),
|
||||
input_metadata: input_metadata(fields),
|
||||
output_names,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -96,25 +93,242 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
);
|
||||
}
|
||||
|
||||
// Add the hand-written network nodes to the map and add the metadata for their internal protonodes
|
||||
for mut network_node in custom {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
|
||||
}
|
||||
let graphs = GRAPH_METADATA.lock().unwrap().clone();
|
||||
add_graph_definitions(graphs, &mut definitions_map);
|
||||
|
||||
definitions_map
|
||||
}
|
||||
|
||||
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
|
||||
/// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports.
|
||||
/// The rest of a parameter's widget settings are read from its field when the Inspector draws it.
|
||||
fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let (name, description) = (field.name, field.description);
|
||||
match field.widget_override {
|
||||
RegistryWidgetOverride::None => (name, description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())),
|
||||
RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Why a `#[graph]` node has no definition yet, or can't have one.
|
||||
enum GraphDefinitionError {
|
||||
/// A node inside it has no definition, which may be another graph not yet added.
|
||||
MissingNode(String),
|
||||
/// The graph's wiring is invalid, so it's left out of the catalog.
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
/// Adds the nodes defined as subgraphs by `#[graph]`, each once the definitions of the nodes inside it exist.
|
||||
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
|
||||
let mut identifier_counts = HashMap::new();
|
||||
for graph in &graphs {
|
||||
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
|
||||
}
|
||||
let mut rejected = HashSet::new();
|
||||
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
|
||||
.into_iter()
|
||||
.filter(|graph| {
|
||||
let taken = identifier_counts[graph.identifier] > 1;
|
||||
if taken {
|
||||
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
}
|
||||
!taken
|
||||
})
|
||||
.map(|graph| (graph, String::new()))
|
||||
.collect();
|
||||
|
||||
loop {
|
||||
let pending_count = pending_graphs.len();
|
||||
|
||||
let mut ready = Vec::new();
|
||||
pending_graphs.retain_mut(|(graph, missing)| {
|
||||
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
|
||||
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
|
||||
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(inner_graph) = rejected_inner_graph {
|
||||
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
return false;
|
||||
}
|
||||
|
||||
match graph_definition(graph, definitions_map) {
|
||||
Ok(definition) => {
|
||||
ready.push(definition);
|
||||
false
|
||||
}
|
||||
Err(GraphDefinitionError::MissingNode(missing_node)) => {
|
||||
*missing = missing_node;
|
||||
true
|
||||
}
|
||||
Err(GraphDefinitionError::Invalid(reason)) => {
|
||||
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
for definition in ready {
|
||||
let definition = prepare_network_definition(definition, definitions_map);
|
||||
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
|
||||
}
|
||||
|
||||
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (graph, missing_node) in pending_graphs {
|
||||
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills a network definition's nested proto node metadata and points its network at the definition.
|
||||
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
network_node
|
||||
}
|
||||
|
||||
/// Builds the catalog definition of a node defined as a subgraph by `#[graph]`.
|
||||
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
|
||||
let mut nodes = HashMap::new();
|
||||
for (index, node) in graph.nodes.iter().enumerate() {
|
||||
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
|
||||
let (identifier, name) = match &node.implementation {
|
||||
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
|
||||
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
|
||||
};
|
||||
let Some(definition) = definitions_map.get(&identifier) else {
|
||||
return Err(GraphDefinitionError::MissingNode(name));
|
||||
};
|
||||
let mut template = definition.default_node_template();
|
||||
|
||||
if let Some(call_argument) = &node.call_argument {
|
||||
template.call_argument = call_argument.clone();
|
||||
}
|
||||
template.visible = !node.hidden;
|
||||
template.locked = node.locked;
|
||||
template.pinned = node.pinned;
|
||||
if let Some(display_name) = node.display_name {
|
||||
template.display_name = display_name.to_string();
|
||||
}
|
||||
|
||||
let position = node.position.map_or(IVec2::ZERO, |(x, y)| IVec2::new(x, y));
|
||||
template.node_type_metadata = if node.layer {
|
||||
NodeTypePersistentMetadata::layer(position)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(position)
|
||||
};
|
||||
|
||||
for (input_index, source) in &node.inputs {
|
||||
let Some(input) = template.inputs.get_mut(*input_index) else {
|
||||
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
|
||||
};
|
||||
|
||||
// An input the compiler fills in can't be set, which the macro already prevents for the graphs it builds
|
||||
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
|
||||
return Err(GraphDefinitionError::Invalid(format!(
|
||||
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
|
||||
)));
|
||||
}
|
||||
|
||||
*input = graph_input(source, input);
|
||||
}
|
||||
|
||||
nodes.insert(NodeId(index as u64), template);
|
||||
}
|
||||
|
||||
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
|
||||
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
|
||||
|
||||
let exports = graph.exports.iter().map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false))).collect();
|
||||
|
||||
Ok(DocumentNodeDefinition {
|
||||
identifier: graph.identifier,
|
||||
version: graph.version,
|
||||
category: graph.category,
|
||||
icon: graph.icon,
|
||||
description: Cow::Borrowed(graph.description),
|
||||
inspector: None,
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
|
||||
inputs,
|
||||
input_metadata: input_metadata(&graph.imports),
|
||||
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
|
||||
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
|
||||
node_type_metadata: if graph.layer {
|
||||
NodeTypePersistentMetadata::layer(IVec2::ZERO)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(IVec2::ZERO)
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
|
||||
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> NodeInput {
|
||||
match source {
|
||||
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
|
||||
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
|
||||
GraphInputSource::Value { value, exposed } => {
|
||||
let ty = match default {
|
||||
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
|
||||
NodeInput::Import { import_type, .. } => import_type.clone(),
|
||||
_ => generic!(T),
|
||||
};
|
||||
NodeInput::value(graph_value(value, &ty), exposed.unwrap_or(default.is_exposed()))
|
||||
}
|
||||
GraphInputSource::Scope(key) => NodeInput::scope(*key),
|
||||
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
|
||||
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
|
||||
fn element_type(ty: &Type) -> &Type {
|
||||
let mut element = ty;
|
||||
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
|
||||
element = inner;
|
||||
}
|
||||
element
|
||||
}
|
||||
|
||||
/// Converts a value written in a graph definition to the type of the input it feeds.
|
||||
fn graph_value(value: &GraphValue, ty: &Type) -> TaggedValue {
|
||||
// An integer literal feeds an integer input as an integer, and any other as a number
|
||||
let is_integer = *element_type(ty) == concrete!(i64);
|
||||
|
||||
match value {
|
||||
GraphValue::Integer(integer) if is_integer => TaggedValue::Integer(*integer),
|
||||
GraphValue::Integer(integer) => TaggedValue::Number(*integer as f64),
|
||||
GraphValue::Number(number) => TaggedValue::Number(*number),
|
||||
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
|
||||
GraphValue::String(string) => TaggedValue::String(string.clone()),
|
||||
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
|
||||
GraphValue::Color(color) => TaggedValue::Color(*color),
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
|
||||
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
match &mut node_template.implementation {
|
||||
NodeTemplateImplementation::Network(network_template) => {
|
||||
@@ -128,13 +342,190 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
|
||||
return;
|
||||
};
|
||||
|
||||
// A display name, lock, or pin the network's author gave the node is kept
|
||||
let definition_template = &definition.node_template;
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
if node_template.display_name.is_empty() {
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
}
|
||||
node_template.input_metadata = definition_template.input_metadata.clone();
|
||||
node_template.output_names = definition_template.output_names.clone();
|
||||
node_template.locked = definition_template.locked;
|
||||
node_template.pinned = definition_template.pinned;
|
||||
node_template.locked |= definition_template.locked;
|
||||
node_template.pinned |= definition_template.pinned;
|
||||
}
|
||||
NodeTemplateImplementation::Definition(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
|
||||
fn number_import() -> FieldMetadata {
|
||||
FieldMetadata {
|
||||
name: "Value",
|
||||
description: "",
|
||||
internal: false,
|
||||
exposed: true,
|
||||
widget_override: RegistryWidgetOverride::None,
|
||||
value_source: RegistryValueSource::None,
|
||||
default_colors: None,
|
||||
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
number_hard_max: None,
|
||||
number_mode_range: false,
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph exporting one node, which is fed by the given inputs.
|
||||
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
|
||||
GraphMetadata {
|
||||
identifier,
|
||||
category: "Test",
|
||||
icon: None,
|
||||
description: "",
|
||||
version: 1,
|
||||
layer: false,
|
||||
imports: vec![number_import()],
|
||||
exports: vec![GraphExportMetadata {
|
||||
name: "Out",
|
||||
description: "",
|
||||
source: GraphInputSource::Node { node: 0, output: 0 },
|
||||
}],
|
||||
nodes: vec![GraphNodeMetadata {
|
||||
implementation,
|
||||
inputs,
|
||||
position: None,
|
||||
layer: false,
|
||||
display_name: None,
|
||||
hidden: false,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
call_argument: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn from_import() -> Vec<(usize, GraphInputSource)> {
|
||||
let ty = Type::Item(Box::new(concrete!(f64)));
|
||||
vec![(0, GraphInputSource::Import { index: 0, ty })]
|
||||
}
|
||||
|
||||
/// The definitions a test graph builds on: only the As Number proto node.
|
||||
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
|
||||
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
|
||||
HashMap::from([(identifier, definition)])
|
||||
}
|
||||
|
||||
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
|
||||
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
|
||||
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
|
||||
let inner = one_node_graph("Test Inner", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![outer, inner], &mut definitions_map);
|
||||
|
||||
assert!(has_graph(&definitions_map, "Test Inner"));
|
||||
assert!(has_graph(&definitions_map, "Test Outer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
|
||||
let mut inputs = from_import();
|
||||
inputs.push((
|
||||
100,
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Number(1.),
|
||||
exposed: None,
|
||||
},
|
||||
));
|
||||
let graph = one_node_graph("Test Missing Input", math_nodes::as_number::IDENTIFIER.into(), inputs);
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Missing Input"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
|
||||
let first = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let second = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Twin"));
|
||||
assert!(!has_graph(&definitions_map, "Test Dependent"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_integer_value_takes_the_type_of_the_input_it_feeds() {
|
||||
let integer = Type::Item(Box::new(concrete!(i64)));
|
||||
let number = Type::Item(Box::new(concrete!(f64)));
|
||||
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &integer), TaggedValue::Integer(3)));
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &number), TaggedValue::Number(value) if value == 3.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_start_from_their_default_or_type() {
|
||||
let unit_primary = FieldMetadata {
|
||||
default_type: Some(concrete!(())),
|
||||
..number_import()
|
||||
};
|
||||
let with_default = FieldMetadata {
|
||||
value_source: RegistryValueSource::Default("2.5"),
|
||||
..number_import()
|
||||
};
|
||||
let graph = GraphMetadata {
|
||||
imports: vec![unit_primary, with_default],
|
||||
..one_node_graph("Test Defaults", math_nodes::as_number::IDENTIFIER.into(), from_import())
|
||||
};
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
|
||||
|
||||
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
|
||||
assert!(!inputs[0].is_exposed());
|
||||
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
|
||||
assert!(inputs[1].is_exposed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_nodes_widget_settings_come_from_its_import() {
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
|
||||
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
|
||||
|
||||
let location = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
let field = document
|
||||
.network_interface
|
||||
.field_metadata(&node_id, location, &[])
|
||||
.expect("the location input should have its import's settings");
|
||||
assert_eq!(field.labels, Some(("X", "Y")));
|
||||
assert!(field.integer);
|
||||
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,11 @@ pub enum NodeGraphMessage {
|
||||
xy: Option<(i32, i32)>,
|
||||
add_transaction: bool,
|
||||
},
|
||||
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
|
||||
CreateEmptySubgraph {
|
||||
node_id: Option<NodeId>,
|
||||
xy: Option<(i32, i32)>,
|
||||
},
|
||||
CreateWire {
|
||||
output_connector: OutputConnector,
|
||||
input_connector: InputConnector,
|
||||
@@ -383,6 +388,7 @@ impl NodeGraphMessage {
|
||||
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
||||
Self::AddNodes { .. }
|
||||
| Self::CreateNodeFromContextMenu { .. }
|
||||
| Self::CreateEmptySubgraph { .. }
|
||||
| Self::CreateWire { .. }
|
||||
| Self::CreateWires { .. }
|
||||
| Self::ConnectUpstreamOutputToInput { .. }
|
||||
|
||||
@@ -5,13 +5,14 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
|
||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
|
||||
TransactionStatus,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||
@@ -422,6 +423,23 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
});
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
|
||||
let node_id = node_id.unwrap_or_else(NodeId::new);
|
||||
let (x, y) = xy.unwrap_or_else(|| {
|
||||
network_interface
|
||||
.node_graph_ptz(breadcrumb_network_path)
|
||||
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id,
|
||||
node_template: Box::new(NodeTemplate::empty_subgraph()),
|
||||
});
|
||||
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
||||
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
||||
log::error!("Failed to find upstream node for downstream_input");
|
||||
@@ -769,24 +787,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
}
|
||||
|
||||
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
|
||||
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
|
||||
let encapsulating_node_id = NodeId::new();
|
||||
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
|
||||
let mut subgraph_template = NodeTemplate::empty_subgraph();
|
||||
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
||||
log::error!("Could not get center of selected_nodes");
|
||||
return;
|
||||
};
|
||||
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
||||
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id: encapsulating_node_id,
|
||||
node_template: Box::new(default_node_template),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: encapsulating_node_id,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
alias: "Untitled Node".to_string(),
|
||||
node_template: Box::new(subgraph_template),
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
||||
@@ -3426,6 +3439,13 @@ impl NodeGraphMessageHandler {
|
||||
})
|
||||
.disabled(read_only)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextButton::new("New Custom Node")
|
||||
.tooltip_label("New Custom Node")
|
||||
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
|
||||
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
|
||||
.disabled(read_only)
|
||||
.widget_instance(),
|
||||
//
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
//
|
||||
|
||||
@@ -23,8 +23,8 @@ use graph_craft::{Type, concrete, item};
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::{
|
||||
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, MandelbrotExterior, MandelbrotFractal,
|
||||
MandelbrotInterior, NoiseType, RedGreenBlue, RelativeAbsolute, SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, GlowTechnique, Graphic, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -238,7 +238,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
||||
}
|
||||
|
||||
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ParameterOptions {
|
||||
pub soft_min: Option<f64>,
|
||||
pub soft_max: Option<f64>,
|
||||
@@ -250,6 +250,50 @@ pub(crate) struct ParameterOptions {
|
||||
pub unit: Option<&'static str>,
|
||||
pub display_decimal_places: Option<u32>,
|
||||
pub step: Option<f64>,
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
pub integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for ParameterOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
soft_min: None,
|
||||
soft_max: None,
|
||||
hard_min: None,
|
||||
hard_max: None,
|
||||
slider: false,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
unit: None,
|
||||
display_decimal_places: None,
|
||||
step: None,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ParameterOptions {
|
||||
/// The options a proto node's field or a graph's import gives its widget.
|
||||
pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self {
|
||||
Self {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
labels: field.labels,
|
||||
integer: field.integer,
|
||||
blank_assist: field.blank_assist,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
||||
@@ -268,10 +312,18 @@ impl SliderRange {
|
||||
fn value(self, position: f64) -> f64 {
|
||||
(self.min + position * (self.max - self.min)).clamp(self.min, self.max)
|
||||
}
|
||||
|
||||
/// The `value` moved into the bounds by whole periods of their width, for a periodic number like an angle.
|
||||
fn wrapped(self, value: f64) -> f64 {
|
||||
if (self.min..=self.max).contains(&value) {
|
||||
return value;
|
||||
}
|
||||
self.min + (value - self.min).rem_euclid(self.max - self.min)
|
||||
}
|
||||
}
|
||||
|
||||
/// The number a parameter's definition gives it by default, which a slider's double-click restores.
|
||||
fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
|
||||
pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
|
||||
let identifier = parameter_widgets_info
|
||||
.network_interface
|
||||
.reference(¶meter_widgets_info.node_id, parameter_widgets_info.selection_network_path)?;
|
||||
@@ -295,9 +347,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
unit,
|
||||
display_decimal_places,
|
||||
step,
|
||||
labels,
|
||||
integer,
|
||||
blank_assist,
|
||||
} = options;
|
||||
|
||||
let mut number_input = NumberInput::default();
|
||||
let mut number_input = NumberInput::default().is_integer(integer);
|
||||
if slider {
|
||||
number_input = number_input.mode_range();
|
||||
}
|
||||
@@ -340,7 +395,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
}
|
||||
};
|
||||
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
|
||||
|
||||
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
|
||||
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
|
||||
@@ -384,10 +439,14 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
true => text_area_widget(default_info).into(),
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false),
|
||||
Some(x) if id_is::<DVec2>(x) => {
|
||||
let (x_label, y_label) = labels.unwrap_or(("X", "Y"));
|
||||
vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false)
|
||||
}
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
@@ -419,6 +478,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
Some(x) if id_is::<MandelbrotFractal>(x) => enum_choice::<MandelbrotFractal>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MandelbrotExterior>(x) => enum_choice::<MandelbrotExterior>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MandelbrotInterior>(x) => enum_choice::<MandelbrotInterior>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).inspector_row(),
|
||||
@@ -439,6 +501,11 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -877,7 +944,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
||||
}
|
||||
}
|
||||
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool) -> LayoutGroup {
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, max: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
@@ -892,8 +959,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -902,8 +970,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -916,8 +985,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -926,8 +996,9 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
@@ -1637,6 +1708,38 @@ pub fn query_node_and_input_info<'a>(node_id: NodeId, input_index: usize, contex
|
||||
Ok((document_node, name, description))
|
||||
}
|
||||
|
||||
/// Whether a Mandelbrot node's exterior or interior has tendrils or rays for Frequency to set, which a wired one may.
|
||||
pub fn query_mandelbrot_tendrils_or_rays(node_id: NodeId, context: &NodeInspectorContext) -> Result<bool, String> {
|
||||
let document_node = get_document_node(node_id, context)?;
|
||||
|
||||
let exterior = document_node.inputs.iter().find_map(|input| match input.as_value() {
|
||||
Some(&TaggedValue::MandelbrotExterior(exterior)) => Some(exterior),
|
||||
_ => None,
|
||||
});
|
||||
let interior = document_node.inputs.iter().find_map(|input| match input.as_value() {
|
||||
Some(&TaggedValue::MandelbrotInterior(interior)) => Some(interior),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
let exterior_uses_frequency = matches!(exterior, None | Some(MandelbrotExterior::Tendrils | MandelbrotExterior::Rays));
|
||||
let interior_uses_frequency = matches!(interior, None | Some(MandelbrotInterior::Rays));
|
||||
Ok(exterior_uses_frequency || interior_uses_frequency)
|
||||
}
|
||||
|
||||
/// A Mandelbrot node's Mandelbrot-to-Julia percentage, unless it's wired.
|
||||
pub fn query_mandelbrot_to_julia(node_id: NodeId, context: &NodeInspectorContext) -> Result<Option<f64>, String> {
|
||||
let document_node = get_document_node(node_id, context)?;
|
||||
Ok(
|
||||
match document_node
|
||||
.input(graphene_std::raster_nodes::std_nodes::mandelbrot::MandelbrotToJuliaInput)
|
||||
.and_then(|input| input.as_value())
|
||||
{
|
||||
Some(&TaggedValue::Number(percent)) => Some(percent),
|
||||
_ => None,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn query_noise_pattern_state(node_id: NodeId, context: &NodeInspectorContext) -> Result<(bool, bool, bool, bool, bool, bool), String> {
|
||||
let document_node = get_document_node(node_id, context)?;
|
||||
let current_noise_type = document_node.inputs.iter().find_map(|input| match input.as_value() {
|
||||
@@ -2338,13 +2441,14 @@ fn value_slider(
|
||||
}
|
||||
|
||||
/// A row with a range slider and a 60px number input for the number at `parameter_widgets_info`. The slider's 0..1 position maps
|
||||
/// to the number through `position_of` and `value_at`, and double-click restores `default`.
|
||||
/// to the number through `position_of` and `value_at`, a typed number is stored as `typed_value` gives it, and double-click restores `default`.
|
||||
fn slider_row(
|
||||
parameter_widgets_info: ParameterWidgetsInfo,
|
||||
number_props: NumberInput,
|
||||
default: Option<f64>,
|
||||
position_of: impl Fn(f64) -> f64,
|
||||
value_at: impl Fn(f64) -> f64 + 'static + Send + Sync,
|
||||
typed_value: impl Fn(f64) -> f64 + 'static + Send + Sync,
|
||||
) -> Vec<WidgetInstance> {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
@@ -2377,7 +2481,7 @@ fn slider_row(
|
||||
number_props
|
||||
.value(Some(current))
|
||||
.sizing(WidgetSizing::fixed(60))
|
||||
.on_update(update_value_at_index(move |x: &NumberInput| tagged_value(x.value.unwrap_or_default()), node_id, index))
|
||||
.on_update(update_value_at_index(move |x: &NumberInput| tagged_value(typed_value(x.value.unwrap_or_default())), node_id, index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
@@ -2393,6 +2497,19 @@ pub(crate) fn range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo,
|
||||
slider.default,
|
||||
move |value| slider.position(value),
|
||||
move |position| slider.value(position),
|
||||
|value| value,
|
||||
)
|
||||
}
|
||||
|
||||
/// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them.
|
||||
pub(crate) fn wrapping_range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||
slider_row(
|
||||
parameter_widgets_info,
|
||||
number_props,
|
||||
slider.default,
|
||||
move |value| slider.position(slider.wrapped(value)),
|
||||
move |position| slider.value(position),
|
||||
move |value| slider.wrapped(value),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2721,10 +2838,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
||||
NumberInput::default().label("H").min(0.).unit(" px"),
|
||||
));
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false);
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false);
|
||||
widgets.extend([spacing, angles]);
|
||||
} else {
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false);
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
|
||||
widgets.push(spacing);
|
||||
}
|
||||
}
|
||||
@@ -2864,6 +2981,7 @@ pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
||||
Some(1.),
|
||||
|gamma| MarkerScale::Gamma.position(gamma),
|
||||
|position| MarkerScale::Gamma.value(position),
|
||||
|gamma| gamma,
|
||||
);
|
||||
|
||||
vec![LayoutGroup::row(exposure), LayoutGroup::row(offset), LayoutGroup::row(gamma_correction)]
|
||||
@@ -3186,40 +3304,20 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
}
|
||||
|
||||
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
|
||||
let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path);
|
||||
let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default();
|
||||
|
||||
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
|
||||
log::error!("Could not get implementation for node {node_id}");
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut options = ParameterOptions::default();
|
||||
let input_type = match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||
let proto_node_identifier = proto_node_identifier.clone();
|
||||
|
||||
let mut default_type = None;
|
||||
if let Some(field) = graphene_std::registry::NODE_METADATA
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
options = ParameterOptions {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
};
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
if let Some(default) = default_type {
|
||||
if let Some(default) = field.and_then(|field| field.default_type) {
|
||||
break 'early_return default;
|
||||
}
|
||||
|
||||
@@ -3235,12 +3333,21 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
let Some(input_type) = input_type else { return Vec::new() };
|
||||
input_type.clone()
|
||||
}
|
||||
_ => context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.unwrap_or(concrete!(())),
|
||||
_ => {
|
||||
// A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph
|
||||
let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
|
||||
Type::Item(element) => *element,
|
||||
declared_type => declared_type,
|
||||
});
|
||||
|
||||
context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.or(declared_type)
|
||||
.unwrap_or(concrete!(()))
|
||||
}
|
||||
};
|
||||
|
||||
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
|
||||
|
||||
@@ -638,6 +638,73 @@ fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static
|
||||
VelloSceneBuilder::new(size.x as u16, size.y as u16, Affine::IDENTITY, MAX_TEXTURE_SIZE)
|
||||
}
|
||||
|
||||
/// How closely the segments that [`pieces_in_view`] walks follow an overlay's curves, in logical pixels.
|
||||
const OVERLAY_SHAPE_TOLERANCE: f64 = 0.1;
|
||||
|
||||
/// Whether `outer` contains all of `inner`.
|
||||
fn rect_contains(outer: kurbo::Rect, inner: kurbo::Rect) -> bool {
|
||||
inner.x0 >= outer.x0 && inner.y0 >= outer.y0 && inner.x1 <= outer.x1 && inner.y1 <= outer.y1
|
||||
}
|
||||
|
||||
/// The parts of `path` that may show within `visible`, each with how far along its subpath it starts.
|
||||
/// A segment crossing the edge of `visible` is split in half until each half lies inside or outside it, so one far larger than the viewport costs only the log of its size.
|
||||
fn pieces_in_view(path: &BezPath, visible: kurbo::Rect) -> Vec<(f64, BezPath)> {
|
||||
// Halves this small are kept whole, as are those split this many times
|
||||
const SMALLEST_SPLIT: f64 = 1.;
|
||||
const MAX_SPLITS: u32 = 64;
|
||||
const ARC_LENGTH_ACCURACY: f64 = 1e-3;
|
||||
|
||||
let overlaps = |bounds: kurbo::Rect| bounds.x0 <= visible.x1 && bounds.x1 >= visible.x0 && bounds.y0 <= visible.y1 && bounds.y1 >= visible.y0;
|
||||
|
||||
let mut pieces: Vec<(f64, BezPath)> = Vec::new();
|
||||
let (mut previous, mut subpath_start) = (kurbo::Point::ZERO, kurbo::Point::ZERO);
|
||||
let mut distance = 0.;
|
||||
// Whether the last piece ends where the next kept segment starts, so that segment extends it
|
||||
let mut continuing = false;
|
||||
|
||||
for element in path.elements() {
|
||||
let segment = match *element {
|
||||
kurbo::PathEl::MoveTo(point) => {
|
||||
(previous, subpath_start, distance, continuing) = (point, point, 0., false);
|
||||
continue;
|
||||
}
|
||||
kurbo::PathEl::LineTo(point) => PathSeg::Line(kurbo::Line::new(previous, point)),
|
||||
kurbo::PathEl::QuadTo(control, point) => PathSeg::Quad(kurbo::QuadBez::new(previous, control, point)),
|
||||
kurbo::PathEl::CurveTo(control_start, control_end, point) => PathSeg::Cubic(kurbo::CubicBez::new(previous, control_start, control_end, point)),
|
||||
kurbo::PathEl::ClosePath => PathSeg::Line(kurbo::Line::new(previous, subpath_start)),
|
||||
};
|
||||
previous = segment.end();
|
||||
|
||||
// Halves wait on a stack, the second beneath the first, so they're visited in order along the path
|
||||
let mut pending = vec![(segment, 0)];
|
||||
while let Some((segment, splits)) = pending.pop() {
|
||||
let bounds = kurbo::Shape::bounding_box(&segment);
|
||||
let kept = overlaps(bounds);
|
||||
if kept && !rect_contains(visible, bounds) && bounds.width().max(bounds.height()) > SMALLEST_SPLIT && splits < MAX_SPLITS {
|
||||
let (first, second) = segment.subdivide();
|
||||
pending.push((second, splits + 1));
|
||||
pending.push((first, splits + 1));
|
||||
continue;
|
||||
}
|
||||
|
||||
if kept {
|
||||
if !continuing {
|
||||
let mut piece = BezPath::new();
|
||||
piece.move_to(segment.start());
|
||||
pieces.push((distance, piece));
|
||||
}
|
||||
if let Some((_, piece)) = pieces.last_mut() {
|
||||
piece.push(segment.as_path_el());
|
||||
}
|
||||
}
|
||||
continuing = kept;
|
||||
distance += kurbo::ParamCurveArclen::arclen(&segment, ARC_LENGTH_ACCURACY);
|
||||
}
|
||||
}
|
||||
|
||||
pieces
|
||||
}
|
||||
|
||||
impl OverlayContextInternal {
|
||||
fn new(viewport: ViewportMessageHandler) -> Self {
|
||||
Self {
|
||||
@@ -715,7 +782,7 @@ impl OverlayContextInternal {
|
||||
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap]);
|
||||
}
|
||||
|
||||
self.scene.stroke(&stroke, transform, Self::parse_color(stroke_color), None, &path);
|
||||
self.stroke_in_view(&stroke, Self::parse_color(stroke_color), &path);
|
||||
}
|
||||
|
||||
fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
|
||||
@@ -724,8 +791,6 @@ impl OverlayContextInternal {
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn dashed_line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
let transform = self.get_transform();
|
||||
|
||||
let start = self.snap_to_physical_pixel_center(start);
|
||||
let end = self.snap_to_physical_pixel_center(end);
|
||||
|
||||
@@ -740,7 +805,7 @@ impl OverlayContextInternal {
|
||||
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap]);
|
||||
}
|
||||
|
||||
self.scene.stroke(&stroke, transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &path);
|
||||
self.stroke_in_view(&stroke, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), &path);
|
||||
}
|
||||
|
||||
fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
@@ -860,6 +925,26 @@ impl OverlayContextInternal {
|
||||
kurbo::Affine::scale(self.viewport.scale())
|
||||
}
|
||||
|
||||
/// Strokes `shape`, given in logical pixels, dashing only the parts near the viewport when the stroke is dashed, since a shape reaching far past it
|
||||
/// (as deep zoom makes them) would have more dashes than memory holds. Each part keeps the dash phase it has along the whole shape.
|
||||
fn stroke_in_view(&mut self, stroke: &kurbo::Stroke, color: peniko::Color, shape: &impl kurbo::Shape) {
|
||||
let transform = self.get_transform();
|
||||
|
||||
let margin = stroke.width + 1.;
|
||||
let size = self.viewport.size().into_dvec2();
|
||||
let visible = kurbo::Rect::new(-margin, -margin, size.x + margin, size.y + margin);
|
||||
|
||||
if stroke.dash_pattern.is_empty() || rect_contains(visible, shape.bounding_box()) {
|
||||
self.scene.stroke(stroke, transform, color, None, shape);
|
||||
return;
|
||||
}
|
||||
|
||||
for (distance, piece) in pieces_in_view(&shape.to_path(OVERLAY_SHAPE_TOLERANCE), visible) {
|
||||
let piece_stroke = stroke.clone().with_dashes(stroke.dash_offset + distance, stroke.dash_pattern.iter().copied());
|
||||
self.scene.stroke(&piece_stroke, transform, color, None, &piece);
|
||||
}
|
||||
}
|
||||
|
||||
fn square(&mut self, position: DVec2, size: Option<f64>, color_fill: Option<&str>, color_stroke: Option<&str>) {
|
||||
let size = size.unwrap_or(MANIPULATOR_GROUP_MARKER_SIZE);
|
||||
let color_fill = color_fill.unwrap_or(COLOR_OVERLAY_WHITE);
|
||||
@@ -940,7 +1025,7 @@ impl OverlayContextInternal {
|
||||
if let Some(dash_width) = dash_width {
|
||||
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap_width.unwrap_or(1.)]);
|
||||
}
|
||||
self.scene.stroke(&stroke, transform, Self::parse_color(color_stroke.unwrap_or(COLOR_OVERLAY_BLUE)), None, &arc);
|
||||
self.stroke_in_view(&stroke, Self::parse_color(color_stroke.unwrap_or(COLOR_OVERLAY_BLUE)), &arc);
|
||||
}
|
||||
|
||||
fn draw_arc(&mut self, center: DVec2, radius: f64, start_from: f64, end_at: f64) {
|
||||
@@ -1431,3 +1516,39 @@ impl OverlayContextInternal {
|
||||
(physical_corner / scale, physical_size / scale)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const VISIBLE: kurbo::Rect = kurbo::Rect::new(0., 0., 800., 600.);
|
||||
|
||||
#[test]
|
||||
fn a_huge_line_keeps_only_its_part_in_view_at_its_distance_along_the_line() {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((-1e12, 300.));
|
||||
path.line_to((1e12, 300.));
|
||||
|
||||
let pieces = pieces_in_view(&path, VISIBLE);
|
||||
assert_eq!(pieces.len(), 1);
|
||||
|
||||
// The piece starts as far along as its start lies from the line's, so its dashes line up with the whole line's
|
||||
let (distance, piece) = &pieces[0];
|
||||
let start = piece.elements()[0].end_point().unwrap_or_default();
|
||||
assert!((-2.0..=0.).contains(&start.x), "the piece starts at {start:?}");
|
||||
assert!((distance - (start.x + 1e12)).abs() < 1e-3, "the piece starts {distance} along the line");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_circle_through_the_view_keeps_a_few_short_pieces() {
|
||||
let radius = 1e12;
|
||||
let circle = kurbo::Circle::new((400. - radius, 300.), radius);
|
||||
|
||||
// The circle's path starts at its rightmost point, in view, so the part in view is split between its start and end
|
||||
let pieces = pieces_in_view(&kurbo::Shape::to_path(&circle, OVERLAY_SHAPE_TOLERANCE), VISIBLE);
|
||||
assert!((1..=2).contains(&pieces.len()), "{} pieces", pieces.len());
|
||||
|
||||
let elements: usize = pieces.iter().map(|(_, piece)| piece.elements().len()).sum();
|
||||
assert!(elements < 1000, "{elements} elements");
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,6 @@ pub struct ResourceMessageHandler {
|
||||
pub embedded: EmbeddedResources,
|
||||
#[serde(skip)]
|
||||
pending_resolves: HashSet<ResourceId>,
|
||||
/// Resources that failed to load, which rendering no longer waits on, even during a retry.
|
||||
#[serde(skip)]
|
||||
failed_resolves: HashSet<ResourceId>,
|
||||
}
|
||||
@@ -219,8 +218,6 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
ResourceMessage::ResolveFailed { resource_id } => {
|
||||
self.pending_resolves.remove(&resource_id);
|
||||
self.failed_resolves.insert(resource_id);
|
||||
|
||||
// Rendering stops waiting on the resource and draws a fallback in its place
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
@@ -236,20 +233,6 @@ impl ResourceMessageHandler {
|
||||
self.registry.is_empty() && self.embedded.is_empty()
|
||||
}
|
||||
|
||||
/// Whether a resource lacks its data and hasn't failed to load, which rendering waits for.
|
||||
pub fn awaiting_resources(&self) -> bool {
|
||||
self.registry.unresolved().any(|info| !self.failed_resolves.contains(&info.id))
|
||||
}
|
||||
|
||||
/// Changes whenever a resource gains, loses, or changes its data. Summed per resource since the registry's order isn't stable. O(resolved resources).
|
||||
pub fn resolved_hash(&self) -> u64 {
|
||||
self.registry.resolved().fold(0, |sum, info| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(info.id, info.hash).hash(&mut hasher);
|
||||
sum.wrapping_add(hasher.finish())
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn embed_resources(&mut self, resources_load_handle: Box<dyn LoadResource>) {
|
||||
let embedded = self
|
||||
.registry
|
||||
@@ -275,6 +258,18 @@ impl ResourceMessageHandler {
|
||||
self.registry.delete(&id);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn awaiting_resources(&self) -> bool {
|
||||
self.registry.unresolved().any(|info| !self.failed_resolves.contains(&info.id))
|
||||
}
|
||||
|
||||
pub fn resolved_hash(&self) -> u64 {
|
||||
self.registry.resolved().fold(0, |sum, info| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(info.id, info.hash).hash(&mut hasher);
|
||||
sum.wrapping_add(hasher.finish())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
|
||||
@@ -46,8 +46,6 @@ pub struct DocumentMetadata {
|
||||
pub text_frames: HashMap<LayerNodeIdentifier, DAffine2>,
|
||||
pub clip_targets: HashSet<NodeId>,
|
||||
pub vector_modify: HashMap<NodeId, VectorGeometry>,
|
||||
/// Per node with a footprint input, the unit square mapped onto its area in document space.
|
||||
pub footprint_areas: HashMap<NodeId, DAffine2>,
|
||||
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
|
||||
/// This provides accurate SegmentIds for layers without explicit Path nodes.
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
|
||||
|
||||
@@ -57,7 +57,6 @@ use crate::messages::portfolio::document::utility_types::network_interface::reso
|
||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
|
||||
use deserialization::deserialize_node_persistent_metadata;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::Type;
|
||||
@@ -72,7 +71,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
|
||||
use graphene_std::vector::{Vector, VectorModificationType};
|
||||
use kurbo::BezPath;
|
||||
use memo_network::MemoNetwork;
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::Hash;
|
||||
use std::ops::Deref;
|
||||
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
use super::template::NodeTemplateImplementation;
|
||||
use super::template::{NodeTemplate, NodeTemplateImplementation};
|
||||
use super::{InputConnector, OutputConnector, catalog};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
||||
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
|
||||
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
||||
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
||||
|
||||
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
|
||||
let custom = NodeId::new();
|
||||
let blend = NodeId::new();
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]);
|
||||
interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
|
||||
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
||||
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
||||
panic!("the Blend should name a table entry")
|
||||
|
||||
+18
-6
@@ -2614,7 +2614,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir
|
||||
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
|
||||
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
let shaken = editor
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0)
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0)
|
||||
.await;
|
||||
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
|
||||
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
|
||||
@@ -3119,7 +3119,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let path = [subgraph];
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
|
||||
@@ -3506,7 +3506,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
|
||||
|
||||
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
||||
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
editor.handle_message(NodeGraphMessage::AddImport).await;
|
||||
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
||||
@@ -4041,18 +4041,30 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_new_subgraph_is_its_own_definition() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
|
||||
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
|
||||
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cannot_preview_node_without_outputs() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
|
||||
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
|
||||
assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
|
||||
|
||||
// Attempting to toggle preview on a node without outputs should not enable previewing
|
||||
network_interface.toggle_preview(custom_node, &[]);
|
||||
network_interface.toggle_preview(subgraph, &[]);
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
use super::*;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
|
||||
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
|
||||
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
|
||||
@@ -802,7 +799,7 @@ impl NodeNetworkInterface {
|
||||
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
||||
}
|
||||
|
||||
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
|
||||
/// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
|
||||
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
||||
self.reference(node_id, network_path)
|
||||
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
||||
@@ -829,17 +826,27 @@ impl NodeNetworkInterface {
|
||||
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
|
||||
}
|
||||
|
||||
/// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph.
|
||||
/// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
||||
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
|
||||
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
|
||||
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
|
||||
}
|
||||
|
||||
node_metadata
|
||||
.get(proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(index))
|
||||
.is_some_and(|field| field.internal)
|
||||
/// The metadata the node macro records for a proto node's parameter, or the `#[graph]` macro for a graph node's import.
|
||||
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
|
||||
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
|
||||
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
|
||||
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
|
||||
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
|
||||
}
|
||||
|
||||
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
|
||||
return None;
|
||||
};
|
||||
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
|
||||
|
||||
let graphs = graphene_std::registry::GRAPH_METADATA.lock().ok()?;
|
||||
let field = graphs.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
|
||||
(field.name == input_name).then(|| field.clone())
|
||||
}
|
||||
|
||||
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
|
||||
@@ -875,16 +882,16 @@ impl NodeNetworkInterface {
|
||||
node.set_widget_override(index, widget_override);
|
||||
}
|
||||
|
||||
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
|
||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
||||
.unwrap_or_else(|| "Custom Node".to_string())
|
||||
.unwrap_or_else(|| "Subgraph".to_string())
|
||||
}
|
||||
|
||||
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
||||
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
||||
.unwrap_or_else(|| "Custom Node".to_string())
|
||||
.unwrap_or_else(|| "Subgraph".to_string())
|
||||
}
|
||||
|
||||
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
@@ -1079,7 +1086,7 @@ impl NodeNetworkInterface {
|
||||
/// Whether the artboard layer clips the content inside it to its bounds.
|
||||
fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool {
|
||||
self.document_node(&artboard.to_node(), &[])
|
||||
.and_then(|artboard| artboard.inputs.get(ARTBOARD_CLIP_INPUT_INDEX))
|
||||
.and_then(|artboard| artboard.inputs.get(graphene_std::subgraphs::artboard::ClipInput::INDEX))
|
||||
.is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true)))
|
||||
}
|
||||
|
||||
|
||||
@@ -138,7 +138,6 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.upstream_footprints.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.local_transforms.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.vector_modify.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.footprint_areas.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.click_targets.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
self.document_metadata.outlines.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
self.document_metadata.text_frames.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
@@ -190,11 +189,6 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.vector_modify = new_vector_modify;
|
||||
}
|
||||
|
||||
/// Update the cached document space areas of the nodes with a footprint input
|
||||
pub fn update_footprint_areas(&mut self, new_footprint_areas: HashMap<NodeId, DAffine2>) {
|
||||
self.document_metadata.footprint_areas = new_footprint_areas;
|
||||
}
|
||||
|
||||
/// Update the layer vector data (for layers without Path nodes)
|
||||
pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>) {
|
||||
self.document_metadata.mark_changed();
|
||||
|
||||
@@ -38,6 +38,14 @@ pub struct NodeTemplate {
|
||||
}
|
||||
|
||||
impl NodeTemplate {
|
||||
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
|
||||
pub fn empty_subgraph() -> Self {
|
||||
Self {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
||||
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
||||
self.inputs.get(P::INDEX)
|
||||
|
||||
@@ -867,51 +867,11 @@ impl PartialEq for DocumentNodeMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NumberInputSettings {
|
||||
pub unit: Option<String>,
|
||||
pub min: Option<f64>,
|
||||
pub max: Option<f64>,
|
||||
pub step: Option<f64>,
|
||||
pub mode: NumberInputMode,
|
||||
pub range_min: Option<f64>,
|
||||
pub range_max: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for NumberInputSettings {
|
||||
fn default() -> Self {
|
||||
NumberInputSettings {
|
||||
unit: None,
|
||||
min: None,
|
||||
max: None,
|
||||
step: None,
|
||||
mode: NumberInputMode::default(),
|
||||
range_min: None,
|
||||
range_max: None,
|
||||
is_integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Vec2InputSettings {
|
||||
pub x: String,
|
||||
pub y: String,
|
||||
pub unit: String,
|
||||
pub min: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub enum WidgetOverride {
|
||||
None,
|
||||
Hidden,
|
||||
String(String),
|
||||
Number(NumberInputSettings),
|
||||
Vec2(Vec2InputSettings),
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
@@ -948,40 +908,6 @@ impl InputPersistentMetadata {
|
||||
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
|
||||
self.widget_override = Some("string".to_string());
|
||||
}
|
||||
WidgetOverride::Number(mut number_inspector) => {
|
||||
if let Some(unit) = number_inspector.unit.take() {
|
||||
self.input_data.insert("unit".to_string(), json!(unit));
|
||||
}
|
||||
if let Some(min) = number_inspector.min.take() {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
if let Some(max) = number_inspector.max.take() {
|
||||
self.input_data.insert("max".to_string(), json!(max));
|
||||
}
|
||||
if let Some(step) = number_inspector.step.take() {
|
||||
self.input_data.insert("step".to_string(), json!(step));
|
||||
}
|
||||
if let Some(range_min) = number_inspector.range_min.take() {
|
||||
self.input_data.insert("range_min".to_string(), json!(range_min));
|
||||
}
|
||||
if let Some(range_max) = number_inspector.range_max.take() {
|
||||
self.input_data.insert("range_max".to_string(), json!(range_max));
|
||||
}
|
||||
self.input_data.insert("mode".to_string(), json!(number_inspector.mode));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(number_inspector.is_integer));
|
||||
self.input_data.insert("blank_assist".to_string(), Value::Bool(number_inspector.blank_assist));
|
||||
self.widget_override = Some("number".to_string());
|
||||
}
|
||||
WidgetOverride::Vec2(vec2_inspector) => {
|
||||
self.input_data.insert("x".to_string(), json!(vec2_inspector.x));
|
||||
self.input_data.insert("y".to_string(), json!(vec2_inspector.y));
|
||||
self.input_data.insert("unit".to_string(), json!(vec2_inspector.unit));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_inspector.is_integer));
|
||||
if let Some(min) = vec2_inspector.min {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
self.widget_override = Some("vec2".to_string());
|
||||
}
|
||||
WidgetOverride::Custom(lambda_name) => {
|
||||
self.widget_override = Some(lambda_name);
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|identifier| identifier.implementation_name_from_identifier())
|
||||
.unwrap_or("Custom Node".to_string())
|
||||
.unwrap_or("Subgraph".to_string())
|
||||
}
|
||||
|
||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||
|
||||
@@ -12,6 +12,7 @@ use graph_craft::document::DocumentNode;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
|
||||
use graph_craft::{Type, concrete, item, list};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::ParameterRef;
|
||||
use graphene_std::ProtoNodeIdentifier;
|
||||
use graphene_std::extract_xy::XY;
|
||||
@@ -471,9 +472,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
|
||||
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
// Old references (including these older aliases) are remapped here to `vec2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::vec2_value::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_math_nodes::Vec2ValueNode",
|
||||
"graphene_core::ops::ConstructVector2",
|
||||
@@ -483,7 +484,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER,
|
||||
aliases: &["math_nodes::CombineVec2Node"],
|
||||
},
|
||||
// ================================
|
||||
@@ -538,8 +539,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ChannelMixerNode",
|
||||
],
|
||||
},
|
||||
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
node: graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::ColorOverlayNode",
|
||||
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
|
||||
@@ -547,6 +549,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::adjustments::ColorOverlayNode",
|
||||
"raster_nodes::generate_curves::ColorOverlayNode",
|
||||
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
"raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -651,8 +654,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_raster_nodes::std_nodes::MandelbrotNode", "graphene_std::raster::MandelbrotNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::std_nodes::MaskNode", "graphene_std::raster::MaskNode", "graphene_std::raster::MaskImageNode"],
|
||||
node: graphene_std::blending_nodes::masks::mask::IDENTIFIER,
|
||||
aliases: &[
|
||||
"raster_nodes::std_nodes::MaskNode",
|
||||
"graphene_raster_nodes::std_nodes::MaskNode",
|
||||
"graphene_std::raster::MaskNode",
|
||||
"graphene_std::raster::MaskImageNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::posterize::IDENTIFIER,
|
||||
@@ -1279,12 +1287,15 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if *new == graphene_std::vector::weld::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Merge by Distance");
|
||||
}
|
||||
if *new == graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
|
||||
// Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
||||
// Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
||||
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
|
||||
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
|
||||
.network_interface
|
||||
@@ -1565,8 +1576,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||
let split_wrapper_replacements = [
|
||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vec2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||
];
|
||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||
@@ -1630,7 +1641,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
|
||||
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
|
||||
if EXTRACT_XY.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||
} else {
|
||||
@@ -1760,6 +1771,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
})
|
||||
.collect();
|
||||
|
||||
migrate_custom_node_subgraphs(document);
|
||||
|
||||
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
|
||||
let nodes = document
|
||||
.network_interface
|
||||
@@ -1898,6 +1911,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if let Some(size) = clipped_size {
|
||||
fill_square_with_pattern(document, node_id, network_path, *size);
|
||||
}
|
||||
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
|
||||
move_mandelbrot_to_old_origin(document, node_id, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||
@@ -2031,6 +2047,46 @@ fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Keeps an old Mandelbrot's look now that the complex plane's origin is its pattern's, with a third of a unit's scale and a Transform moving the pattern back to where
|
||||
/// the old unit square, which spanned the plane from -2 to 1, put that origin.
|
||||
fn move_mandelbrot_to_old_origin(document: &mut DocumentMessageHandler, mandelbrot_node_id: &NodeId, network_path: &[NodeId]) -> Option<()> {
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*mandelbrot_node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let transform_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER))?.default_node_template();
|
||||
|
||||
let origin_transform_id = NodeId::new();
|
||||
document.network_interface.insert_node(origin_transform_id, transform_template, network_path);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(*mandelbrot_node_id, graphene_std::raster_nodes::std_nodes::mandelbrot::ScaleInput::INDEX),
|
||||
NodeInput::value(TaggedValue::Number(1. / 3.), false),
|
||||
network_path,
|
||||
);
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node_at_index(origin_transform_id, 1),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5)), false),
|
||||
network_path,
|
||||
);
|
||||
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(origin_transform_id, 0), NodeInput::node(*mandelbrot_node_id, 0), network_path);
|
||||
for consumer in &downstream_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(origin_transform_id, 0), network_path);
|
||||
}
|
||||
|
||||
// The Transform takes the pattern's place, and the pattern moves before it
|
||||
if let Some(position) = document.network_interface.position(mandelbrot_node_id, network_path) {
|
||||
document.network_interface.set_absolute_position(&origin_transform_id, position, network_path);
|
||||
document.network_interface.set_absolute_position(mandelbrot_node_id, position + IVec2::new(-7, 0), network_path);
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -2157,6 +2213,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 3;
|
||||
}
|
||||
|
||||
// 'Mask' gained its mode, density, feather, and invert inputs when it learned to mask any graphic, which take the definition's defaults
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::masks::mask::IDENTIFIER) && inputs_count == 2 {
|
||||
let definition = resolve_document_node_type(&reference)?;
|
||||
let mut template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
|
||||
for (index, input) in old_inputs.into_iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
inputs_count = 6;
|
||||
}
|
||||
|
||||
// Split the legacy combined "Blending" node into a chain of separate Blend Mode, Opacity (now also covers fill), and Clip nodes.
|
||||
// `NODE_REPLACEMENTS` rewrites the old `Blending` proto identifier (and its older aliases) to `blend_mode::IDENTIFIER`, so a leftover
|
||||
// 5-input shape on a Blend Mode node identifies an old Blending node that still needs structural splitting. Sub-nodes whose values
|
||||
@@ -2326,6 +2394,24 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 5;
|
||||
}
|
||||
|
||||
// 'Drop Shadow', 'Inner Shadow', and 'Outer Glow' gained a blend mode after their color, set to Normal to keep compositing them as before
|
||||
use graphene_std::blending_nodes::effects::{drop_shadow, inner_shadow, outer_glow};
|
||||
let lacks_blend_mode = |identifier: ProtoNodeIdentifier, count: usize| reference == DefinitionIdentifier::ProtoNode(identifier) && inputs_count == count;
|
||||
if lacks_blend_mode(drop_shadow::IDENTIFIER, 8) || lacks_blend_mode(inner_shadow::IDENTIFIER, 7) || lacks_blend_mode(outer_glow::IDENTIFIER, 7) {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for (index, input) in old_inputs.into_iter().enumerate() {
|
||||
let index = if index < 2 { index } else { index + 1 };
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
let normal = NodeInput::value(TaggedValue::BlendMode(graphene_std::blending::BlendMode::Normal), false);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), normal, network_path);
|
||||
|
||||
inputs_count += 1;
|
||||
}
|
||||
|
||||
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
|
||||
// 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_form, _has_transform, _transform).
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
|
||||
@@ -2560,7 +2646,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
|
||||
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
|
||||
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
|
||||
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
|
||||
];
|
||||
for (parameter, fallback) in conversions {
|
||||
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
|
||||
@@ -2771,8 +2856,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
|
||||
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER);
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER);
|
||||
let mut node_template = resolve_document_node_type(&numbers_to_vec2_reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
@@ -3962,6 +4047,25 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button.
|
||||
/// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed.
|
||||
fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) {
|
||||
let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into()));
|
||||
let subgraphs: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node)
|
||||
.map(|(node_id, _, path)| (*node_id, path))
|
||||
.collect();
|
||||
|
||||
for (node_id, network_path) in subgraphs {
|
||||
reset_default_display_name(document, &node_id, &network_path, "Custom Node");
|
||||
reset_default_display_name(document, &node_id, &network_path, "Untitled Node");
|
||||
document.network_interface.set_reference(&node_id, &network_path, None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
||||
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
||||
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
@@ -4514,6 +4618,45 @@ mod tests {
|
||||
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let from_catalog = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let document = editor.active_document_mut();
|
||||
let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else {
|
||||
panic!("the subgraph should name a definitions table entry")
|
||||
};
|
||||
|
||||
// A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made
|
||||
let from_merging = NodeId::new();
|
||||
let instance = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Definition(shared),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(from_merging, instance, &[]);
|
||||
document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into()));
|
||||
document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]);
|
||||
document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]);
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
for node_id in [from_catalog, from_merging] {
|
||||
assert!(
|
||||
matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))),
|
||||
"the subgraph should still exist"
|
||||
);
|
||||
assert_eq!(interface.reference(&node_id, &[]), None);
|
||||
assert_eq!(interface.display_name(&node_id, &[]), "Subgraph");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_rasterize_node_on_the_export_compiles() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
@@ -5000,7 +5143,11 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node");
|
||||
let (&count_conversion_id, count_conversion) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. })))
|
||||
.expect("Blend should have a count conversion node");
|
||||
count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
|
||||
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
@@ -5017,7 +5164,7 @@ mod tests {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Blend", NodeId(3))].implementation,
|
||||
inner.nodes[&shipped_node_id("Blend", count_conversion_id)].implementation,
|
||||
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
|
||||
);
|
||||
}
|
||||
@@ -5034,7 +5181,11 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
|
||||
let (&edited_subtract_id, edited_subtract) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER))
|
||||
.expect("Blend should have an open-path denominator node");
|
||||
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
@@ -5044,7 +5195,7 @@ mod tests {
|
||||
let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
let edited_subtract = derived_node_id(*definition, NodeId(5));
|
||||
let edited_subtract = derived_node_id(*definition, edited_subtract_id);
|
||||
assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
|
||||
}
|
||||
|
||||
@@ -5126,8 +5277,15 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Regex Find should be a network node")
|
||||
};
|
||||
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
let inner_node_id = |identifier: graphene_std::ProtoNodeIdentifier| {
|
||||
let implementation = NodeTemplateImplementation::ProtoNode(identifier);
|
||||
network_template.nodes.iter().find(|(_, node)| node.implementation == implementation).map(|(&id, _)| id)
|
||||
};
|
||||
let find_id = inner_node_id(graphene_std::text_nodes::regex::regex_find::IDENTIFIER).expect("Regex Find should have a find node");
|
||||
let item_at_index_id = inner_node_id(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Regex Find should have an item-at-index node");
|
||||
|
||||
network_template.nodes.get_mut(&find_id).expect("the find node should exist").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&item_at_index_id).expect("the item-at-index node should exist").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
migrate(&mut document);
|
||||
@@ -5141,9 +5299,9 @@ mod tests {
|
||||
let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else {
|
||||
panic!("Regex Find should stay a network node")
|
||||
};
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", NodeId(0))].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", find_id)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Regex Find", NodeId(1))].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
inner.nodes[&shipped_node_id("Regex Find", item_at_index_id)].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::Integer(0))
|
||||
);
|
||||
}
|
||||
@@ -5669,6 +5827,54 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadows_and_glows_from_before_their_blend_mode_open_blending_normally() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::blending_nodes::effects::{drop_shadow, inner_shadow, outer_glow};
|
||||
|
||||
let saved_nodes = [(drop_shadow::IDENTIFIER, 8), (inner_shadow::IDENTIFIER, 7), (outer_glow::IDENTIFIER, 7)];
|
||||
let template = |identifier: &ProtoNodeIdentifier| {
|
||||
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier.clone())).expect("the definition should exist");
|
||||
definition.default_node_template()
|
||||
};
|
||||
|
||||
// Each node as saved before the blend mode, with each number marked by its index so the shift shows
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
|
||||
let mut inputs = template(identifier).inputs;
|
||||
inputs.remove(2);
|
||||
inputs.truncate(*count);
|
||||
for (input_index, input) in inputs.iter_mut().enumerate() {
|
||||
if matches!(input.as_value(), Some(TaggedValue::Number(_))) {
|
||||
*input = NodeInput::value(TaggedValue::Number(input_index as f64), false);
|
||||
}
|
||||
}
|
||||
|
||||
let node_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(identifier.clone()),
|
||||
inputs,
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(NodeId(index as u64 + 1), node_template, &[]);
|
||||
}
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
|
||||
for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
|
||||
let node = opened.network_interface.document_node(&NodeId(index as u64 + 1), &[]).expect("the node should still exist");
|
||||
let name = identifier.as_str();
|
||||
assert_eq!(node.inputs.len(), template(identifier).inputs.len(), "{name} should take the current shape");
|
||||
assert_eq!(node.inputs[2], NodeInput::value(TaggedValue::BlendMode(BlendMode::Normal), false), "{name} should blend normally");
|
||||
for (input_index, input) in node.inputs.iter().enumerate().take(count + 1).skip(3) {
|
||||
if let Some(TaggedValue::Number(number)) = input.as_value() {
|
||||
assert_eq!(*number, (input_index - 1) as f64, "{name} should move its input {} past the blend mode", input_index - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize, Sample Image, and Empty Image nodes open as As String, Passthrough, and Image nodes, keeping their wires and Serialize's stored text
|
||||
#[test]
|
||||
fn removed_nodes_open_as_their_stand_ins() {
|
||||
@@ -6213,13 +6419,24 @@ mod tests {
|
||||
|
||||
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
|
||||
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
|
||||
assert_eq!(upstream(paint, 0), Some(pattern));
|
||||
|
||||
// The Mandelbrot is also moved back to where its old unit square put the complex plane's origin
|
||||
let mut read = upstream(paint, 0).expect("the paint should read the pattern");
|
||||
if pattern == mandelbrot {
|
||||
assert_eq!(value(read, 1), Some(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5))));
|
||||
read = upstream(read, 0).expect("the origin transform should read the pattern");
|
||||
}
|
||||
assert_eq!(read, pattern);
|
||||
}
|
||||
|
||||
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
|
||||
// Noise settings shift past the removed Clip toggle, and Mandelbrot gains its primary input and settings, its scale a third of a unit like its old unit square's
|
||||
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
|
||||
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
|
||||
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
|
||||
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 11);
|
||||
assert_eq!(
|
||||
value(mandelbrot, graphene_std::raster_nodes::std_nodes::mandelbrot::ScaleInput::INDEX),
|
||||
Some(TaggedValue::Number(1. / 3.))
|
||||
);
|
||||
}
|
||||
|
||||
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
||||
|
||||
@@ -989,16 +989,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
} => {
|
||||
let document_id = self.active_document_id.expect("Tried to render non-existent document");
|
||||
let document = self.documents.get_mut(&document_id).expect("Tried to render non-existent document");
|
||||
|
||||
// An export now would capture the fallbacks drawn in place of fonts and images still loading
|
||||
if document.resources.awaiting_resources() {
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Unable to export document".to_string(),
|
||||
description: "The document's fonts or images are still loading. Try again once they finish.".to_string(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let export_config = ExportConfig {
|
||||
name,
|
||||
file_type,
|
||||
@@ -1035,7 +1025,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
return;
|
||||
};
|
||||
|
||||
// Skip rendering while a resource is still loading, so its fallback isn't drawn in the meantime.
|
||||
// Skip rendering while a resource is still loading, so its error isn't shown in the meantime.
|
||||
// Each load queues `RunDocumentGraph` when it succeeds or fails, so the render goes ahead once none are left.
|
||||
if document.resources.awaiting_resources() {
|
||||
return;
|
||||
|
||||
@@ -1,332 +0,0 @@
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::transformation_cage::{BoundingBoxManager, SelectedEdges};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::context::bake_footprint;
|
||||
use graphene_std::platform_application_io::rasterize;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::transform::Footprint;
|
||||
|
||||
/// A transform cage that resizes and moves the area of the selected node with a footprint input.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FootprintCage {
|
||||
target: Option<CageTarget>,
|
||||
drag: Option<CageDrag>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct CageTarget {
|
||||
footprint_input: InputConnector,
|
||||
area: Footprint,
|
||||
/// Spans the area, with the unit square as its bounds.
|
||||
bounding_box: BoundingBoxManager,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct CageDrag {
|
||||
footprint_input: InputConnector,
|
||||
original_area: Footprint,
|
||||
unit_square_to_viewport: DAffine2,
|
||||
kind: CageDragKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum CageDragKind {
|
||||
Resize(SelectedEdges),
|
||||
Move { grab: DVec2 },
|
||||
}
|
||||
|
||||
impl FootprintCage {
|
||||
/// Places the cage on the area of the selected node with a footprint input, or removes it if it is hidden or there is none.
|
||||
pub fn refresh(&mut self, document: &DocumentMessageHandler, visible: bool) {
|
||||
self.target = visible.then(|| Self::find_target(document)).flatten();
|
||||
}
|
||||
|
||||
fn find_target(document: &DocumentMessageHandler) -> Option<CageTarget> {
|
||||
let network_path = document.selection_network_path();
|
||||
let network_interface = &document.network_interface;
|
||||
|
||||
let selected_nodes = network_interface.selected_nodes_in_nested_network(network_path)?;
|
||||
let mut footprint_inputs = selected_nodes.selected_nodes().filter_map(|&node_id| footprint_input(node_id, network_interface, network_path));
|
||||
let footprint_input = footprint_inputs.next()?;
|
||||
if footprint_inputs.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
let node_id = footprint_input.node_id()?;
|
||||
|
||||
let input = network_interface.input_from_connector(&footprint_input, network_path)?;
|
||||
let &TaggedValue::Footprint(area) = input.as_non_exposed_value()? else { return None };
|
||||
|
||||
let unit_square_to_document = *document.metadata().footprint_areas.get(&node_id)?;
|
||||
let unit_square_to_viewport = document.metadata().document_to_viewport * unit_square_to_document;
|
||||
if unit_square_to_viewport.matrix2.determinant() == 0. {
|
||||
return None;
|
||||
}
|
||||
|
||||
let bounding_box = BoundingBoxManager {
|
||||
bounds: [DVec2::ZERO, DVec2::ONE],
|
||||
transform: unit_square_to_viewport,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Some(CageTarget { footprint_input, area, bounding_box })
|
||||
}
|
||||
|
||||
pub fn overlays(&mut self, overlay_context: &mut OverlayContext) {
|
||||
if let Some(target) = &mut self.target {
|
||||
target.bounding_box.render_overlays(overlay_context, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The cursor for the part of the cage under the pointer, if any.
|
||||
pub fn cursor(&self, input: &InputPreprocessorMessageHandler) -> Option<MouseCursorIcon> {
|
||||
let target = self.target.as_ref()?;
|
||||
|
||||
let edge_cursor = target.bounding_box.get_cursor(input, false, false, None);
|
||||
if edge_cursor != MouseCursorIcon::Default {
|
||||
return Some(edge_cursor);
|
||||
}
|
||||
|
||||
target.contains(input.mouse.position).then_some(MouseCursorIcon::Move)
|
||||
}
|
||||
|
||||
/// Begins resizing or moving the area if the pointer is on the cage, returning whether it did.
|
||||
pub fn begin_drag(&mut self, mouse: DVec2, responses: &mut VecDeque<Message>) -> bool {
|
||||
let Some(target) = &self.target else { return false };
|
||||
let bounding_box = &target.bounding_box;
|
||||
|
||||
let kind = if let Some((top, bottom, left, right)) = bounding_box.check_selected_edges(mouse) {
|
||||
CageDragKind::Resize(SelectedEdges::new(top, bottom, left, right, bounding_box.bounds))
|
||||
} else if target.contains(mouse) {
|
||||
CageDragKind::Move {
|
||||
grab: bounding_box.transform.inverse().transform_point2(mouse),
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.drag = Some(CageDrag {
|
||||
footprint_input: target.footprint_input,
|
||||
original_area: target.area,
|
||||
unit_square_to_viewport: bounding_box.transform,
|
||||
kind,
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
responses.add(DocumentMessage::NameInteraction { action: "Changed a Footprint".into() });
|
||||
true
|
||||
}
|
||||
|
||||
/// Moves or resizes the area to follow the pointer, keeping its pixel density.
|
||||
pub fn update_drag(&mut self, mouse: DVec2, centered: bool, constrain: bool, responses: &mut VecDeque<Message>) {
|
||||
let Some(drag) = &self.drag else { return };
|
||||
|
||||
let (position, size) = match &drag.kind {
|
||||
CageDragKind::Resize(edges) => {
|
||||
let center = drag.unit_square_to_viewport.transform_point2(DVec2::splat(0.5));
|
||||
let (position, size) = edges.new_size(mouse, drag.unit_square_to_viewport, centered.then_some(center), constrain, None);
|
||||
(position.min(position + size), size.abs())
|
||||
}
|
||||
CageDragKind::Move { grab } => {
|
||||
let pointer = drag.unit_square_to_viewport.inverse().transform_point2(mouse);
|
||||
(pointer - *grab, DVec2::ONE)
|
||||
}
|
||||
};
|
||||
|
||||
let original_area = drag.original_area;
|
||||
let one_pixel = original_area.resolution.as_dvec2().recip();
|
||||
let size = size.max(one_pixel);
|
||||
|
||||
let area = Footprint {
|
||||
transform: original_area.transform * DAffine2::from_scale_angle_translation(size, 0., position),
|
||||
resolution: (original_area.resolution.as_dvec2() * size).round().as_uvec2().max(UVec2::ONE),
|
||||
..original_area
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: drag.footprint_input,
|
||||
input: NodeInput::value(TaggedValue::Footprint(area), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Keeps the drag in place on the document while the viewport pans by `shift`.
|
||||
pub fn pan(&mut self, shift: DVec2) {
|
||||
if let Some(drag) = &mut self.drag {
|
||||
drag.unit_square_to_viewport.translation += shift;
|
||||
}
|
||||
}
|
||||
|
||||
/// Finishes the drag, undoing its changes if it was aborted.
|
||||
pub fn end_drag(&mut self, aborted: bool, responses: &mut VecDeque<Message>) {
|
||||
if self.drag.take().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(if aborted { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction });
|
||||
}
|
||||
}
|
||||
|
||||
/// The input holding the footprint of a node that has one.
|
||||
fn footprint_input(node_id: NodeId, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option<InputConnector> {
|
||||
let reference = network_interface.reference(&node_id, network_path)?;
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER) {
|
||||
Some(InputConnector::node(node_id, bake_footprint::FootprintInput))
|
||||
} else if reference == DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER) {
|
||||
Some(InputConnector::node(node_id, rasterize::FootprintInput))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl CageTarget {
|
||||
fn contains(&self, viewport_point: DVec2) -> bool {
|
||||
(self.bounding_box.transform * Quad::from_box(self.bounding_box.bounds)).contains(viewport_point)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bake_footprint_node_in_a_layer_reports_where_its_area_lies() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
|
||||
let document = editor.active_document();
|
||||
let input = document.network_interface.input_from_connector(&InputConnector::node(node_id, bake_footprint::FootprintInput), &[]);
|
||||
let Some(&TaggedValue::Footprint(area)) = input.and_then(NodeInput::as_non_exposed_value) else {
|
||||
panic!("the node should have a footprint value")
|
||||
};
|
||||
|
||||
let metadata = document.metadata();
|
||||
let baked_area = metadata.footprint_areas.get(&node_id).expect("the render should report where the node baked its area");
|
||||
let layer_content_to_viewport = metadata.upstream_footprints.get(&layer.to_node()).expect("the render should report the layer's footprint").transform;
|
||||
let expected = metadata.rendered_document_to_viewport.inverse() * layer_content_to_viewport * area.transform;
|
||||
assert!(baked_area.abs_diff_eq(expected, 1e-9), "{baked_area:?} should be {expected:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_baked_area_moves_with_a_transform_applied_after_it() {
|
||||
use graphene_std::transform_nodes::transform;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let bake_footprint_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
|
||||
node_id: bake_footprint_node,
|
||||
parent: layer,
|
||||
})
|
||||
.await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
let untransformed = *editor.active_document().metadata().footprint_areas.get(&bake_footprint_node).expect("the area should be reported");
|
||||
|
||||
let transform_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(transform::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
|
||||
node_id: transform_node,
|
||||
parent: layer,
|
||||
})
|
||||
.await;
|
||||
let translation = DVec2::new(100., 50.);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(transform_node, transform::TranslationInput),
|
||||
input: NodeInput::value(TaggedValue::DVec2(translation), false),
|
||||
})
|
||||
.await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
|
||||
let transformed = *editor
|
||||
.active_document()
|
||||
.metadata()
|
||||
.footprint_areas
|
||||
.get(&bake_footprint_node)
|
||||
.expect("the area should still be reported");
|
||||
let expected = DAffine2::from_translation(translation) * untransformed;
|
||||
assert!(transformed.abs_diff_eq(expected, 1e-9), "{transformed:?} should be {expected:?}");
|
||||
}
|
||||
|
||||
/// Drags the cage of a 'Bake Footprint' node in a layer between two points of its unit square, giving its area before and after.
|
||||
async fn drag_cage(from: DVec2, to: DVec2) -> (Footprint, Footprint) {
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
|
||||
let area = Footprint {
|
||||
transform: DAffine2::from_scale(DVec2::splat(100.)),
|
||||
resolution: UVec2::splat(200),
|
||||
..Default::default()
|
||||
};
|
||||
let footprint_input = InputConnector::node(node_id, bake_footprint::FootprintInput);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInput {
|
||||
input_connector: footprint_input,
|
||||
input: NodeInput::value(TaggedValue::Footprint(area), false),
|
||||
})
|
||||
.await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }).await;
|
||||
|
||||
let metadata = editor.active_document().metadata();
|
||||
let unit_square_to_viewport = metadata.document_to_viewport * *metadata.footprint_areas.get(&node_id).expect("the area should be reported");
|
||||
let (from, to) = (unit_square_to_viewport.transform_point2(from), unit_square_to_viewport.transform_point2(to));
|
||||
|
||||
editor.select_tool(ToolType::Select).await;
|
||||
editor.handle_message(SelectToolMessage::Overlays { context: OverlayContext::default() }).await;
|
||||
editor.move_mouse(from.x, from.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(from.x, from.y, ModifierKeys::empty()).await;
|
||||
editor.move_mouse(to.x, to.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
editor.left_mouseup(to.x, to.y, ModifierKeys::empty()).await;
|
||||
|
||||
let input = editor.active_document().network_interface.input_from_connector(&footprint_input, &[]);
|
||||
let Some(&TaggedValue::Footprint(dragged)) = input.and_then(NodeInput::as_non_exposed_value) else {
|
||||
panic!("the node should have a footprint value")
|
||||
};
|
||||
(area, dragged)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dragging_the_right_edge_of_the_cage_widens_the_area_and_its_resolution() {
|
||||
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(1.5, 0.5)).await;
|
||||
|
||||
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(1.5, 1.));
|
||||
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
|
||||
assert_eq!(dragged.resolution, UVec2::new(300, 200));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dragging_the_right_edge_onto_the_left_one_keeps_one_pixel_of_width() {
|
||||
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(0., 0.5)).await;
|
||||
|
||||
let one_pixel = 1. / area.resolution.x as f64;
|
||||
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(one_pixel, 1.));
|
||||
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
|
||||
assert_eq!(dragged.resolution, UVec2::new(1, 200));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,2 @@
|
||||
pub mod footprint_cage;
|
||||
pub mod gizmo_manager;
|
||||
pub mod shape_gizmos;
|
||||
@@ -15,7 +15,6 @@ use crate::messages::tool::common_functionality::color_selector::{
|
||||
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, has_paintable_selection, swap_fill_and_stroke, sync_drawing_state,
|
||||
};
|
||||
use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose};
|
||||
use crate::messages::tool::common_functionality::gizmos::footprint_cage::FootprintCage;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::measure;
|
||||
use crate::messages::tool::common_functionality::pivot::{Pivot, PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget};
|
||||
@@ -506,7 +505,6 @@ enum SelectToolFsmState {
|
||||
},
|
||||
RotatingBounds,
|
||||
DraggingPivot,
|
||||
DraggingFootprintCage,
|
||||
}
|
||||
|
||||
impl Default for SelectToolFsmState {
|
||||
@@ -547,7 +545,6 @@ struct SelectToolData {
|
||||
axis_align: bool,
|
||||
non_duplicated_layers: Option<Vec<LayerNodeIdentifier>>,
|
||||
bounding_box_manager: Option<BoundingBoxManager>,
|
||||
footprint_cage: FootprintCage,
|
||||
cursor: MouseCursorIcon,
|
||||
pivot_gizmo: PivotGizmo,
|
||||
/// The pivot as it was when a drag of it began, restored if the drag is aborted.
|
||||
@@ -957,9 +954,6 @@ impl Fsm for SelectToolFsmState {
|
||||
(_, SelectToolMessage::Overlays { context: mut overlay_context }) => {
|
||||
crate::messages::tool::common_functionality::layer_origin_cross::draw_for_selected_layers(&mut overlay_context, document);
|
||||
|
||||
tool_data.footprint_cage.refresh(document, overlay_context.visibility_settings.transform_cage());
|
||||
tool_data.footprint_cage.overlays(&mut overlay_context);
|
||||
|
||||
let selected_layers_count = document.network_interface.selected_nodes().selected_unlocked_layers(&document.network_interface).count();
|
||||
let paintable_layers_selected = has_paintable_selection(document);
|
||||
tool_data.selected_layers_changed = selected_layers_count != tool_data.selected_layers_count || paintable_layers_selected != tool_data.paintable_layers_selected;
|
||||
@@ -1394,10 +1388,6 @@ impl Fsm for SelectToolFsmState {
|
||||
tool_data.drag_current = input.mouse.position;
|
||||
tool_data.selection_mode = None;
|
||||
|
||||
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_none() && tool_data.footprint_cage.begin_drag(input.mouse.position, responses) {
|
||||
return SelectToolFsmState::DraggingFootprintCage;
|
||||
}
|
||||
|
||||
let mut selected: Vec<_> = document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface).collect();
|
||||
let intersection_list = document.click_list(input, viewport).collect::<Vec<_>>();
|
||||
let intersection = document.find_deepest(&intersection_list);
|
||||
@@ -1630,18 +1620,6 @@ impl Fsm for SelectToolFsmState {
|
||||
remove,
|
||||
}
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerMove { modifier_keys }) => {
|
||||
let (centered, constrain) = (input.keyboard.key(modifier_keys.center), input.keyboard.key(modifier_keys.axis_align));
|
||||
tool_data.footprint_cage.update_drag(input.mouse.position, centered, constrain, responses);
|
||||
|
||||
let messages = [
|
||||
SelectToolMessage::PointerOutsideViewport { modifier_keys: modifier_keys.clone() }.into(),
|
||||
SelectToolMessage::PointerMove { modifier_keys }.into(),
|
||||
];
|
||||
tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses);
|
||||
|
||||
SelectToolFsmState::DraggingFootprintCage
|
||||
}
|
||||
(SelectToolFsmState::ResizingBounds, SelectToolMessage::PointerMove { modifier_keys }) => {
|
||||
if let Some(bounds) = &mut tool_data.bounding_box_manager {
|
||||
resize_bounds(
|
||||
@@ -1743,10 +1721,6 @@ impl Fsm for SelectToolFsmState {
|
||||
.as_ref()
|
||||
.map_or(MouseCursorIcon::Default, |bounds| bounds.get_cursor(input, true, dragging_bounds, Some(tool_data.skew_edge)));
|
||||
|
||||
if let Some(footprint_cage_cursor) = tool_data.footprint_cage.cursor(input) {
|
||||
cursor = footprint_cage_cursor;
|
||||
}
|
||||
|
||||
// Dragging the pivot overrules the other operations
|
||||
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_some() {
|
||||
cursor = MouseCursorIcon::Move;
|
||||
@@ -1798,14 +1772,6 @@ impl Fsm for SelectToolFsmState {
|
||||
|
||||
self
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// Auto-panning
|
||||
if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) {
|
||||
tool_data.footprint_cage.pan(shift);
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
(SelectToolFsmState::DraggingPivot, SelectToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// Auto-panning
|
||||
let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses);
|
||||
@@ -1951,14 +1917,6 @@ impl Fsm for SelectToolFsmState {
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::DragStop { .. } | SelectToolMessage::Enter) => {
|
||||
let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON;
|
||||
tool_data.footprint_cage.end_drag(drag_too_small, responses);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::Drawing { selection_shape, .. }, SelectToolMessage::DragStop { remove_from_selection }) => {
|
||||
let quad = tool_data.selection_quad();
|
||||
|
||||
@@ -2048,13 +2006,6 @@ impl Fsm for SelectToolFsmState {
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::Abort) => {
|
||||
tool_data.footprint_cage.end_drag(true, responses);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::Dragging { .. }, SelectToolMessage::Abort) => {
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
tool_data.axis_align = false;
|
||||
@@ -2224,13 +2175,6 @@ impl Fsm for SelectToolFsmState {
|
||||
]);
|
||||
hint_data.send_layout(responses);
|
||||
}
|
||||
SelectToolFsmState::DraggingFootprintCage => {
|
||||
let hint_data = HintData(vec![
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
|
||||
HintGroup(vec![HintInfo::keys([Key::Alt], "From Center"), HintInfo::keys([Key::Shift], "Preserve Aspect Ratio")]),
|
||||
]);
|
||||
hint_data.send_layout(responses);
|
||||
}
|
||||
SelectToolFsmState::RotatingBounds => {
|
||||
let hint_data = HintData(vec![
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
|
||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
@@ -6,27 +7,24 @@ use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{Vector, graphic_types, no_paths, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic};
|
||||
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
|
||||
mod observations;
|
||||
#[cfg(test)]
|
||||
mod recompile_tests;
|
||||
mod runtime;
|
||||
pub use observations::ObservationKey;
|
||||
use observations::{path_content_observations, path_contents};
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
@@ -45,6 +43,18 @@ pub struct ExecutionResponse {
|
||||
observations: HashMap<ObservationKey, InspectResult>,
|
||||
}
|
||||
|
||||
/// Names an observation so it can be changed or stopped without touching the others.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ObservationKey {
|
||||
/// The node the Data panel inspects.
|
||||
DataPanel,
|
||||
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
|
||||
PathContent(NodeId),
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// The "Fill" node whose geometry a gradient migration measures.
|
||||
FillMeasurement,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ExecutionResult {
|
||||
Pending,
|
||||
@@ -274,7 +284,6 @@ impl NodeGraphExecutor {
|
||||
self.inspect_context_overrides = ContextOverrides::default();
|
||||
}
|
||||
|
||||
// The compile looks up each resource's data in the registry, so a resource that loads reruns it like an edit to the network does
|
||||
let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash());
|
||||
if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
@@ -632,7 +641,6 @@ impl NodeGraphExecutor {
|
||||
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
|
||||
document.network_interface.update_outlines(HashMap::new());
|
||||
document.network_interface.update_vector_modify(HashMap::new());
|
||||
document.network_interface.update_footprint_areas(HashMap::new());
|
||||
if let Some(message) = &message {
|
||||
log::error!("Node graph evaluation failed:\n{message}");
|
||||
}
|
||||
@@ -692,13 +700,6 @@ impl NodeGraphExecutor {
|
||||
if let Err((_, e)) = &result {
|
||||
log::trace!("Gradient migration measurement compile: {e}");
|
||||
}
|
||||
|
||||
// A fallback drawn in place of a missing font or image would be measured instead, so the fills wait for a later open
|
||||
if node_graph_warnings.iter().any(|warning| matches!(warning.error, GraphErrorType::MissingResource { .. })) {
|
||||
self.cancel_gradient_migration();
|
||||
self.gradient_migration_attempted.insert(document_id);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -709,7 +710,6 @@ impl NodeGraphExecutor {
|
||||
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
|
||||
document.network_interface.update_outlines(HashMap::new());
|
||||
document.network_interface.update_vector_modify(HashMap::new());
|
||||
document.network_interface.update_footprint_areas(HashMap::new());
|
||||
|
||||
// The graph only shows errors tied to nodes, so the console gets the others
|
||||
if node_graph_errors.is_empty() {
|
||||
@@ -1057,7 +1057,6 @@ impl NodeGraphExecutor {
|
||||
outlines,
|
||||
group_layers,
|
||||
text_frames,
|
||||
footprint_areas,
|
||||
clip_targets,
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
@@ -1065,9 +1064,6 @@ impl NodeGraphExecutor {
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
let viewport_to_document = document_to_viewport.inverse();
|
||||
let footprint_areas = footprint_areas.into_iter().map(|(node_id, area)| (node_id, viewport_to_document * area)).collect();
|
||||
|
||||
// Run these update state messages immediately
|
||||
responses.add(DocumentMessage::UpdateUpstreamTransforms {
|
||||
upstream_footprints,
|
||||
@@ -1078,7 +1074,6 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClickTargets { click_targets, group_layers });
|
||||
responses.add(DocumentMessage::UpdateOutlines { outlines });
|
||||
responses.add(DocumentMessage::UpdateTextFrames { text_frames });
|
||||
responses.add(DocumentMessage::UpdateFootprintAreas { footprint_areas });
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
@@ -1227,6 +1222,37 @@ fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
||||
}
|
||||
}
|
||||
|
||||
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
|
||||
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
|
||||
|
||||
path_nodes.into_iter().filter_map(|node_path| {
|
||||
let key = ObservationKey::PathContent(*node_path.last()?);
|
||||
let observation = Observation {
|
||||
node_path,
|
||||
connector: ObservedConnector::Input(path::ContentInput::INDEX),
|
||||
overrides: ContextOverrides::default(),
|
||||
};
|
||||
Some((key, observation))
|
||||
})
|
||||
}
|
||||
|
||||
/// The incoming geometry of each 'Path' node, read from its observed content.
|
||||
fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
|
||||
observations
|
||||
.iter()
|
||||
.filter_map(|(key, result)| {
|
||||
let ObservationKey::PathContent(path_node) = *key else { return None };
|
||||
let value = result.data.as_ref()?;
|
||||
|
||||
let geometry = match value.downcast_ref::<List<Vector>>() {
|
||||
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
|
||||
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
|
||||
};
|
||||
Some((path_node, geometry))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Re-export for usage by tests in other modules
|
||||
#[cfg(test)]
|
||||
pub use test::Instrumented;
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
use super::{InspectResult, Observation, ObservedConnector};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::vector::{Vector, VectorGeometry, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ContextOverrides, NodeParameter};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Names an observation so it can be changed or stopped without touching the others.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ObservationKey {
|
||||
/// The node the Data panel inspects.
|
||||
DataPanel,
|
||||
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
|
||||
PathContent(NodeId),
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// The "Fill" node whose geometry a gradient migration measures.
|
||||
FillMeasurement,
|
||||
}
|
||||
|
||||
pub(super) fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
|
||||
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
|
||||
|
||||
path_nodes.into_iter().filter_map(|node_path| {
|
||||
let key = ObservationKey::PathContent(*node_path.last()?);
|
||||
let observation = Observation {
|
||||
node_path,
|
||||
connector: ObservedConnector::Input(path::ContentInput::INDEX),
|
||||
overrides: ContextOverrides::default(),
|
||||
};
|
||||
Some((key, observation))
|
||||
})
|
||||
}
|
||||
|
||||
/// The incoming geometry of each 'Path' node, read from its observed content.
|
||||
pub(super) fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
|
||||
observations
|
||||
.iter()
|
||||
.filter_map(|(key, result)| {
|
||||
let ObservationKey::PathContent(path_node) = *key else { return None };
|
||||
let value = result.data.as_ref()?;
|
||||
|
||||
let geometry = match value.downcast_ref::<List<Vector>>() {
|
||||
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
|
||||
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
|
||||
};
|
||||
Some((path_node, geometry))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -3,12 +3,12 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, RenderedLayers};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
|
||||
use crate::task::{Spawn, Spawner, Task};
|
||||
use graph_craft::application_io::resource::{Resource, ResourceRegistry};
|
||||
use graph_craft::application_io::resource::ResourceRegistry;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
|
||||
use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors};
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_hash::CacheHash;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
@@ -18,7 +18,7 @@ use graphene_std::raster_types::Raster;
|
||||
use graphene_std::runtime::AsyncRuntime;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Context, NodeError, Poll};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use observer::Observer;
|
||||
@@ -43,6 +43,7 @@ pub struct NodeRuntime {
|
||||
pub(super) executor: DynamicExecutor,
|
||||
#[cfg(not(test))]
|
||||
executor: DynamicExecutor,
|
||||
output: OutputHandle,
|
||||
receiver: Receiver<GraphRuntimeRequest>,
|
||||
sender: Sender<NodeGraphUpdate>,
|
||||
editor_wake: Wake,
|
||||
@@ -134,28 +135,6 @@ pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId
|
||||
}
|
||||
}
|
||||
|
||||
/// A warning for each input holding a resource the registry can't resolve, placed in the first instance of a network that several nodes share.
|
||||
fn missing_resource_warnings(network: &NodeNetwork, resources: &ResourceRegistry) -> GraphErrors {
|
||||
network
|
||||
.recursive_nodes()
|
||||
.flat_map(|(node_id, node, network_path)| {
|
||||
node.inputs.iter().enumerate().filter_map(move |(index, input)| {
|
||||
let NodeInput::Value { tagged_value, .. } = input else { return None };
|
||||
let TaggedValue::Resource(resource_id) = &**tagged_value else { return None };
|
||||
|
||||
resources.hash(resource_id).is_none().then(|| GraphError {
|
||||
node_path: [network_path.as_slice(), &[*node_id]].concat(),
|
||||
identifier: match &node.implementation {
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => identifier.as_str().to_string().into(),
|
||||
_ => Default::default(),
|
||||
},
|
||||
error: GraphErrorType::MissingResource { index },
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ExportConfig {
|
||||
pub name: String,
|
||||
@@ -170,6 +149,7 @@ impl NodeRuntime {
|
||||
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>, editor_wake: Wake) -> Self {
|
||||
Self {
|
||||
executor: DynamicExecutor::default(),
|
||||
output: OutputHandle::default(),
|
||||
receiver,
|
||||
sender,
|
||||
editor_wake,
|
||||
@@ -272,7 +252,7 @@ impl NodeRuntime {
|
||||
|
||||
self.node_graph_errors.clear();
|
||||
self.node_graph_warnings.clear();
|
||||
let result = self.update_network(&network);
|
||||
let result = self.update_network(network.clone());
|
||||
self.compile_failed = result.is_err();
|
||||
if result.is_ok() {
|
||||
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
||||
@@ -485,7 +465,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) {
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.output.node(), &context))) {
|
||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||
@@ -541,23 +521,12 @@ impl NodeRuntime {
|
||||
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: &NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_in_scope(graph.clone(), self.editor_api.clone(), self.async_runtime().handle());
|
||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||
|
||||
// A missing resource compiles as the empty one, which its consumers draw with a fallback, and warns on the nodes using it
|
||||
let resource_missing = std::cell::Cell::new(false);
|
||||
let resolve_resource = |resource_id| {
|
||||
self.resources.hash(&resource_id).or_else(|| {
|
||||
resource_missing.set(true);
|
||||
Some(Resource::empty().hash())
|
||||
})
|
||||
};
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &resolve_resource) {
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||
}
|
||||
if resource_missing.get() {
|
||||
self.node_graph_warnings = missing_resource_warnings(graph, &self.resources);
|
||||
}
|
||||
|
||||
// We assume only one output
|
||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
@@ -572,10 +541,14 @@ impl NodeRuntime {
|
||||
}
|
||||
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
|
||||
};
|
||||
self.node_graph_warnings.extend(warnings);
|
||||
self.node_graph_warnings = warnings;
|
||||
|
||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||
let result = self.executor.update(proto_network).map_err(|(types, e)| {
|
||||
let updated = self.executor.update(proto_network).map(|(output, types)| {
|
||||
self.output = output;
|
||||
types
|
||||
});
|
||||
let result = updated.map_err(|(types, e)| {
|
||||
self.node_graph_errors.clone_from(&e);
|
||||
(types, format!("{e:?}"))
|
||||
});
|
||||
@@ -591,7 +564,7 @@ impl NodeRuntime {
|
||||
paths.into()
|
||||
};
|
||||
let mut errors = Vec::new();
|
||||
let output = self.executor.output();
|
||||
let output = self.output.node();
|
||||
let mut pending = vec![(vec![paths(output)], output, error)];
|
||||
while let Some((mut trace, node, error)) = pending.pop() {
|
||||
let passed = self.executor.trace_error(node, error);
|
||||
@@ -908,59 +881,22 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_missing_resource_renders_with_a_warning_on_its_node() {
|
||||
async fn a_resource_that_loads_recompiles_the_unchanged_network() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graphene_std::raster_nodes::std_nodes::image;
|
||||
|
||||
let mut editor = editor().await;
|
||||
|
||||
// The layer shows an 'Image' node holding an image the document has no record of
|
||||
let image_node = NodeId::new();
|
||||
let missing_image = NodeInput::value(TaggedValue::Resource(ResourceId::new()), false);
|
||||
let template = resolve_proto_node_type(image::IDENTIFIER).unwrap().node_template_input_override([None, Some(missing_image)]);
|
||||
editor.active_document_mut().network_interface.insert_node(image_node, template, &[]);
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(image_node),
|
||||
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
|
||||
});
|
||||
|
||||
send_update(&mut editor);
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
assert!(evaluated(&mut editor), "the graph should render with the missing image left empty");
|
||||
assert!(editor.portfolio_message_handler_mut().executor.take_evaluation_errors().is_none());
|
||||
|
||||
let resolved_types = &editor.active_document().network_interface.resolved_types;
|
||||
assert!(resolved_types.node_graph_errors.is_empty(), "{:?}", resolved_types.node_graph_errors);
|
||||
let warnings = resolved_types.node_graph_warnings.as_slice();
|
||||
let expected = GraphErrorType::MissingResource { index: 1 };
|
||||
assert!(matches!(warnings, [warning] if warning.node_path == [image_node] && warning.error == expected), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_resource_that_fails_to_load_renders_with_a_fallback_until_it_loads() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
|
||||
use crate::test_utils::test_prelude::{Color, Image};
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
|
||||
use graphene_std::raster_nodes::std_nodes::image;
|
||||
|
||||
/// Handles the message, lets the runtime compile and evaluate whatever it queued, and gives back the graph's warnings and whether it drew an image.
|
||||
async fn render_after(editor: &mut EditorTestUtils, message: impl Into<Message>) -> (GraphErrors, bool) {
|
||||
/// Handles the message, lets the runtime compile and evaluate whatever it queued, and gives back whether it drew an image.
|
||||
async fn image_drawn_after(editor: &mut EditorTestUtils, message: impl Into<Message>) -> bool {
|
||||
editor.dispatch(message);
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
let messages = editor.dispatch(Message::Wake);
|
||||
let image_drawn = messages
|
||||
messages
|
||||
.iter()
|
||||
.any(|message| matches!(message, FrontendMessage::UpdateImageData { canvas_ids_in_use, .. } if !canvas_ids_in_use.is_empty()));
|
||||
|
||||
let resolved_types = &editor.active_document().network_interface.resolved_types;
|
||||
assert!(resolved_types.node_graph_errors.is_empty(), "{:?}", resolved_types.node_graph_errors);
|
||||
(resolved_types.node_graph_warnings.clone(), image_drawn)
|
||||
.any(|message| matches!(message, FrontendMessage::UpdateImageData { canvas_ids_in_use, .. } if !canvas_ids_in_use.is_empty()))
|
||||
}
|
||||
|
||||
let mut editor = editor().await;
|
||||
@@ -987,71 +923,50 @@ mod tests {
|
||||
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
|
||||
});
|
||||
|
||||
let (warnings, _) = render_after(&mut editor, NodeGraphMessage::RunDocumentGraph).await;
|
||||
assert!(warnings.is_empty(), "the graph shouldn't run while the image may still load: {warnings:?}");
|
||||
|
||||
// Failing to load sends the network while the image has no data
|
||||
let failed = ResourceMessage::ResolveFailed { resource_id }.into();
|
||||
let (warnings, image_drawn) = render_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: failed }).await;
|
||||
let expected = GraphErrorType::MissingResource { index: 1 };
|
||||
assert!(
|
||||
matches!(warnings.as_slice(), [warning] if warning.node_path == [image_node] && warning.error == expected),
|
||||
"{warnings:?}"
|
||||
);
|
||||
assert!(!image_drawn, "the image that failed to load should be left empty");
|
||||
image_drawn_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: failed }).await;
|
||||
|
||||
// Loading it later, as a retry would, has to recompile the unchanged network
|
||||
let data: Arc<[u8]> = Image::new(2, 2, Color::BLACK).to_png().into();
|
||||
let hash = ResourceHash::from(data.as_ref());
|
||||
editor.dispatch(ResourceStorageMessage::Store { data });
|
||||
let resolved = ResourceMessage::Resolved { resource_id, source, hash }.into();
|
||||
let (warnings, image_drawn) = render_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: resolved }).await;
|
||||
assert!(warnings.is_empty(), "the warning should clear once the image loads: {warnings:?}");
|
||||
assert!(image_drawn, "the image should be drawn once it loads");
|
||||
assert!(image_drawn_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: resolved }).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_export_is_refused_while_its_resources_load() {
|
||||
async fn a_missing_resource_renders_with_an_error_traced_through_its_node() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use graph_craft::application_io::resource::{DataSource, ResourceId};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graphene_std::platform_application_io::MissingResourceError;
|
||||
use graphene_std::raster_nodes::std_nodes::image;
|
||||
|
||||
/// Requests an export and lets the runtime evaluate whatever was sent, giving back whether it explained a refusal and whether it exported.
|
||||
async fn refused_and_exported(editor: &mut EditorTestUtils) -> (bool, bool) {
|
||||
let messages = editor.dispatch(PortfolioMessage::SubmitDocumentExport {
|
||||
name: "export".to_string(),
|
||||
file_type: FileType::Svg,
|
||||
scale_factor: 1.,
|
||||
bounds: ExportBounds::AllArtwork,
|
||||
artboard_name: None,
|
||||
artboard_count: 0,
|
||||
});
|
||||
let refused = messages.iter().any(|message| matches!(message, FrontendMessage::DisplayDialog { .. }));
|
||||
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
(refused, exported(editor))
|
||||
}
|
||||
|
||||
let mut editor = editor().await;
|
||||
let document_id = editor.portfolio_message_handler().active_document_id.unwrap();
|
||||
|
||||
// An 'Image' node whose image is known only by where to load it from
|
||||
let resource_id = ResourceId::new();
|
||||
let source = DataSource::Url("https://example.com/image.png".parse().unwrap());
|
||||
editor.active_document_mut().resources.registry.push_source_back(&resource_id, source);
|
||||
let template = resolve_proto_node_type(image::IDENTIFIER)
|
||||
.unwrap()
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Resource(resource_id), false))]);
|
||||
editor.active_document_mut().network_interface.insert_node(NodeId::new(), template, &[]);
|
||||
// The layer shows an 'Image' node holding an image the document has no record of
|
||||
let image_node = NodeId::new();
|
||||
let missing_image = NodeInput::value(TaggedValue::Resource(ResourceId::new()), false);
|
||||
let template = resolve_proto_node_type(image::IDENTIFIER).unwrap().node_template_input_override([None, Some(missing_image)]);
|
||||
editor.active_document_mut().network_interface.insert_node(image_node, template, &[]);
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(image_node),
|
||||
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
|
||||
});
|
||||
|
||||
let outcome = refused_and_exported(&mut editor).await;
|
||||
assert_eq!(outcome, (true, false), "the export shouldn't capture the image's fallback while it may still load");
|
||||
send_update(&mut editor);
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
assert!(evaluated(&mut editor));
|
||||
|
||||
// Once the image fails to load, its fallback is all there is to export
|
||||
let failed = ResourceMessage::ResolveFailed { resource_id }.into();
|
||||
editor.dispatch(PortfolioMessage::DocumentPassMessage { document_id, message: failed });
|
||||
let outcome = refused_and_exported(&mut editor).await;
|
||||
assert_eq!(outcome, (false, true), "the export should go ahead once nothing is left loading");
|
||||
let errors = editor.portfolio_message_handler_mut().executor.take_evaluation_errors().unwrap();
|
||||
assert!(
|
||||
errors
|
||||
.iter()
|
||||
.any(|(error, trace)| error.is::<MissingResourceError>() && trace.iter().flatten().any(|path| **path == [image_node])),
|
||||
"{errors:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -398,7 +398,8 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeTemplateImplementation, shipped_node_id};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -429,8 +430,20 @@ mod tests {
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
// The node adding Merge's content to the stack
|
||||
let Some(NodeTemplateImplementation::Network(merge_network)) = resolve_network_node_type("Merge").map(|merge| &merge.node_template.implementation) else {
|
||||
panic!("Merge should be a network node")
|
||||
};
|
||||
let Some((&extend_id, _)) = merge_network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER))
|
||||
else {
|
||||
panic!("Merge should extend the stack with its content")
|
||||
};
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", extend_id))]);
|
||||
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
|
||||
assert_eq!(
|
||||
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
||||
|
||||
@@ -423,6 +423,17 @@ impl EditorTestUtils {
|
||||
self.create_node(node_type, Some((x, y))).await
|
||||
}
|
||||
|
||||
/// Adds an empty subgraph at the grid position, as the graph's New Custom Node button does.
|
||||
pub async fn create_empty_subgraph_at(&mut self, x: i32, y: i32) -> NodeId {
|
||||
let node_id = NodeId::new();
|
||||
self.handle_message(NodeGraphMessage::CreateEmptySubgraph {
|
||||
node_id: Some(node_id),
|
||||
xy: Some((x, y)),
|
||||
})
|
||||
.await;
|
||||
node_id
|
||||
}
|
||||
|
||||
async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
|
||||
let node_id = NodeId::new();
|
||||
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
|
||||
+16
-2
@@ -34,12 +34,24 @@
|
||||
background: #222;
|
||||
}
|
||||
|
||||
body.loading-progress::before {
|
||||
background-image:
|
||||
url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' rx='2' fill='%23eee'/></svg>"),
|
||||
url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'><rect width='100%' height='100%' rx='2' fill='%23444'/></svg>");
|
||||
background-position: left calc(50vw - 80px) top calc(50vh + 64px);
|
||||
background-size:
|
||||
calc(var(--loading-progress, 0) * 160px) 4px,
|
||||
160px 4px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
body::after {
|
||||
content: "";
|
||||
display: block;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
border-radius: 50%;
|
||||
@@ -50,6 +62,8 @@
|
||||
@media (prefers-reduced-motion) {
|
||||
border: none;
|
||||
animation: none;
|
||||
width: auto;
|
||||
height: auto;
|
||||
content: "Loading…";
|
||||
font-family: Arial, sans-serif;
|
||||
font-size: 24px;
|
||||
@@ -58,10 +72,10 @@
|
||||
|
||||
@keyframes spinning-loading-indicator {
|
||||
0% {
|
||||
transform: translate(-30px, -30px) rotate(0deg);
|
||||
transform: translate(-50%, -50%) rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: translate(-30px, -30px) rotate(360deg);
|
||||
transform: translate(-50%, -50%) rotate(360deg);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import type { MessageName, SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import { joinSessionFromUrl, loadDemoArtwork } from "/src/utility-functions/network";
|
||||
import { operatingSystem } from "/src/utility-functions/platform";
|
||||
import { registerServiceWorker } from "/src/utility-functions/service-worker";
|
||||
import { initWasm } from "/src/utility-functions/wasm-loader";
|
||||
import { EditorWrapper, receiveNativeMessage } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { FrontendMessage } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
@@ -18,6 +19,10 @@
|
||||
try {
|
||||
// Initialize the editor wrapper
|
||||
const wrapper = await initWasm();
|
||||
|
||||
// Register the service worker, except in dev mode and native builds
|
||||
if (!import.meta.env.DEV && import.meta.env.MODE !== "native" && "serviceWorker" in navigator) registerServiceWorker();
|
||||
|
||||
for (const [name, f] of Object.entries(wrapper)) {
|
||||
if (name.startsWith("__node_registry") || name.startsWith("__migration_registry")) f();
|
||||
}
|
||||
@@ -57,6 +62,12 @@
|
||||
{/if}
|
||||
|
||||
<style lang="scss">
|
||||
// Disable the loading indicator
|
||||
body:has(.main-window, .startup-error)::before,
|
||||
body:has(.main-window, .startup-error)::after {
|
||||
content: none !important;
|
||||
}
|
||||
|
||||
.startup-error {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
@@ -82,12 +82,6 @@
|
||||
<MainWindow />
|
||||
|
||||
<style lang="scss">
|
||||
// Disable the spinning loading indicator
|
||||
body::before,
|
||||
body::after {
|
||||
content: none !important;
|
||||
}
|
||||
|
||||
:root {
|
||||
--color-0-black: #000;
|
||||
--color-1-nearblack: #111;
|
||||
|
||||
@@ -84,10 +84,12 @@
|
||||
--row-height: 24px;
|
||||
|
||||
&:has(.slider-input) {
|
||||
margin-top: 16px;
|
||||
margin-top: 8px;
|
||||
|
||||
.number-input {
|
||||
flex: 0 0 auto;
|
||||
// Level with the gradient strip, below the slider's room for its midpoint diamonds
|
||||
margin-top: 8px;
|
||||
margin-left: 8px;
|
||||
min-width: 0;
|
||||
width: calc(24px + 8px + 24px);
|
||||
|
||||
@@ -670,7 +670,7 @@
|
||||
|
||||
<LayoutCol
|
||||
class="slider-input"
|
||||
classes={{ narrow, disabled, "range-slider": rangeSlider }}
|
||||
classes={{ narrow, disabled, "range-slider": rangeSlider, "with-midpoints": showMidpoints }}
|
||||
styles={{
|
||||
"--gradient-start": trackStartCSS,
|
||||
"--gradient-end": trackEndCSS,
|
||||
@@ -830,11 +830,17 @@
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
// Room for the diamonds above the strip, inside the widget so rows that clip their overflow still show them
|
||||
&.with-midpoints {
|
||||
padding-top: 8px;
|
||||
}
|
||||
|
||||
.midpoint-track {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: var(--marker-half-width);
|
||||
right: var(--marker-half-width);
|
||||
height: 8px;
|
||||
|
||||
.midpoint {
|
||||
position: absolute;
|
||||
|
||||
Vendored
+2
-1
@@ -6,8 +6,9 @@ interface Window {
|
||||
receiveNativeMessage?: (buffer: ArrayBuffer) => void;
|
||||
}
|
||||
|
||||
// Build-time constant injected by the `wasmSplitting` plugin in `vite.config.ts`
|
||||
// Build-time constants injected by plugins in `vite.config.ts`
|
||||
declare const __WASM_PART_COUNT__: number;
|
||||
declare const __WASM_SIZE__: number;
|
||||
|
||||
// Graphite's custom "pointerlockmove" event dispatched by input.ts for pointer lock in the CEF desktop app
|
||||
interface WindowEventMap {
|
||||
|
||||
@@ -124,6 +124,7 @@ import NodeAsVector from "/../branding/assets/16x16-nodes/node-as-vector.svg";
|
||||
import NodeAverage from "/../branding/assets/16x16-nodes/node-average.svg";
|
||||
import NodeBakeTransform from "/../branding/assets/16x16-nodes/node-bake-transform.svg";
|
||||
import NodeBasicBrush from "/../branding/assets/16x16-nodes/node-basic-brush.svg";
|
||||
import NodeBevelAndEmboss from "/../branding/assets/16x16-nodes/node-bevel-and-emboss.svg";
|
||||
import NodeBevel from "/../branding/assets/16x16-nodes/node-bevel.svg";
|
||||
import NodeBlackAndWhite from "/../branding/assets/16x16-nodes/node-black-and-white.svg";
|
||||
import NodeBlendMode from "/../branding/assets/16x16-nodes/node-blend-mode.svg";
|
||||
@@ -223,6 +224,7 @@ import NodeImageToChannels from "/../branding/assets/16x16-nodes/node-image-to-c
|
||||
import NodeImage from "/../branding/assets/16x16-nodes/node-image.svg";
|
||||
import NodeIndexPoints from "/../branding/assets/16x16-nodes/node-index-points.svg";
|
||||
import NodeIndices from "/../branding/assets/16x16-nodes/node-indices.svg";
|
||||
import NodeInnerGlow from "/../branding/assets/16x16-nodes/node-inner-glow.svg";
|
||||
import NodeInnerShadow from "/../branding/assets/16x16-nodes/node-inner-shadow.svg";
|
||||
import NodeInvertTransform from "/../branding/assets/16x16-nodes/node-invert-transform.svg";
|
||||
import NodeInvert from "/../branding/assets/16x16-nodes/node-invert.svg";
|
||||
@@ -277,6 +279,7 @@ import NodeOpacity from "/../branding/assets/16x16-nodes/node-opacity.svg";
|
||||
import NodeOpenEnds from "/../branding/assets/16x16-nodes/node-open-ends.svg";
|
||||
import NodeOriginsToPolyline from "/../branding/assets/16x16-nodes/node-origins-to-polyline.svg";
|
||||
import NodeOuterGlow from "/../branding/assets/16x16-nodes/node-outer-glow.svg";
|
||||
import NodeOutline from "/../branding/assets/16x16-nodes/node-outline.svg";
|
||||
import NodePackStrips from "/../branding/assets/16x16-nodes/node-pack-strips.svg";
|
||||
import NodePassthrough from "/../branding/assets/16x16-nodes/node-passthrough.svg";
|
||||
import NodePathIsClosed from "/../branding/assets/16x16-nodes/node-path-is-closed.svg";
|
||||
@@ -325,6 +328,7 @@ import NodeRoot from "/../branding/assets/16x16-nodes/node-root.svg";
|
||||
import NodeRoundCorners from "/../branding/assets/16x16-nodes/node-round-corners.svg";
|
||||
import NodeRound from "/../branding/assets/16x16-nodes/node-round.svg";
|
||||
import NodeSamplePolyline from "/../branding/assets/16x16-nodes/node-sample-polyline.svg";
|
||||
import NodeSatin from "/../branding/assets/16x16-nodes/node-satin.svg";
|
||||
import NodeScatterPoints from "/../branding/assets/16x16-nodes/node-scatter-points.svg";
|
||||
import NodeSelectiveColor from "/../branding/assets/16x16-nodes/node-selective-color.svg";
|
||||
import NodeSeparatePaths from "/../branding/assets/16x16-nodes/node-separate-paths.svg";
|
||||
@@ -415,6 +419,7 @@ export const ICON_16X16_NODES = {
|
||||
NodeBakeTransform: { svg: NodeBakeTransform, size: 16 },
|
||||
NodeBasicBrush: { svg: NodeBasicBrush, size: 16 },
|
||||
NodeBevel: { svg: NodeBevel, size: 16 },
|
||||
NodeBevelAndEmboss: { svg: NodeBevelAndEmboss, size: 16 },
|
||||
NodeBlackAndWhite: { svg: NodeBlackAndWhite, size: 16 },
|
||||
NodeBlend: { svg: NodeBlend, size: 16 },
|
||||
NodeBlendMode: { svg: NodeBlendMode, size: 16 },
|
||||
@@ -513,6 +518,7 @@ export const ICON_16X16_NODES = {
|
||||
NodeImageToChannels: { svg: NodeImageToChannels, size: 16 },
|
||||
NodeIndexPoints: { svg: NodeIndexPoints, size: 16 },
|
||||
NodeIndices: { svg: NodeIndices, size: 16 },
|
||||
NodeInnerGlow: { svg: NodeInnerGlow, size: 16 },
|
||||
NodeInnerShadow: { svg: NodeInnerShadow, size: 16 },
|
||||
NodeInvert: { svg: NodeInvert, size: 16 },
|
||||
NodeInvertTransform: { svg: NodeInvertTransform, size: 16 },
|
||||
@@ -567,6 +573,7 @@ export const ICON_16X16_NODES = {
|
||||
NodeOpenEnds: { svg: NodeOpenEnds, size: 16 },
|
||||
NodeOriginsToPolyline: { svg: NodeOriginsToPolyline, size: 16 },
|
||||
NodeOuterGlow: { svg: NodeOuterGlow, size: 16 },
|
||||
NodeOutline: { svg: NodeOutline, size: 16 },
|
||||
NodePackStrips: { svg: NodePackStrips, size: 16 },
|
||||
NodePassthrough: { svg: NodePassthrough, size: 16 },
|
||||
NodePath: { svg: NodePath, size: 16 },
|
||||
@@ -615,6 +622,7 @@ export const ICON_16X16_NODES = {
|
||||
NodeRound: { svg: NodeRound, size: 16 },
|
||||
NodeRoundCorners: { svg: NodeRoundCorners, size: 16 },
|
||||
NodeSamplePolyline: { svg: NodeSamplePolyline, size: 16 },
|
||||
NodeSatin: { svg: NodeSatin, size: 16 },
|
||||
NodeScatterPoints: { svg: NodeScatterPoints, size: 16 },
|
||||
NodeSelectiveColor: { svg: NodeSelectiveColor, size: 16 },
|
||||
NodeSeparatePaths: { svg: NodeSeparatePaths, size: 16 },
|
||||
|
||||
@@ -2,12 +2,6 @@
|
||||
|
||||
import { mount, unmount } from "svelte";
|
||||
import App from "/src/App.svelte";
|
||||
import { registerServiceWorker } from "/src/utility-functions/service-worker";
|
||||
|
||||
// Register the service worker, except in dev mode and native (CEF) builds
|
||||
if (!import.meta.env.DEV && import.meta.env.MODE !== "native" && "serviceWorker" in navigator) {
|
||||
registerServiceWorker();
|
||||
}
|
||||
|
||||
document.body.setAttribute("data-app-container", "");
|
||||
|
||||
|
||||
@@ -19,6 +19,11 @@ const DEFERRED_ENTRIES = new Map(DEFERRED_CACHE_MANIFEST.map((entry) => [new URL
|
||||
// Caching strategies
|
||||
// ==================
|
||||
|
||||
function withoutRedirect(response) {
|
||||
if (!response.redirected) return response;
|
||||
return new Response(response.body, { status: response.status, statusText: response.statusText, headers: response.headers });
|
||||
}
|
||||
|
||||
function isCacheable(response) {
|
||||
// Cache normal successful responses and opaque responses (cross-origin no-cors, e.g. <link> stylesheets)
|
||||
return response.ok || response.type === "opaque";
|
||||
@@ -47,6 +52,20 @@ async function networkFirst(request, cacheName) {
|
||||
}
|
||||
}
|
||||
|
||||
async function latestIndexHtml(request) {
|
||||
const cache = await caches.open(STATIC_CACHE_NAME);
|
||||
const cached = await cache.match("/index.html");
|
||||
if (!cached) return fetch(request);
|
||||
if (!navigator.onLine) return cached;
|
||||
|
||||
const network = fetch("/", { cache: "no-cache" }).then(
|
||||
(response) => (response.ok ? withoutRedirect(response) : cached),
|
||||
() => cached,
|
||||
);
|
||||
const timeout = new Promise((resolve) => setTimeout(() => resolve(cached), 1000));
|
||||
return Promise.race([network, timeout]);
|
||||
}
|
||||
|
||||
// ================
|
||||
// Lifecycle events
|
||||
// ================
|
||||
@@ -60,15 +79,7 @@ self.addEventListener("install", (event) => {
|
||||
PRECACHE_MANIFEST.map(async (entry) => {
|
||||
const response = await fetch(entry.url);
|
||||
if (!response.ok) throw new Error(`Precache fetch failed for ${entry.url}: ${response.status}`);
|
||||
// Strip the `redirected` flag which causes errors when served via respondWith
|
||||
const cleaned = response.redirected
|
||||
? new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: response.headers,
|
||||
})
|
||||
: response;
|
||||
await cache.put(entry.url, cleaned);
|
||||
await cache.put(entry.url, withoutRedirect(response));
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -148,15 +159,9 @@ self.addEventListener("fetch", (event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Navigation requests: serve cached index.html for all routes (SPA pattern)
|
||||
// Navigation requests: serve index.html for all routes (SPA pattern)
|
||||
if (request.mode === "navigate") {
|
||||
event.respondWith(
|
||||
(async () => {
|
||||
const cache = await caches.open(STATIC_CACHE_NAME);
|
||||
const cached = await cache.match("/index.html");
|
||||
return cached || fetch(request);
|
||||
})(),
|
||||
);
|
||||
event.respondWith(latestIndexHtml(request));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
export async function registerServiceWorker() {
|
||||
try {
|
||||
const registration = await navigator.serviceWorker.register("/service-worker.js", { scope: "/" });
|
||||
|
||||
// When a new service worker is found, auto-reload once it activates
|
||||
registration.addEventListener("updatefound", () => {
|
||||
const newWorker = registration.installing;
|
||||
newWorker?.addEventListener("statechange", () => {
|
||||
// Only reload if there was a previous controller, meaning this is an update, not first install
|
||||
if (newWorker.state === "activated" && navigator.serviceWorker.controller) window.location.reload();
|
||||
});
|
||||
navigator.serviceWorker.addEventListener("controllerchange", () => {
|
||||
const controller = navigator.serviceWorker.controller;
|
||||
const reloadIfRemoved = async () => {
|
||||
if (controller?.state === "activated" && !(await caches.match(import.meta.url))) window.location.reload();
|
||||
};
|
||||
reloadIfRemoved();
|
||||
controller?.addEventListener("statechange", reloadIfRemoved);
|
||||
});
|
||||
|
||||
const registration = await navigator.serviceWorker.register("/service-worker.js", { scope: "/" });
|
||||
|
||||
const activeWorker = registration.active || registration.waiting || registration.installing;
|
||||
if (!activeWorker) return;
|
||||
|
||||
|
||||
@@ -4,22 +4,57 @@ import wasmBinaryUrl from "/wrapper/pkg/graphite_wasm_wrapper_bg.wasm?url";
|
||||
// Initializes the editor's Wasm module, rejoining the parts that CI deployments split the binary into
|
||||
// to fit under the single-file size limit (see `wasmSplitting` in `vite.config.ts`)
|
||||
export async function initWasm() {
|
||||
// Local and native builds keep the binary whole, letting the wasm-bindgen glue code load it directly
|
||||
if (__WASM_PART_COUNT__ <= 1) return init();
|
||||
if (__WASM_PART_COUNT__ <= 1 && __WASM_SIZE__ === 0) return init();
|
||||
|
||||
// Fetch all parts in parallel (served from the service worker's precache once it is installed)
|
||||
const partRequests = [];
|
||||
for (let index = 0; index < __WASM_PART_COUNT__; index += 1) {
|
||||
partRequests.push(fetch(wasmBinaryUrl.replace(/\.wasm$/, `-part${index}.wasm`)));
|
||||
}
|
||||
const partResponses = await Promise.all(partRequests);
|
||||
const partUrls = __WASM_PART_COUNT__ <= 1 ? [wasmBinaryUrl] : Array.from({ length: __WASM_PART_COUNT__ }, (_, index) => wasmBinaryUrl.replace(/\.wasm$/, `-part${index}.wasm`));
|
||||
// Read the parts straight from the service worker's precache when it has them
|
||||
const partResponses = (await cachedParts(partUrls)) || downloadParts(partUrls);
|
||||
|
||||
const failedResponse = partResponses.find((response) => !response.ok);
|
||||
if (failedResponse) throw new Error(`Failed to fetch Wasm binary part (status ${failedResponse.status}): ${failedResponse.url}`);
|
||||
// eslint-disable-next-line camelcase
|
||||
if (partResponses.length === 1) return init({ module_or_path: await partResponses[0] });
|
||||
|
||||
// Rejoin the parts and hand them to wasm-bindgen as a single response, with the MIME type needed for streaming compilation
|
||||
const parts = await Promise.all(partResponses.map((response) => response.blob()));
|
||||
const parts = await Promise.all(partResponses.map(async (response) => (await response).blob()));
|
||||
const joined = new Response(new Blob(parts), { headers: { "Content-Type": "application/wasm" } });
|
||||
// eslint-disable-next-line camelcase
|
||||
return init({ module_or_path: joined });
|
||||
}
|
||||
|
||||
async function cachedParts(urls: string[]): Promise<Response[] | undefined> {
|
||||
try {
|
||||
const responses = await Promise.all(urls.map((url) => caches.match(url)));
|
||||
if (responses.every((response): response is Response => response !== undefined)) return responses;
|
||||
} catch {
|
||||
// Cache Storage is unavailable, such as in some private windows
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function downloadParts(urls: string[]): Promise<Response>[] {
|
||||
const trackProgress = trackDownloadProgress();
|
||||
|
||||
return urls.map(async (url) => {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(`Failed to fetch Wasm binary part (status ${response.status}): ${response.url}`);
|
||||
return trackProgress(response);
|
||||
});
|
||||
}
|
||||
|
||||
function trackDownloadProgress(): (response: Response) => Response {
|
||||
let loadedBytes = 0;
|
||||
document.body.style.setProperty("--loading-progress", "0");
|
||||
document.body.classList.add("loading-progress");
|
||||
|
||||
return (response) => {
|
||||
if (!response.body) return response;
|
||||
|
||||
const counter = new TransformStream<Uint8Array, Uint8Array>({
|
||||
transform(chunk, controller) {
|
||||
loadedBytes += chunk.byteLength;
|
||||
document.body.style.setProperty("--loading-progress", String(Math.min(loadedBytes / __WASM_SIZE__, 1)));
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
});
|
||||
return new Response(response.body.pipeThrough(counter), { status: response.status, statusText: response.statusText, headers: response.headers });
|
||||
};
|
||||
}
|
||||
+16
-1
@@ -18,11 +18,12 @@ export default defineConfig(({ mode }) => {
|
||||
wasmEditorReload(),
|
||||
staticAssets(),
|
||||
mode !== "native" && thirdPartyLicenses(),
|
||||
mode !== "native" && wasmSize(),
|
||||
mode !== "native" && wasmSplitting(),
|
||||
mode !== "native" && serviceWorker(),
|
||||
],
|
||||
// Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active
|
||||
define: { __WASM_PART_COUNT__: "1" },
|
||||
define: { __WASM_SIZE__: "0", __WASM_PART_COUNT__: "1" },
|
||||
resolve: {
|
||||
alias: [
|
||||
...(mode === "native" ? [{ find: /^\/wrapper\/pkg\//, replacement: "/wrapper/pkg-native/" }] : []),
|
||||
@@ -177,6 +178,20 @@ function thirdPartyLicenses(): PluginOption {
|
||||
};
|
||||
}
|
||||
|
||||
function wasmSize(): PluginOption {
|
||||
return {
|
||||
name: "wasm-size",
|
||||
config(_, { command }) {
|
||||
if (command !== "build") return;
|
||||
|
||||
const wasmPath = path.resolve(projectRootDir, "wrapper/pkg/graphite_wasm_wrapper_bg.wasm");
|
||||
if (!existsSync(wasmPath)) return;
|
||||
|
||||
return { define: { __WASM_SIZE__: String(statSync(wasmPath).size) } };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Splits the Wasm binary into parts small enough for Cloudflare Pages' 25 MiB single-file limit, rejoined at runtime by `initWasm()` in `src/utility-functions/wasm-loader.ts`.
|
||||
// Only active when the `SPLIT_WASM` environment variable is set, which CI does for deployments; local builds keep the single file.
|
||||
function wasmSplitting(): PluginOption {
|
||||
|
||||
+24
-2
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
|
||||
}
|
||||
```
|
||||
|
||||
Only the definitions of nodes built from a nested network, such as the empty "Custom Node", are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
|
||||
None of these definitions are written by hand. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`. A built-in node made from a subgraph has its definition generated from the `graph` macro (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
|
||||
|
||||
## Inspector
|
||||
|
||||
@@ -127,7 +127,29 @@ fn opacity<T>(
|
||||
|
||||
## Additional Macro Options
|
||||
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `unit`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, while `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `step`, `display_decimal_places`, `unit`, `integer`, `labels`, `blank_assist`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, `#[display_decimal_places(2)]` sets how many decimal places a number's widget shows, `#[integer]` makes a number or Vec2 widget take only integers, `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[blank_assist(false)]` drops the space a widget leaves for its assist area. `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
|
||||
## Creating a node from a subgraph
|
||||
|
||||
A node built from other nodes uses the `graph` macro, which registers the subgraph as a catalog definition. It takes `category`, `icon`, `name`, and `version` as `node` does, plus `layer` for a node that starts as a layer. Unlike a proto node's, a graph's name (or the title derived from its function name) is also its catalog identifier, which documents store. The function's parameters are the subgraph's imports, which are parsed like a proto node's parameters and take the same value and widget attributes. On an import, `#[hard]` bounds the Inspector widget without clamping a value wired into it. `out!(...)` names the exports. In the body, `>>` feeds its left side into the primary input of the node on its right, every other parameter is named in the call, and a bare name feeds the binding or import of that name into the parameter of the same name. State methods after a call, each written once, set the node's position in grid units (`.at(x, y)`), its display name (`.named("…")`), its flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`), and its call argument (`.call_argument::<Footprint>()`, or `impl Any` for a generic one). An output's name after the call or a binding, like `.captures`, wires from that output instead of the primary one, and goes after any state methods. The body ends with one value per export, as a final expression or with `return`. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
|
||||
|
||||
```rs
|
||||
/// Loads an image from a given URL.
|
||||
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
|
||||
pub fn load_image(
|
||||
_: (),
|
||||
/// The web address or local asset path of the image to load.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
) -> out!(
|
||||
/// The loaded image.
|
||||
image,
|
||||
) {
|
||||
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
|
||||
}
|
||||
```
|
||||
|
||||
Each node, parameter, and output name resolves through the module the `node` or `graph` macro generates for that node, named after its function, so a misspelled one is reported where it's written. The module's `PARAMETER_COUNT` lets the macro reject `>>` into a node with no parameters. Proto nodes don't name their outputs in that module, so only a graph's outputs can be chosen by name. Every input a call leaves out keeps the default from the node's own definition.
|
||||
|
||||
## Executing a document `NodeNetwork`
|
||||
|
||||
|
||||
@@ -531,12 +531,20 @@ tagged_value! {
|
||||
CellularDistanceFunction(raster_nodes::adjustments::CellularDistanceFunction),
|
||||
CellularReturnType(raster_nodes::adjustments::CellularReturnType),
|
||||
DomainWarpType(raster_nodes::adjustments::DomainWarpType),
|
||||
MandelbrotFractal(raster_nodes::adjustments::MandelbrotFractal),
|
||||
MandelbrotExterior(raster_nodes::adjustments::MandelbrotExterior),
|
||||
MandelbrotInterior(raster_nodes::adjustments::MandelbrotInterior),
|
||||
RelativeAbsolute(raster_nodes::adjustments::RelativeAbsolute),
|
||||
SelectiveColorChoice(raster_nodes::adjustments::SelectiveColorChoice),
|
||||
TonalRange(raster_nodes::adjustments::TonalRange),
|
||||
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
|
||||
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
|
||||
GlowTechnique(graphic_types::GlowTechnique),
|
||||
GlowSource(graphic_types::GlowSource),
|
||||
MaskMode(graphic_types::MaskMode),
|
||||
BevelStyle(graphic_types::BevelStyle),
|
||||
BevelDirection(graphic_types::BevelDirection),
|
||||
BevelTechnique(graphic_types::BevelTechnique),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -687,6 +695,46 @@ impl TaggedValue {
|
||||
})
|
||||
}
|
||||
|
||||
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
||||
let mut choices = input.split("::");
|
||||
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
||||
if first == "StrokeAlign" {
|
||||
return Some(match second {
|
||||
"Center" => vector::style::StrokeAlign::Center,
|
||||
"Inside" => vector::style::StrokeAlign::Inside,
|
||||
"Outside" => vector::style::StrokeAlign::Outside,
|
||||
_ => {
|
||||
log::error!("Invalid StrokeAlign default type variant: {input}");
|
||||
return None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
log::error!("Invalid StrokeAlign default type: {input}");
|
||||
None
|
||||
}
|
||||
|
||||
fn to_blend_mode(input: &str) -> Option<core_types::blending::BlendMode> {
|
||||
use core_types::blending::BlendMode;
|
||||
|
||||
let Some(("BlendMode", variant)) = input.split_once("::").map(|(first, second)| (first.trim(), second.trim())) else {
|
||||
log::error!("Invalid BlendMode default type: {input}");
|
||||
return None;
|
||||
};
|
||||
|
||||
// The variants hidden from the standard list are valid defaults too
|
||||
let blend_mode = BlendMode::list()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha])
|
||||
.find(|blend_mode| format!("{blend_mode:?}") == variant)
|
||||
.copied();
|
||||
if blend_mode.is_none() {
|
||||
log::error!("Invalid BlendMode default type variant: {input}");
|
||||
}
|
||||
blend_mode
|
||||
}
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
@@ -706,9 +754,14 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||
() if ty == TypeId::of::<Footprint>() => to_footprint(string).map(TaggedValue::Footprint)?,
|
||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
|
||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
_ => return None,
|
||||
_ => {
|
||||
log::error!("No parser for a default value of type `{}`: {string}", concrete_type.name);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
Some(ty)
|
||||
}
|
||||
|
||||
@@ -602,10 +602,6 @@ pub enum GraphErrorType {
|
||||
NonConstantInput {
|
||||
index: usize,
|
||||
},
|
||||
/// The input's value refers to a resource the document can't resolve to its data.
|
||||
MissingResource {
|
||||
index: usize,
|
||||
},
|
||||
}
|
||||
impl Debug for GraphErrorType {
|
||||
// TODO: format with the document graph context so the input index is the same as in the graph UI.
|
||||
@@ -654,11 +650,6 @@ impl Debug for GraphErrorType {
|
||||
"Warning: an upstream node adapts to the visible canvas area, so this node's output changes when the view is panned or zoomed"
|
||||
),
|
||||
GraphErrorType::NonConstantInput { index } => write!(f, "Input {} must be a fixed value rather than computed by other nodes", index + 1),
|
||||
GraphErrorType::MissingResource { index } => write!(
|
||||
f,
|
||||
"Warning: input {} needs a font, image, or other resource that can't be found, so a fallback is used in its place",
|
||||
index + 1
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use crate::TokioSpawner;
|
||||
use graph_craft::document::value::{DAffine2, DVec2, RenderOutputType, TaggedValue, UVec2};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::core_types::ops::ConvertAsync;
|
||||
use graphene_std::core_types::transform::Footprint;
|
||||
@@ -9,7 +8,7 @@ use graphene_std::runtime::AsyncRuntime;
|
||||
use graphene_std::vector::{no_paths, paths_from_item_attributes};
|
||||
use graphene_std::{NodeError, Poll};
|
||||
use image::ImageFormat;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use std::error::Error;
|
||||
use std::io::Cursor;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -88,12 +87,12 @@ pub struct Framing {
|
||||
impl ExportSettings {
|
||||
/// Frame the artwork as it is at time zero, unless a size was given.
|
||||
/// Every frame of an animation shares this framing, so they all have one size.
|
||||
pub async fn framed(mut self, executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Self, Box<dyn Error>> {
|
||||
pub async fn framed(mut self, executor: &DynamicExecutor, output: &OutputHandle, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Self, Box<dyn Error>> {
|
||||
if self.size.0.is_some() && self.size.1.is_some() {
|
||||
return Ok(self);
|
||||
}
|
||||
|
||||
let [min, max] = artwork_bounds(executor, runtime, spawner).await?.ok_or("The document has no artwork to export")?;
|
||||
let [min, max] = artwork_bounds(executor, output, runtime, spawner).await?.ok_or("The document has no artwork to export")?;
|
||||
let resolution = ((max - min) * self.scale).round().max(DVec2::ONE).as_uvec2();
|
||||
self.framing = Some(Framing {
|
||||
transform: DAffine2::from_translation(min).inverse(),
|
||||
@@ -105,7 +104,7 @@ impl ExportSettings {
|
||||
|
||||
/// The document-space bounds of every layer including its stroke, artboards included, from the metadata of an SVG render.
|
||||
/// Content an artboard clips away still counts, since this has no layer tree to tell which artboard holds it.
|
||||
async fn artwork_bounds(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Option<[DVec2; 2]>, Box<dyn Error>> {
|
||||
async fn artwork_bounds(executor: &DynamicExecutor, output: &OutputHandle, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Option<[DVec2; 2]>, Box<dyn Error>> {
|
||||
// An identity viewport, since the default one is degenerate and its transforms come out NaN
|
||||
let render_config = RenderConfig {
|
||||
viewport: Footprint {
|
||||
@@ -118,7 +117,7 @@ async fn artwork_bounds(executor: &DynamicExecutor, runtime: &AsyncRuntime, spaw
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
};
|
||||
let TaggedValue::RenderOutput(output) = execute_until_settled(executor, runtime, spawner, render_config).await? else {
|
||||
let TaggedValue::RenderOutput(output) = execute_until_settled(executor, output, runtime, spawner, render_config).await? else {
|
||||
return Err("The document did not render".into());
|
||||
};
|
||||
|
||||
@@ -153,6 +152,7 @@ fn combine_bounds([a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]) -> [DV
|
||||
/// Renders the document at the given animation time, as SVG text for an SVG export and as pixels for every other file type.
|
||||
pub(crate) async fn render_frame(
|
||||
executor: &DynamicExecutor,
|
||||
output: &OutputHandle,
|
||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
||||
settings: ExportSettings,
|
||||
animation_time: Duration,
|
||||
@@ -187,7 +187,7 @@ pub(crate) async fn render_frame(
|
||||
}
|
||||
|
||||
// Execute the graph and extract its output
|
||||
match execute_until_settled(executor, runtime, spawner, render_config).await? {
|
||||
match execute_until_settled(executor, output, runtime, spawner, render_config).await? {
|
||||
TaggedValue::RenderOutput(output) => match output.data {
|
||||
RenderOutputType::Svg { svg, .. } => Ok(RenderedFrame::Svg(svg)),
|
||||
RenderOutputType::Texture(texture) => {
|
||||
@@ -263,13 +263,14 @@ fn encode_raster(file_type: FileType, data: Vec<u8>, width: u32, height: u32, tr
|
||||
|
||||
pub async fn export_document(
|
||||
executor: &DynamicExecutor,
|
||||
output: &OutputHandle,
|
||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
||||
output_path: PathBuf,
|
||||
settings: ExportSettings,
|
||||
runtime: &AsyncRuntime,
|
||||
spawner: &TokioSpawner,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let frame = render_frame(executor, wgpu_executor, settings, Duration::ZERO, runtime, spawner).await?;
|
||||
let frame = render_frame(executor, output, wgpu_executor, settings, Duration::ZERO, runtime, spawner).await?;
|
||||
write_frame(&output_path, settings, frame)?;
|
||||
|
||||
log::info!("Exported to: {}", output_path.display());
|
||||
@@ -305,8 +306,10 @@ impl AnimationParams {
|
||||
}
|
||||
|
||||
/// Export an animated GIF by rendering multiple frames at different animation times
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn export_gif(
|
||||
executor: &DynamicExecutor,
|
||||
output: &OutputHandle,
|
||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
||||
output_path: PathBuf,
|
||||
settings: ExportSettings,
|
||||
@@ -334,7 +337,7 @@ pub async fn export_gif(
|
||||
|
||||
log::debug!("Rendering frame {}/{} at time {:?}", frame_idx + 1, animation.frames, animation_time);
|
||||
|
||||
let RenderedFrame::Raster { data, width, height } = render_frame(executor, wgpu_executor, settings, animation_time, runtime, spawner).await? else {
|
||||
let RenderedFrame::Raster { data, width, height } = render_frame(executor, output, wgpu_executor, settings, animation_time, runtime, spawner).await? else {
|
||||
return Err("A GIF frame must render as pixels".into());
|
||||
};
|
||||
|
||||
@@ -355,8 +358,10 @@ pub async fn export_gif(
|
||||
}
|
||||
|
||||
/// Export an animation as one numbered file per frame beside the output path (`name_000.png`, `name_001.png`, ..., zero-padded to fit the frame count).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn export_image_sequence(
|
||||
executor: &DynamicExecutor,
|
||||
output: &OutputHandle,
|
||||
wgpu_executor: &wgpu_executor::WgpuExecutor,
|
||||
output_path: PathBuf,
|
||||
settings: ExportSettings,
|
||||
@@ -378,7 +383,7 @@ pub async fn export_image_sequence(
|
||||
// Print progress to stderr (overwrites previous line)
|
||||
eprint!("\rRendering frame {}/{}...", frame_idx + 1, animation.frames);
|
||||
|
||||
let frame = render_frame(executor, wgpu_executor, settings, animation_time, runtime, spawner).await?;
|
||||
let frame = render_frame(executor, output, wgpu_executor, settings, animation_time, runtime, spawner).await?;
|
||||
let frame_path = directory.join(format!("{stem}_{frame_idx:0digits$}.{extension}"));
|
||||
write_frame(&frame_path, settings, frame)?;
|
||||
}
|
||||
@@ -390,8 +395,14 @@ pub async fn export_image_sequence(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn execute_until_settled(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner, render_config: RenderConfig) -> Result<TaggedValue, Box<dyn Error>> {
|
||||
let execute = || executor.execute(render_config.into_context_with_generations(runtime.snapshot()));
|
||||
pub async fn execute_until_settled(
|
||||
executor: &DynamicExecutor,
|
||||
output: &OutputHandle,
|
||||
runtime: &AsyncRuntime,
|
||||
spawner: &TokioSpawner,
|
||||
render_config: RenderConfig,
|
||||
) -> Result<TaggedValue, Box<dyn Error>> {
|
||||
let execute = || executor.execute(output, render_config.into_context_with_generations(runtime.snapshot()));
|
||||
let mut frame = execute()?;
|
||||
while spawner.join().await {
|
||||
frame = execute()?;
|
||||
|
||||
@@ -12,7 +12,7 @@ use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graphene_std::application_io::ApplicationIo;
|
||||
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::collections::HashMap;
|
||||
@@ -111,13 +111,6 @@ pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_ap
|
||||
Ok(compiled_network.network)
|
||||
}
|
||||
|
||||
pub fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||
DynamicExecutor::new(proto_network).map_err(|errors| {
|
||||
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
||||
messages.join("\n").into()
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocument, Box<dyn Error>> {
|
||||
let (application_io, editor_api) = editor_api(document.gdd.as_ref()).await;
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
@@ -134,7 +127,11 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
|
||||
|
||||
impl CompiledDocument {
|
||||
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
|
||||
let executor = create_executor(self.proto_network)?;
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(self.proto_network).map_err(|(_, errors)| {
|
||||
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
||||
messages.join("\n")
|
||||
})?;
|
||||
self.runtime.update_sources(executor.sources());
|
||||
|
||||
let device = self.application_io.gpu_executor().ok_or("No GPU executor is available")?.context().device.clone();
|
||||
@@ -151,6 +148,7 @@ impl CompiledDocument {
|
||||
|
||||
Ok(Renderer {
|
||||
executor,
|
||||
output,
|
||||
application_io: self.application_io,
|
||||
runtime: self.runtime,
|
||||
spawner: self.spawner,
|
||||
@@ -162,6 +160,7 @@ impl CompiledDocument {
|
||||
/// Executes a compiled document, polling its GPU device until dropped.
|
||||
pub struct Renderer {
|
||||
pub executor: DynamicExecutor,
|
||||
pub output: OutputHandle,
|
||||
pub runtime: AsyncRuntime,
|
||||
pub spawner: Arc<TokioSpawner>,
|
||||
application_io: Arc<PlatformApplicationIo>,
|
||||
@@ -175,12 +174,12 @@ impl Renderer {
|
||||
|
||||
/// Fit `settings` to the artwork, unless they give a size.
|
||||
pub async fn frame(&self, settings: export::ExportSettings) -> Result<export::ExportSettings, Box<dyn Error>> {
|
||||
settings.framed(&self.executor, &self.runtime, &self.spawner).await
|
||||
settings.framed(&self.executor, &self.output, &self.runtime, &self.spawner).await
|
||||
}
|
||||
|
||||
/// Render one frame at `animation_time`.
|
||||
pub async fn render(&self, settings: export::ExportSettings, animation_time: std::time::Duration) -> Result<export::RenderedFrame, Box<dyn Error>> {
|
||||
export::render_frame(&self.executor, self.wgpu_executor(), settings, animation_time, &self.runtime, &self.spawner).await
|
||||
export::render_frame(&self.executor, &self.output, self.wgpu_executor(), settings, animation_time, &self.runtime, &self.spawner).await
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -198,14 +198,14 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let settings = renderer.frame(settings).await?;
|
||||
let animation = export::AnimationParams::new(fps, frames, duration);
|
||||
if file_type == export::FileType::Gif {
|
||||
export::export_gif(executor, wgpu_executor, output, settings, animation, runtime, spawner).await?;
|
||||
export::export_gif(executor, &renderer.output, wgpu_executor, output, settings, animation, runtime, spawner).await?;
|
||||
} else if animation.frames > 1 {
|
||||
if file_type == export::FileType::Ico {
|
||||
return Err("ICO can't be exported as an image sequence".into());
|
||||
}
|
||||
export::export_image_sequence(executor, wgpu_executor, output, settings, animation, runtime, spawner).await?;
|
||||
export::export_image_sequence(executor, &renderer.output, wgpu_executor, output, settings, animation, runtime, spawner).await?;
|
||||
} else {
|
||||
export::export_document(executor, wgpu_executor, output, settings, runtime, spawner).await?;
|
||||
export::export_document(executor, &renderer.output, wgpu_executor, output, settings, runtime, spawner).await?;
|
||||
}
|
||||
}
|
||||
Command::ListNodeIdentifiers | Command::ExtractLegacyDoc { .. } | Command::Host { .. } | Command::Join { .. } | Command::Watch { .. } => unreachable!("Handled before compiling"),
|
||||
|
||||
@@ -2,10 +2,10 @@ use document_live::{Event, LiveDocument};
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue, UVec2};
|
||||
use graphene_cli::{TokioSpawner, compile_graph, create_executor, editor_api, export};
|
||||
use graphene_cli::{TokioSpawner, compile_graph, editor_api, export};
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, RenderConfig};
|
||||
use graphene_std::runtime::AsyncRuntime;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -56,7 +56,7 @@ struct Viewer {
|
||||
window: Option<Arc<dyn Window>>,
|
||||
surface: Option<(WgpuSurface, wgpu::SurfaceConfiguration)>,
|
||||
blitter: Option<TextureBlitter>,
|
||||
executor: Option<DynamicExecutor>,
|
||||
executor: Option<(DynamicExecutor, OutputHandle)>,
|
||||
dirty: bool,
|
||||
waiting: Vec<ResourceHash>,
|
||||
}
|
||||
@@ -132,13 +132,17 @@ impl Viewer {
|
||||
Ok(proto) => proto,
|
||||
Err(error) => return log::error!("Compile failed: {error}"),
|
||||
};
|
||||
match create_executor(proto) {
|
||||
Ok(executor) => {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
match executor.update(proto) {
|
||||
Ok((output, _)) => {
|
||||
self.graph_runtime.update_sources(executor.sources());
|
||||
log::info!("Document compiled");
|
||||
self.executor = Some(executor);
|
||||
self.executor = Some((executor, output));
|
||||
}
|
||||
Err((_, errors)) => {
|
||||
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
||||
log::error!("Executor creation failed: {}", messages.join("\n"));
|
||||
}
|
||||
Err(error) => log::error!("Executor creation failed: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,14 +153,15 @@ impl Viewer {
|
||||
|
||||
// Present even without a frame, since Wayland never shows a surface with no committed buffer
|
||||
let frame = match &self.executor {
|
||||
Some(executor) => {
|
||||
Some((executor, output)) => {
|
||||
let mut render_config = RenderConfig {
|
||||
export_format: ExportFormat::Raster,
|
||||
scale: 1.,
|
||||
..Default::default()
|
||||
};
|
||||
render_config.viewport.resolution = UVec2::new(config.width, config.height);
|
||||
match self.runtime.block_on(export::execute_until_settled(executor, &self.graph_runtime, &self.spawner, render_config))? {
|
||||
let settled = export::execute_until_settled(executor, output, &self.graph_runtime, &self.spawner, render_config);
|
||||
match self.runtime.block_on(settled)? {
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Texture(texture),
|
||||
..
|
||||
|
||||
@@ -4,11 +4,11 @@ use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::{DEMO_ART, compile};
|
||||
use graphene_std::application_io::EditorApi;
|
||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::path::Path;
|
||||
|
||||
pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork) {
|
||||
let network = futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite"))))
|
||||
.unwrap()
|
||||
.network;
|
||||
@@ -17,8 +17,9 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
|
||||
(executor, proto_network)
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(proto_network.clone()).unwrap();
|
||||
(executor, output, proto_network)
|
||||
}
|
||||
|
||||
#[allow(dead_code, reason = "shared by the bench targets, only some of which call it, and each compiles this module separately")]
|
||||
|
||||
@@ -20,7 +20,7 @@ use graphene_std::uuid::NodeId;
|
||||
use graphene_std::{Color, Context};
|
||||
use gungraun::prelude::*;
|
||||
use gungraun::{Callgrind, EntryPoint};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::hint::black_box;
|
||||
use std::sync::Arc;
|
||||
@@ -43,6 +43,7 @@ pub struct Session {
|
||||
runtime: AsyncRuntime,
|
||||
preprocessor: preprocessor::Preprocessor,
|
||||
executor: DynamicExecutor,
|
||||
output: OutputHandle,
|
||||
/// The document graph for the measured update.
|
||||
document: NodeNetwork,
|
||||
}
|
||||
@@ -60,6 +61,7 @@ impl Session {
|
||||
runtime: AsyncRuntime::new(Arc::new(BlockingSpawner)),
|
||||
preprocessor: preprocessor::Preprocessor::new(),
|
||||
executor: DynamicExecutor::default(),
|
||||
output: OutputHandle::default(),
|
||||
document: NodeNetwork::default(),
|
||||
};
|
||||
session.update(brush_layer(&BrushCache::default(), after));
|
||||
@@ -71,7 +73,7 @@ impl Session {
|
||||
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
|
||||
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
|
||||
self.executor.update(proto_network).expect("Failed to update the executor");
|
||||
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
|
||||
|
||||
let render_config = RenderConfig {
|
||||
viewport: Footprint {
|
||||
@@ -82,7 +84,7 @@ impl Session {
|
||||
scale: 1.,
|
||||
..Default::default()
|
||||
};
|
||||
let output = self.executor.tree().eval_tagged_value(self.executor.output(), &render_config.into_context());
|
||||
let output = self.executor.tree().eval_tagged_value(self.output.node(), &render_config.into_context());
|
||||
assert!(matches!(output, Ok(graphene_std::Poll::Final(_))), "Failed to render the document: {output:?}");
|
||||
// Waiting for the device puts its rasterization inside the measurement, rather than only the encoding of its commands
|
||||
let _ = self.gpu.context().device.poll(wgpu::PollType::wait_indefinitely());
|
||||
|
||||
@@ -8,9 +8,9 @@ fn subsequent_evaluations(c: &mut Criterion) {
|
||||
let mut group = c.benchmark_group("Subsequent Evaluations");
|
||||
let context = RenderConfig::default().into_context();
|
||||
bench_for_each_demo(&mut group, |name, g| {
|
||||
let (executor, _) = setup_network(name);
|
||||
let (executor, output, _) = setup_network(name);
|
||||
let context = context.clone();
|
||||
g.bench_function(name, |b| b.iter(|| executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(&context)).unwrap()));
|
||||
g.bench_function(name, |b| b.iter(|| executor.tree().eval_tagged_value(output.node(), std::hint::black_box(&context)).unwrap()));
|
||||
});
|
||||
group.finish();
|
||||
}
|
||||
|
||||
@@ -3,27 +3,28 @@ mod benchmark_util;
|
||||
use benchmark_util::setup_network;
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
use gungraun::prelude::*;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use std::hint::black_box;
|
||||
|
||||
fn setup_run_cached(name: &str) -> DynamicExecutor {
|
||||
let (executor, _) = setup_network(name);
|
||||
fn setup_run_cached(name: &str) -> (DynamicExecutor, OutputHandle) {
|
||||
let (executor, output, _) = setup_network(name);
|
||||
|
||||
// Warm up the cache by running once
|
||||
let context = RenderConfig::default().into_context();
|
||||
let _ = executor.tree().eval_tagged_value(executor.output(), &context);
|
||||
let _ = executor.tree().eval_tagged_value(output.node(), &context);
|
||||
|
||||
executor
|
||||
(executor, output)
|
||||
}
|
||||
|
||||
#[library_benchmark]
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
|
||||
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
|
||||
pub fn run_cached(setup: (DynamicExecutor, OutputHandle)) -> (DynamicExecutor, OutputHandle) {
|
||||
let (executor, output) = setup;
|
||||
let context = RenderConfig::default().into_context();
|
||||
black_box(executor.tree().eval_tagged_value(executor.output(), black_box(&context)).unwrap());
|
||||
black_box(executor.tree().eval_tagged_value(output.node(), black_box(&context)).unwrap());
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
(executor, output)
|
||||
}
|
||||
|
||||
library_benchmark_group!(name = run_cached_group; benchmarks = run_cached);
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
use criterion::measurement::Measurement;
|
||||
use criterion::{BenchmarkGroup, Criterion, criterion_group, criterion_main};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::{DEMO_ART, compile};
|
||||
use graphene_std::transform::Footprint;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -12,9 +10,8 @@ fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
.unwrap()
|
||||
.network;
|
||||
let proto_network = compile(network);
|
||||
let empty = ProtoNetwork::default();
|
||||
|
||||
let executor = DynamicExecutor::new(empty).unwrap();
|
||||
let executor = DynamicExecutor::default();
|
||||
|
||||
c.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
@@ -38,10 +35,11 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
.network;
|
||||
let proto_network = compile(network);
|
||||
|
||||
let executor = DynamicExecutor::new(proto_network).unwrap();
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(proto_network).unwrap();
|
||||
let footprint = Footprint::default();
|
||||
|
||||
c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
|
||||
c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint)));
|
||||
}
|
||||
fn run_once_demo(c: &mut Criterion) {
|
||||
let mut g = c.benchmark_group("Run Once no render");
|
||||
|
||||
@@ -12,7 +12,7 @@ fn run_once(c: &mut Criterion) {
|
||||
g.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
|| setup_network(name),
|
||||
|(executor, _)| executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(&context)).unwrap(),
|
||||
|(executor, output, _)| executor.tree().eval_tagged_value(output.node(), std::hint::black_box(&context)).unwrap(),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -3,22 +3,23 @@ mod benchmark_util;
|
||||
use benchmark_util::setup_network;
|
||||
use graphene_std::application_io;
|
||||
use gungraun::prelude::*;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use std::hint::black_box;
|
||||
|
||||
fn setup_run_once(name: &str) -> DynamicExecutor {
|
||||
let (executor, _) = setup_network(name);
|
||||
executor
|
||||
fn setup_run_once(name: &str) -> (DynamicExecutor, OutputHandle) {
|
||||
let (executor, output, _) = setup_network(name);
|
||||
(executor, output)
|
||||
}
|
||||
|
||||
#[library_benchmark]
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
|
||||
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
|
||||
pub fn run_once(setup: (DynamicExecutor, OutputHandle)) -> (DynamicExecutor, OutputHandle) {
|
||||
let (executor, output) = setup;
|
||||
let context = application_io::RenderConfig::default().into_context();
|
||||
black_box(executor.tree().eval_tagged_value(executor.output(), black_box(&context)).unwrap());
|
||||
black_box(executor.tree().eval_tagged_value(output.node(), black_box(&context)).unwrap());
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
(executor, output)
|
||||
}
|
||||
|
||||
library_benchmark_group!(name = run_once_group; benchmarks = run_once);
|
||||
|
||||
@@ -2,7 +2,6 @@ mod benchmark_util;
|
||||
|
||||
use benchmark_util::{bench_for_each_demo, setup_network};
|
||||
use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
|
||||
fn update_executor(c: &mut Criterion) {
|
||||
@@ -11,10 +10,8 @@ fn update_executor(c: &mut Criterion) {
|
||||
g.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
|| {
|
||||
let (_, proto_network) = setup_network(name);
|
||||
let empty = ProtoNetwork::default();
|
||||
let executor = DynamicExecutor::new(empty).unwrap();
|
||||
(executor, proto_network)
|
||||
let (_, _, proto_network) = setup_network(name);
|
||||
(DynamicExecutor::default(), proto_network)
|
||||
},
|
||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
||||
criterion::BatchSize::SmallInput,
|
||||
|
||||
@@ -7,10 +7,8 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use std::hint::black_box;
|
||||
|
||||
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let (_, proto_network) = setup_network(name);
|
||||
let empty = ProtoNetwork::default();
|
||||
let executor = DynamicExecutor::new(empty).unwrap();
|
||||
(executor, proto_network)
|
||||
let (_, _, proto_network) = setup_network(name);
|
||||
(DynamicExecutor::default(), proto_network)
|
||||
}
|
||||
|
||||
#[library_benchmark]
|
||||
|
||||
@@ -3,32 +3,41 @@ use core_types::{NodeError, Poll, SourceId, WasmNotSend};
|
||||
use graph_craft::Type;
|
||||
use graph_craft::document::value::{TaggedValue, UpcastNode};
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::Executor;
|
||||
use graph_craft::proto::{Any, AnyInput, ConstructionArgs, GraphError, NodeContainer, ProtoNetwork, ProtoNode, SharedNode, SharedNodeContainer, TypeErasedBox, TypeErasedNode, TypingContext};
|
||||
use graph_craft::proto::{GraphErrorType, GraphErrors};
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
|
||||
#[derive(Clone)]
|
||||
pub struct DynamicExecutor {
|
||||
output: NodeId,
|
||||
/// Stores all of the dynamic node structs.
|
||||
tree: BorrowTree,
|
||||
/// Stores the types of the proto nodes.
|
||||
typing_context: TypingContext,
|
||||
/// The outputs of the networks, kept alive by the executor as long as there are handles to them.
|
||||
outputs: Vec<Weak<NodeId>>,
|
||||
// Kept for one more update, so a node that comes back is reused
|
||||
orphaned_nodes: HashSet<NodeId>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct OutputHandle(Arc<NodeId>);
|
||||
|
||||
impl OutputHandle {
|
||||
pub fn node(&self) -> NodeId {
|
||||
*self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DynamicExecutor {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
output: Default::default(),
|
||||
tree: Default::default(),
|
||||
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
||||
outputs: Vec::new(),
|
||||
orphaned_nodes: HashSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -49,28 +58,24 @@ pub struct ResolvedDocumentNodeTypesDelta {
|
||||
}
|
||||
|
||||
impl DynamicExecutor {
|
||||
pub fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&proto_network)?;
|
||||
let output = proto_network.output;
|
||||
let tree = BorrowTree::new(proto_network, &typing_context)?;
|
||||
|
||||
Ok(Self {
|
||||
tree,
|
||||
output,
|
||||
typing_context,
|
||||
orphaned_nodes: HashSet::new(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn sources(&self) -> impl Iterator<Item = &SourceId> {
|
||||
self.tree.sources.iter().map(|(_, source)| source)
|
||||
}
|
||||
|
||||
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
|
||||
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
|
||||
#[cfg_attr(debug_assertions, inline(never))]
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
self.output = proto_network.output;
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
let (output, add) = self.insert_nodes(proto_network)?;
|
||||
let remove = self.free_orphaned_nodes();
|
||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
|
||||
}
|
||||
|
||||
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
let (output, add) = self.insert_nodes(proto_network)?;
|
||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }))
|
||||
}
|
||||
|
||||
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
self.typing_context.update(&proto_network).map_err(|e| {
|
||||
// If there is an error then get types that have been resolved before the error
|
||||
let add = proto_network
|
||||
@@ -92,7 +97,31 @@ impl DynamicExecutor {
|
||||
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
|
||||
})?;
|
||||
|
||||
let (add, orphaned) = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||
let output = proto_network.output;
|
||||
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||
self.outputs.retain(|output| output.strong_count() > 0);
|
||||
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
|
||||
let output = held.unwrap_or_else(|| {
|
||||
let output = Arc::new(output);
|
||||
self.outputs.push(Arc::downgrade(&output));
|
||||
output
|
||||
});
|
||||
|
||||
let add = self.document_node_types(add.into_iter()).collect();
|
||||
Ok((OutputHandle(output), add))
|
||||
}
|
||||
|
||||
fn free_orphaned_nodes(&mut self) -> Vec<Path> {
|
||||
let mut kept = HashSet::new();
|
||||
let mut pending: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
|
||||
while let Some(node) = pending.pop() {
|
||||
if kept.insert(node)
|
||||
&& let Some((_, _, inputs)) = self.tree.nodes.get(&node)
|
||||
{
|
||||
pending.extend(inputs.iter());
|
||||
}
|
||||
}
|
||||
let orphaned = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
|
||||
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
|
||||
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
|
||||
for node_id in old_to_remove {
|
||||
@@ -104,31 +133,23 @@ impl DynamicExecutor {
|
||||
}
|
||||
}
|
||||
}
|
||||
let add = self.document_node_types(add.into_iter()).collect();
|
||||
Ok(ResolvedDocumentNodeTypesDelta { add, remove })
|
||||
remove
|
||||
}
|
||||
|
||||
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
let orphaned_nodes = std::mem::take(&mut self.orphaned_nodes);
|
||||
let result = self.update(proto_network);
|
||||
self.orphaned_nodes = orphaned_nodes;
|
||||
result
|
||||
pub fn execute<I: 'static + WasmNotSend>(&self, output: &OutputHandle, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> {
|
||||
self.tree.eval_tagged_value(output.node(), &input).map_err(|error| error.into())
|
||||
}
|
||||
|
||||
pub fn input_type(&self) -> Option<Type> {
|
||||
self.typing_context.type_of(self.output).map(|node_io| node_io.call_argument.clone())
|
||||
pub fn input_type(&self, output: &OutputHandle) -> Option<Type> {
|
||||
self.typing_context.type_of(output.node()).map(|node_io| node_io.call_argument.clone())
|
||||
}
|
||||
|
||||
pub fn tree(&self) -> &BorrowTree {
|
||||
&self.tree
|
||||
}
|
||||
|
||||
pub fn output(&self) -> NodeId {
|
||||
self.output
|
||||
}
|
||||
|
||||
pub fn output_type(&self) -> Option<Type> {
|
||||
self.typing_context.type_of(self.output).map(|node_io| node_io.return_value.clone())
|
||||
pub fn output_type(&self, output: &OutputHandle) -> Option<Type> {
|
||||
self.typing_context.type_of(output.node()).map(|node_io| node_io.return_value.clone())
|
||||
}
|
||||
|
||||
pub fn document_node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
|
||||
@@ -160,15 +181,6 @@ impl DynamicExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
impl<I> Executor<I, Poll<TaggedValue>> for &DynamicExecutor
|
||||
where
|
||||
I: 'static + WasmNotSend,
|
||||
{
|
||||
fn execute(&self, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> {
|
||||
self.tree.eval_tagged_value(self.output, &input).map_err(|error| error.into())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InputMapping {}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -285,9 +297,8 @@ impl BorrowTree {
|
||||
Ok(nodes)
|
||||
}
|
||||
|
||||
/// Pushes new nodes into the tree and return orphaned nodes
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
|
||||
let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect();
|
||||
/// Pushes new nodes into the tree
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<Vec<Path>, GraphErrors> {
|
||||
let mut new_nodes: Vec<_> = Vec::new();
|
||||
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
|
||||
for (id, node) in proto_network.nodes {
|
||||
@@ -297,9 +308,8 @@ impl BorrowTree {
|
||||
} else if self.update_source_map(id, typing_context, &node) {
|
||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||
}
|
||||
old_nodes.remove(&id);
|
||||
}
|
||||
Ok((new_nodes, old_nodes))
|
||||
Ok(new_nodes)
|
||||
}
|
||||
|
||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SharedNodeContainer> {
|
||||
|
||||
@@ -875,11 +875,12 @@ fn error_traced_through(indices: &[usize]) -> NodeError {
|
||||
|
||||
#[test]
|
||||
fn a_trace_leads_to_the_node_that_raised_the_error() {
|
||||
let executor = DynamicExecutor::new(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||
|
||||
assert!(executor.trace_error(executor.output(), &error_traced_through(&[])).is_empty());
|
||||
assert_eq!(*executor.trace_error(executor.output(), &error_traced_through(&[0])), [NodeId(0)]);
|
||||
assert_eq!(*executor.trace_error(executor.output(), &error_traced_through(&[0, 0])), [NodeId(0)], "a value node has no inputs");
|
||||
assert!(executor.trace_error(output.node(), &error_traced_through(&[])).is_empty());
|
||||
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0])), [NodeId(0)]);
|
||||
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)], "a value node has no inputs");
|
||||
assert!(executor.trace_error(NodeId(0), &error_traced_through(&[])).is_empty());
|
||||
assert!(
|
||||
executor.trace_error(NodeId(0), &error_traced_through(&[0])).is_empty(),
|
||||
@@ -892,14 +893,15 @@ fn a_trace_steps_over_the_index_of_a_promotion_adapter() {
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(f64)).into()), vec![NodeId(0)]);
|
||||
let mut box_corners_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
box_corners_node.identifier = graphene_std::vector::generator_nodes::box_corners::IDENTIFIER;
|
||||
let executor = DynamicExecutor::new(ProtoNetwork {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(network).unwrap();
|
||||
|
||||
assert_eq!(*executor.trace_error(executor.output(), &error_traced_through(&[0, 0])), [NodeId(0)]);
|
||||
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -912,21 +914,19 @@ fn executor_panics_reach_the_host_with_the_original_payload() {
|
||||
}
|
||||
}
|
||||
|
||||
let mut executor = DynamicExecutor {
|
||||
output: NodeId(0),
|
||||
..Default::default()
|
||||
};
|
||||
let missing_output = (&executor).execute(()).unwrap_err();
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = OutputHandle::default();
|
||||
let missing_output = executor.execute(&output, ()).unwrap_err();
|
||||
assert_eq!(missing_output.to_string(), "Output node not found in executor");
|
||||
|
||||
executor.tree.store_node(ObservedNode::new(Box::new(Panics)), NodeId(0), Box::default(), Box::default());
|
||||
let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (&executor).execute(()))).unwrap_err();
|
||||
let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| executor.execute(&output, ()))).unwrap_err();
|
||||
assert_eq!(*payload.downcast::<u32>().unwrap(), 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chained_fallbacks_both_reach_the_root() {
|
||||
let executor = DynamicExecutor::new(ProtoNetwork {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(4),
|
||||
nodes: [
|
||||
@@ -934,15 +934,16 @@ fn chained_fallbacks_both_reach_the_root() {
|
||||
vec![(NodeId(3), throw_error_node([0, 1, 2, 1], 3)), (NodeId(4), throw_error_node([3, 1, 2, 1], 4))],
|
||||
]
|
||||
.concat(),
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(network).unwrap();
|
||||
|
||||
let context: Context = None;
|
||||
let Ok(Poll::Fallback(boxed)) = (&executor).execute(context) else {
|
||||
let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else {
|
||||
panic!("Both nodes fall back, so the root should too")
|
||||
};
|
||||
let error = &boxed.1;
|
||||
assert!(executor.trace_error(executor.output(), error).is_empty());
|
||||
assert!(executor.trace_error(output.node(), error).is_empty());
|
||||
let [upstream] = error.upstream() else {
|
||||
panic!("The second node's error should carry the first node's error")
|
||||
};
|
||||
@@ -951,7 +952,7 @@ fn chained_fallbacks_both_reach_the_root() {
|
||||
|
||||
#[test]
|
||||
fn an_error_after_a_fallback_keeps_both() {
|
||||
let executor = DynamicExecutor::new(ProtoNetwork {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(5),
|
||||
nodes: [
|
||||
@@ -963,14 +964,15 @@ fn an_error_after_a_fallback_keeps_both() {
|
||||
],
|
||||
]
|
||||
.concat(),
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(network).unwrap();
|
||||
|
||||
let context: Context = None;
|
||||
let Ok(Poll::Error(error)) = (&executor).execute(context) else {
|
||||
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
|
||||
panic!("The failing node should stop the frame")
|
||||
};
|
||||
assert!(executor.trace_error(executor.output(), &error).is_empty());
|
||||
assert!(executor.trace_error(output.node(), &error).is_empty());
|
||||
let [upstream] = error.upstream() else {
|
||||
panic!("The failing node's error should carry the fallback before it")
|
||||
};
|
||||
@@ -979,7 +981,7 @@ fn an_error_after_a_fallback_keeps_both() {
|
||||
|
||||
#[test]
|
||||
fn a_node_error_names_the_node_that_raised_it() {
|
||||
let executor = DynamicExecutor::new(ProtoNetwork {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(5),
|
||||
nodes: [
|
||||
@@ -991,14 +993,15 @@ fn a_node_error_names_the_node_that_raised_it() {
|
||||
],
|
||||
]
|
||||
.concat(),
|
||||
})
|
||||
.expect("The Throw Error nodes should resolve");
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(network).expect("The Throw Error nodes should resolve");
|
||||
|
||||
let context: Context = None;
|
||||
let Ok(Poll::Error(error)) = (&executor).execute(context) else {
|
||||
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
|
||||
panic!("The failing node should stop the frame")
|
||||
};
|
||||
let origin = executor.trace_error(executor.output(), &error).last().copied();
|
||||
let origin = executor.trace_error(output.node(), &error).last().copied();
|
||||
assert_eq!(origin, Some(NodeId(4)), "The error should name the failing node, not the root that forwarded it");
|
||||
let paths: Vec<_> = executor
|
||||
.tree()
|
||||
@@ -1028,11 +1031,11 @@ fn throw_error_node(inputs: [u64; 4], id: u64) -> ProtoNode {
|
||||
node
|
||||
}
|
||||
|
||||
fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], keep_value: bool) -> DynamicExecutor {
|
||||
fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], keep_value: bool) -> (DynamicExecutor, OutputHandle) {
|
||||
let mut handler_node = ProtoNode::value(ConstructionArgs::Nodes(handler_inputs.iter().copied().map(NodeId).collect()), vec![NodeId(6)]);
|
||||
handler_node.identifier = handler;
|
||||
|
||||
DynamicExecutor::new(ProtoNetwork {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(6),
|
||||
nodes: [
|
||||
@@ -1045,40 +1048,42 @@ fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], k
|
||||
],
|
||||
]
|
||||
.concat(),
|
||||
})
|
||||
.expect("The error handling nodes should resolve")
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(network).expect("The error handling nodes should resolve");
|
||||
(executor, output)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_caught_error_does_not_reach_the_output() {
|
||||
let context: Context = None;
|
||||
for keep_value in [false, true] {
|
||||
let executor = handled_error_network(graphene_core::poll::catch::IDENTIFIER, &[4, 5], keep_value);
|
||||
assert!(matches!((&executor).execute(context.clone()), Ok(Poll::Final(_))), "Catch should hide the error");
|
||||
let (executor, output) = handled_error_network(graphene_core::poll::catch::IDENTIFIER, &[4, 5], keep_value);
|
||||
assert!(matches!(executor.execute(&output, context.clone()), Ok(Poll::Final(_))), "Catch should hide the error");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suppress_error_hides_only_an_error_with_a_value() {
|
||||
let context: Context = None;
|
||||
let executor = handled_error_network(graphene_core::poll::suppress_error::IDENTIFIER, &[4], true);
|
||||
let (executor, output) = handled_error_network(graphene_core::poll::suppress_error::IDENTIFIER, &[4], true);
|
||||
assert!(
|
||||
matches!((&executor).execute(context.clone()), Ok(Poll::Final(_))),
|
||||
matches!(executor.execute(&output, context.clone()), Ok(Poll::Final(_))),
|
||||
"Suppress Error should keep the value and hide the error"
|
||||
);
|
||||
let executor = handled_error_network(graphene_core::poll::suppress_error::IDENTIFIER, &[4], false);
|
||||
assert!(matches!((&executor).execute(context), Ok(Poll::Error(_))), "An error without a value should still stop the frame");
|
||||
let (executor, output) = handled_error_network(graphene_core::poll::suppress_error::IDENTIFIER, &[4], false);
|
||||
assert!(matches!(executor.execute(&output, context), Ok(Poll::Error(_))), "An error without a value should still stop the frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fallback_keeps_the_error_on_the_node_that_raised_it() {
|
||||
let executor = handled_error_network(graphene_core::poll::fallback::IDENTIFIER, &[4, 5], false);
|
||||
let (executor, output) = handled_error_network(graphene_core::poll::fallback::IDENTIFIER, &[4, 5], false);
|
||||
let context: Context = None;
|
||||
let Ok(Poll::Fallback(boxed)) = (&executor).execute(context) else {
|
||||
let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else {
|
||||
panic!("Fallback should keep the frame going with the error")
|
||||
};
|
||||
assert_eq!(boxed.1.to_string(), "too small");
|
||||
assert_eq!(*executor.trace_error(executor.output(), &boxed.1), [NodeId(4)], "The error should stay on the Throw Error node");
|
||||
assert_eq!(*executor.trace_error(output.node(), &boxed.1), [NodeId(4)], "The error should stay on the Throw Error node");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1187,16 +1192,63 @@ fn source_network(node: u64) -> ProtoNetwork {
|
||||
|
||||
#[test]
|
||||
fn update_without_freeing_keeps_the_nodes_the_network_leaves_out() {
|
||||
let mut executor = DynamicExecutor::new(source_network(0)).unwrap();
|
||||
let mut executor = DynamicExecutor::default();
|
||||
executor.update(source_network(0)).unwrap();
|
||||
|
||||
executor.update_without_freeing(source_network(1)).unwrap();
|
||||
executor.update_without_freeing(source_network(1)).unwrap();
|
||||
assert!(executor.tree().get(NodeId(0)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn networks_are_executed_side_by_side_by_their_handles() {
|
||||
let network = |node: u64| ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(node),
|
||||
nodes: vec![value_node(node, TaggedValue::Number(node as f64))],
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (first, _) = executor.update(network(0)).unwrap();
|
||||
let (second, _) = executor.update(network(1)).unwrap();
|
||||
|
||||
let context: Context = None;
|
||||
assert_eq!(executor.execute(&first, context.clone()).unwrap(), Poll::Final(TaggedValue::Number(0.)));
|
||||
assert_eq!(executor.execute(&second, context).unwrap(), Poll::Final(TaggedValue::Number(1.)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_output_that_is_already_held_shares_its_handle() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (first, _) = executor.update(source_network(0)).unwrap();
|
||||
let (second, _) = executor.update(source_network(0)).unwrap();
|
||||
let (other, _) = executor.update(source_network(1)).unwrap();
|
||||
|
||||
assert!(Arc::ptr_eq(&first.0, &second.0));
|
||||
assert!(!Arc::ptr_eq(&first.0, &other.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||
let kept = |executor: &DynamicExecutor| [0, 1].map(|node| executor.tree().get(NodeId(node)).is_some());
|
||||
|
||||
for _ in 0..3 {
|
||||
executor.update(source_network(2)).unwrap();
|
||||
}
|
||||
assert_eq!(kept(&executor), [true; 2]);
|
||||
|
||||
drop(output);
|
||||
executor.update(source_network(2)).unwrap();
|
||||
assert_eq!(kept(&executor), [true; 2], "orphaned for one more update");
|
||||
executor.update(source_network(2)).unwrap();
|
||||
assert_eq!(kept(&executor), [false; 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_is_listed_for_as_long_as_its_node_lives() {
|
||||
let mut executor = DynamicExecutor::new(source_network(0)).unwrap();
|
||||
let mut executor = DynamicExecutor::default();
|
||||
executor.update(source_network(0)).unwrap();
|
||||
|
||||
for _ in 0..3 {
|
||||
executor.update(source_network(1)).unwrap();
|
||||
|
||||
@@ -49,6 +49,6 @@ mod tests {
|
||||
let compiler = Compiler {};
|
||||
let protograph = compiler.compile_single(network).expect("Graph should be generated").network;
|
||||
|
||||
let _exec = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
let _exec = DynamicExecutor::default().update(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::RenderOutput;
|
||||
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphene_std::GlowTechnique;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::Stroke;
|
||||
@@ -29,6 +28,7 @@ use graphene_std::vector::misc::{
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -290,6 +290,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
GlowTechnique,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
@@ -300,6 +305,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
MandelbrotFractal,
|
||||
MandelbrotExterior,
|
||||
MandelbrotInterior,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
GridTopology,
|
||||
|
||||
@@ -261,12 +261,15 @@ mod tests {
|
||||
assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}");
|
||||
}
|
||||
|
||||
// Color Dodge gives white for a white source, and Divide for a black backdrop
|
||||
// Color Dodge gives white for a white source, and Divide keeps a black backdrop black and turns any other white under a black source
|
||||
for source in [1., 1. - 1e-7, 1. + 2e-7] {
|
||||
assert_eq!(Color::blend_color_dodge(0., source), 1., "a source of {source}");
|
||||
}
|
||||
for backdrop in [0., 1e-7, -1e-7] {
|
||||
assert_eq!(Color::blend_divide(backdrop, 0.5), 1., "a backdrop of {backdrop}");
|
||||
assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}");
|
||||
}
|
||||
for source in [0., 1e-7, -1e-7] {
|
||||
assert_eq!(Color::blend_divide(0.5, source), 1., "a source of {source}");
|
||||
}
|
||||
|
||||
// Past the tolerance the modes follow their formulas
|
||||
|
||||
@@ -744,9 +744,15 @@ impl Color {
|
||||
c_b - c_s
|
||||
}
|
||||
|
||||
/// Per-channel "Divide" blend.
|
||||
/// Per-channel "Divide" blend, where a black backdrop stays black and any other turns white when divided by black.
|
||||
pub fn blend_divide(c_b: f32, c_s: f32) -> f32 {
|
||||
if c_b.abs() <= BLEND_EDGE_TOLERANCE { 1. } else { c_b / c_s }
|
||||
if c_b <= BLEND_EDGE_TOLERANCE {
|
||||
0.
|
||||
} else if c_s <= BLEND_EDGE_TOLERANCE {
|
||||
1.
|
||||
} else {
|
||||
c_b / c_s
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `blend` on this color's and `c_s`'s gamma-encoded channels, which the component blend modes are defined on, keeping `c_s`'s alpha.
|
||||
|
||||
@@ -32,10 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_FOOTPRINT_AREAS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS,
|
||||
ATTR_EDITOR_TEXT_FRAME, ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE,
|
||||
ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START,
|
||||
ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD,
|
||||
ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
|
||||
ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use num_traits;
|
||||
|
||||
@@ -40,9 +40,6 @@ pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
|
||||
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
|
||||
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
|
||||
/// `List<NodeIdPath>` of the nodes with a footprint input this item passed through.
|
||||
/// Each row's transform maps the unit square onto that node's area in this item's local space.
|
||||
pub const ATTR_EDITOR_FOOTPRINT_AREAS: &str = "editor:footprint_areas";
|
||||
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
|
||||
pub const ATTR_START: &str = "start";
|
||||
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
|
||||
|
||||
@@ -60,6 +60,12 @@ pub struct FieldMetadata {
|
||||
pub progression: bool,
|
||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||
pub constant: bool,
|
||||
/// The X and Y labels of a Vec2 parameter's widget, from `#[labels("W", "H")]`.
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
/// Whether a number or Vec2 parameter's widget only takes integers, from `#[integer]`. Integer types always do.
|
||||
pub integer: bool,
|
||||
/// Whether the widget leaves room for the assist area beside it, which `#[blank_assist(false)]` turns off.
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -222,6 +228,167 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne
|
||||
|
||||
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// Every node defined as a subgraph by the `#[graph]` macro, in registration order.
|
||||
pub static GRAPH_METADATA: LazyLock<Mutex<Vec<GraphMetadata>>> = LazyLock::new(|| Mutex::new(Vec::new()));
|
||||
|
||||
/// A node defined as a subgraph by `#[graph]`, which the editor turns into a catalog definition alongside the proto nodes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphMetadata {
|
||||
/// The definition's identifier and display name.
|
||||
pub identifier: &'static str,
|
||||
pub category: &'static str,
|
||||
pub icon: Option<&'static str>,
|
||||
pub description: &'static str,
|
||||
/// The declaration version from `#[graph(version(N))]`, starting at 1.
|
||||
pub version: u32,
|
||||
/// Whether a new instance starts as a layer, from `#[graph(layer)]`.
|
||||
pub layer: bool,
|
||||
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
|
||||
/// Each one's `default_type` is the type it was declared with.
|
||||
pub imports: Vec<FieldMetadata>,
|
||||
pub exports: Vec<GraphExportMetadata>,
|
||||
/// The nodes inside the subgraph, where each node's position in this list is its ID.
|
||||
pub nodes: Vec<GraphNodeMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphExportMetadata {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub source: GraphInputSource,
|
||||
}
|
||||
|
||||
/// A node inside a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphNodeMetadata {
|
||||
pub implementation: GraphNodeImplementation,
|
||||
/// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition.
|
||||
pub inputs: Vec<(usize, GraphInputSource)>,
|
||||
/// The absolute position in grid units, from `.at(x, y)`.
|
||||
pub position: Option<(i32, i32)>,
|
||||
/// From `.layer()`.
|
||||
pub layer: bool,
|
||||
/// From `.named("…")`.
|
||||
pub display_name: Option<&'static str>,
|
||||
/// From `.hidden()`.
|
||||
pub hidden: bool,
|
||||
/// From `.locked()`.
|
||||
pub locked: bool,
|
||||
/// From `.pinned()`.
|
||||
pub pinned: bool,
|
||||
/// From `.call_argument::<T>()`.
|
||||
pub call_argument: Option<Type>,
|
||||
}
|
||||
|
||||
/// What a node inside a subgraph is an instance of.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GraphNodeImplementation {
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
/// Another node defined by `#[graph]`, named by its identifier.
|
||||
Graph(&'static str),
|
||||
}
|
||||
|
||||
impl From<ProtoNodeIdentifier> for GraphNodeImplementation {
|
||||
fn from(identifier: ProtoNodeIdentifier) -> Self {
|
||||
Self::ProtoNode(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for GraphNodeImplementation {
|
||||
fn from(identifier: &'static str) -> Self {
|
||||
Self::Graph(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// What feeds an input, or an export, of a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum GraphInputSource {
|
||||
/// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`].
|
||||
Node { node: usize, output: usize },
|
||||
/// One of the subgraph's imports, with the type its wire records.
|
||||
Import { index: usize, ty: Type },
|
||||
/// A value. Without an exposure, the input keeps the one from the node's own definition.
|
||||
Value { value: GraphValue, exposed: Option<bool> },
|
||||
/// A scope input, from `scope("…")`.
|
||||
Scope(&'static str),
|
||||
/// The document path of the node, from `reflect(NodePath)`.
|
||||
NodePath,
|
||||
/// The source ID of the node, from `reflect(SourceId)`.
|
||||
SourceId,
|
||||
}
|
||||
|
||||
/// A value written in a subgraph definition. The editor converts it to the type of the input it feeds.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GraphValue {
|
||||
/// A number written without a fractional part, which feeds an integer input as an integer and any other as a number.
|
||||
Integer(i64),
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
Vec2(glam::DVec2),
|
||||
Color(Color),
|
||||
}
|
||||
|
||||
impl GraphValue {
|
||||
pub fn vec2(x: f64, y: f64) -> Self {
|
||||
Self::Vec2(glam::DVec2::new(x, y))
|
||||
}
|
||||
|
||||
/// An opaque color from `rgb(0xRRGGBB)`.
|
||||
pub fn rgb(hex: u32) -> Self {
|
||||
let [_, red, green, blue] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, 255).into())
|
||||
}
|
||||
|
||||
/// A color with alpha from `rgba(0xRRGGBBAA)`.
|
||||
pub fn rgba(hex: u32) -> Self {
|
||||
let [red, green, blue, alpha] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, alpha).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for GraphValue {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::String(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for GraphValue {
|
||||
fn from(value: String) -> Self {
|
||||
Self::String(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> for GraphValue {
|
||||
fn from(value: bool) -> Self {
|
||||
Self::Bool(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f64> for GraphValue {
|
||||
fn from(value: f64) -> Self {
|
||||
Self::Number(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<i64> for GraphValue {
|
||||
fn from(value: i64) -> Self {
|
||||
Self::Integer(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<glam::DVec2> for GraphValue {
|
||||
fn from(value: glam::DVec2) -> Self {
|
||||
Self::Vec2(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Color> for GraphValue {
|
||||
fn from(value: Color) -> Self {
|
||||
Self::Color(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier.
|
||||
/// Snapshotted on first access, which must happen after startup registration of the node metadata completes.
|
||||
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
|
||||
|
||||
@@ -113,36 +113,7 @@ impl RuntimeInner {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Slots<T>(Arc<Mutex<SlotTable<T>>>);
|
||||
|
||||
struct SlotTable<T> {
|
||||
slots: HashMap<u64, Slot<T>>,
|
||||
/// The number of started evaluations, which orders them.
|
||||
started: u64,
|
||||
/// The value of the latest started evaluation that has landed, with its order.
|
||||
latest: Option<(u64, T)>,
|
||||
}
|
||||
|
||||
impl<T: Clone> SlotTable<T> {
|
||||
fn start(&mut self) -> u64 {
|
||||
self.started += 1;
|
||||
self.started
|
||||
}
|
||||
|
||||
fn land(&mut self, key: u64, order: u64, state: Poll<T>) {
|
||||
let superseded = self.latest.as_ref().is_some_and(|(latest_order, _)| *latest_order > order);
|
||||
if !superseded && let Some(value) = state.clone().value() {
|
||||
self.latest = Some((order, value));
|
||||
}
|
||||
self.slots.insert(key, Slot::Ready(state));
|
||||
}
|
||||
|
||||
/// The value a pending evaluation returns, preferring the latest landed value if `keep_previous` is set.
|
||||
fn stand_in(&self, placeholder: Option<T>, keep_previous: bool) -> Poll<T> {
|
||||
let previous = if keep_previous { self.latest.as_ref().map(|(_, value)| value.clone()) } else { None };
|
||||
previous.or(placeholder).map_or(Poll::Pending, Poll::Partial)
|
||||
}
|
||||
}
|
||||
pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>);
|
||||
|
||||
enum Slot<T> {
|
||||
Ready(Poll<T>),
|
||||
@@ -159,11 +130,7 @@ impl<T> Drop for Slot<T> {
|
||||
|
||||
impl<T> Default for Slots<T> {
|
||||
fn default() -> Self {
|
||||
Self(Arc::new(Mutex::new(SlotTable {
|
||||
slots: HashMap::new(),
|
||||
started: 0,
|
||||
latest: None,
|
||||
})))
|
||||
Self(Arc::default())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,46 +147,42 @@ impl<T> std::fmt::Debug for Slots<T> {
|
||||
}
|
||||
|
||||
impl<T: Clone + WasmNotSend + 'static> Slots<T> {
|
||||
/// The landed state for `key`, or else starts its evaluation and returns its stand-in.
|
||||
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, keep_previous: bool, future: impl FnOnce() -> F) -> Poll<T>
|
||||
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, future: impl FnOnce() -> F) -> Poll<T>
|
||||
where
|
||||
F: Future<Output = Poll<T>> + WasmNotSend + 'static,
|
||||
{
|
||||
let order = {
|
||||
let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match table.slots.get(&key) {
|
||||
Some(Slot::Ready(landed)) => return landed.clone(),
|
||||
Some(Slot::Pending(_)) => return table.stand_in(placeholder, keep_previous),
|
||||
None => table.start(),
|
||||
}
|
||||
};
|
||||
match self.0.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
|
||||
Some(Slot::Ready(landed)) => return landed.clone(),
|
||||
Some(Slot::Pending(_)) => return placeholder.map_or(Poll::Pending, Poll::Partial),
|
||||
None => {}
|
||||
}
|
||||
|
||||
// Fast path for futures that are ready immediately
|
||||
// TODO(Timon): check if this would ever cause a problem; running a future on the graph executor thread might also be a bit wierd
|
||||
let mut future = Box::pin(future());
|
||||
if let std::task::Poll::Ready(state) = future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state.clone());
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state.clone()));
|
||||
return state;
|
||||
}
|
||||
|
||||
let (handle, registration) = AbortHandle::new_pair();
|
||||
let table = Arc::downgrade(&self.0);
|
||||
let slots = Arc::downgrade(&self.0);
|
||||
runtime.spawn(
|
||||
source,
|
||||
Box::pin(async move {
|
||||
if let Ok(state) = Abortable::new(future, registration).await
|
||||
&& let Some(table) = table.upgrade()
|
||||
&& let Some(slots) = slots.upgrade()
|
||||
{
|
||||
table.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state);
|
||||
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state));
|
||||
}
|
||||
}),
|
||||
);
|
||||
let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match table.slots.get(&key) {
|
||||
let mut slots = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match slots.get(&key) {
|
||||
Some(Slot::Ready(landed)) => landed.clone(),
|
||||
_ => {
|
||||
table.slots.insert(key, Slot::Pending(handle));
|
||||
table.stand_in(placeholder, keep_previous)
|
||||
slots.insert(key, Slot::Pending(handle));
|
||||
placeholder.map_or(Poll::Pending, Poll::Partial)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -252,13 +215,6 @@ mod tests {
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
fn drain_newest_first(&self) {
|
||||
let tasks = std::mem::take(&mut *self.0.lock().unwrap());
|
||||
for mut task in tasks.into_iter().rev() {
|
||||
while !poll_once(&mut task) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BlockingSpawner;
|
||||
@@ -320,7 +276,7 @@ mod tests {
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
|
||||
let slots = Slots::default();
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
assert_eq!(spawner.drain(), 0);
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
|
||||
|
||||
@@ -341,77 +297,11 @@ mod tests {
|
||||
Poll::Final(42u32)
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Partial(0));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Partial(0));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
|
||||
assert_eq!(spawner.drain(), 1, "an in-flight slot is not spawned twice");
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slot_keeping_the_previous_value_serves_it_until_the_next_response_lands() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
let fetch = |value: u32| {
|
||||
move || async move {
|
||||
YieldOnce(false).await;
|
||||
Poll::Final(value)
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)),
|
||||
Poll::Partial(0),
|
||||
"nothing landed yet, so the placeholder stands in"
|
||||
);
|
||||
spawner.drain();
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)), Poll::Final(1));
|
||||
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Partial(1), "the previous value stands in");
|
||||
spawner.drain();
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Final(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_response_landing_late_does_not_replace_the_previous_value() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
let fetch = |value: u32| {
|
||||
move || async move {
|
||||
YieldOnce(false).await;
|
||||
Poll::Final(value)
|
||||
}
|
||||
};
|
||||
|
||||
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1));
|
||||
slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2));
|
||||
spawner.drain_newest_first();
|
||||
|
||||
assert_eq!(slots.resolve(3, &runtime, SOURCE, Some(0), true, fetch(3)), Poll::Partial(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fallback_response_stands_in_as_the_previous_value() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
|
||||
slots.resolve(1, &runtime, SOURCE, Some(0), true, || async {
|
||||
YieldOnce(false).await;
|
||||
Poll::fallback(1, "failed")
|
||||
});
|
||||
spawner.drain();
|
||||
|
||||
let fetch = || async {
|
||||
YieldOnce(false).await;
|
||||
Poll::Final(2)
|
||||
};
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch), Poll::Partial(1));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42));
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -424,7 +314,7 @@ mod tests {
|
||||
Poll::Final(42u32)
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42));
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)]);
|
||||
}
|
||||
|
||||
@@ -438,11 +328,11 @@ mod tests {
|
||||
Poll::Final(42u32)
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
|
||||
let clone = slots.clone();
|
||||
drop(slots);
|
||||
assert_eq!(spawner.drain(), 1);
|
||||
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Final(42));
|
||||
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, fetch), Poll::Final(42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -460,7 +350,7 @@ mod tests {
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
|
||||
drop(slots);
|
||||
assert_eq!(spawner.drain(), 1);
|
||||
assert!(!finished.load(Ordering::Relaxed));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::effects::EffectKind;
|
||||
use crate::parameters::ParameterVisitor;
|
||||
use core_types::Color;
|
||||
@@ -105,7 +106,7 @@ impl Adjustment {
|
||||
Self::ColorBalance(_) => EffectKind::ColorBalance,
|
||||
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::ColorOverlay,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,7 +272,12 @@ impl Adjustment {
|
||||
}
|
||||
Self::ColorLookup { lut_file } => visitor.parameter("lut_file", lut_file, Resource::default()),
|
||||
Self::ColorOverlay { color, blend_mode, opacity } => {
|
||||
visitor.parameter("color", color, Color::BLACK);
|
||||
// Rides the row as the paint of the Paint Overlay node, which stamps it
|
||||
let mut paint = Graphic::from(*color);
|
||||
visitor.parameter("paint", &mut paint, Graphic::from(Color::BLACK));
|
||||
if let Graphic::Color(paint) = paint {
|
||||
*color = *paint.element();
|
||||
}
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,690 @@
|
||||
//! How an item's effects split into those flattened into the content's own image and the pieces drawn as layers onto what lies beneath the item, which every renderer follows.
|
||||
//! Runs of pieces that blend normally merge with each other and with the content into one layer, which the item's opacity fades as a whole.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use crate::effects::{BevelStyle, EffectCapture, EffectOperation, Effects, GlowFill, OutlineFill, outline_extents};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Which side of the content a piece of an effect draws on, and how.
|
||||
/// For PSD interop, an interior piece blends within the content's share of each pixel onto the content's color mixed with what lies beneath by the fill, so it splits by the fill.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PiecePlace {
|
||||
/// Beneath the content, like a drop shadow.
|
||||
Beneath,
|
||||
/// Over the content within its silhouette, like an inner shadow, unfaded by its fill: atop the content in the content's own layer, or cut to the content in a layer of its own.
|
||||
Within,
|
||||
/// The part of an interior piece blending with the content's own colors by its mode, in the content's own layer.
|
||||
/// With `over`, it takes only the strength left by its part over the content.
|
||||
IntoContent { over: bool },
|
||||
/// The part of an interior piece blending with what shows through the content's fill, in a layer of its mode beneath the content's, or with `over`, over it.
|
||||
Through { over: bool },
|
||||
}
|
||||
|
||||
/// One coverage of an effect that draws as a piece of its own, named like the map of it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct EffectPiece {
|
||||
pub capture: EffectCapture,
|
||||
pub place: PiecePlace,
|
||||
/// The mode the piece blends by, given as normal where its solid color blends the same either way.
|
||||
pub blend_mode: BlendMode,
|
||||
/// Whether the content hides the piece where it covers it, as for a shadow beneath the content with knockout on.
|
||||
pub knocks_out: bool,
|
||||
}
|
||||
|
||||
/// What a layer of an item draws.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LayerPart {
|
||||
/// The content with its flattened effects carried out, faded by its fill.
|
||||
Content,
|
||||
Piece(EffectPiece),
|
||||
}
|
||||
|
||||
/// One layer an item draws onto what lies beneath it: its parts composited normally in order, then blended by its mode and faded by the item's opacity.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct EffectLayer {
|
||||
pub blend_mode: BlendMode,
|
||||
pub parts: Vec<LayerPart>,
|
||||
}
|
||||
|
||||
impl EffectLayer {
|
||||
/// Whether this layer draws the content itself.
|
||||
pub fn holds_content(&self) -> bool {
|
||||
self.parts.contains(&LayerPart::Content)
|
||||
}
|
||||
}
|
||||
|
||||
/// How an item with effects draws: the leading effects carried out within the content's own image, then its layers from the bottom up.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct EffectLayers {
|
||||
/// How many of the effects, from the first, are carried out within the content's image.
|
||||
pub flattened: usize,
|
||||
pub layers: Vec<EffectLayer>,
|
||||
/// The rows from the first mask after every other effect to the end, which fade each finished layer at each pixel like the item's opacity. Empty where those masks flatten what's before them instead.
|
||||
pub trailing_masks: Range<usize>,
|
||||
}
|
||||
|
||||
impl EffectLayers {
|
||||
/// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask.
|
||||
/// Content in a mode CSS lacks is drawn normally, so it's planned that way.
|
||||
pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal };
|
||||
|
||||
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer
|
||||
let shares_content = blend_mode == BlendMode::Normal;
|
||||
let blends_into_content = shares_content && fill >= 1.;
|
||||
|
||||
// The masks after every other effect fade the layers rather than the content's image, so they flatten nothing before them
|
||||
let no_rows = operations.len()..operations.len();
|
||||
let mut trailing_masks = if layered { trailing_masks(&operations) } else { no_rows.clone() };
|
||||
|
||||
// Rows that change nothing, like a blur of no radius, flatten nothing before them
|
||||
let mut flattened = match layered {
|
||||
true => (operations[..trailing_masks.start].iter())
|
||||
.rposition(|operation| !operation.changes_nothing() && !can_be_layered(operation, blends_into_content))
|
||||
.map_or(0, |index| index + 1),
|
||||
false => operations.len(),
|
||||
};
|
||||
|
||||
// Each piece with the mode it blends by, in the order of the rows drawing them
|
||||
let pieces_from = |start: usize, end: usize| -> Vec<(EffectPiece, BlendMode)> {
|
||||
(operations.iter().enumerate().take(end).skip(start))
|
||||
.filter(|(_, operation)| !operation.changes_nothing())
|
||||
.flat_map(|(index, operation)| pieces(index, operation))
|
||||
.collect()
|
||||
};
|
||||
let has_beneath = |pieces: &[(EffectPiece, BlendMode)]| pieces.iter().any(|(piece, _)| piece.place == PiecePlace::Beneath);
|
||||
|
||||
// Flattened shadows and glows that no later pixel filter merges into the content would draw over the layered ones, so then everything is flattened
|
||||
let last_pixel_filter = (operations[..flattened].iter())
|
||||
.rposition(|operation| !operation.changes_nothing() && is_pixel_filter(operation))
|
||||
.map_or(0, |index| index + 1);
|
||||
let unmerged = pieces_from(last_pixel_filter, flattened);
|
||||
let mut pieces = pieces_from(flattened, operations.len());
|
||||
if has_beneath(&unmerged) && has_beneath(&pieces) {
|
||||
flattened = operations.len();
|
||||
trailing_masks = no_rows.clone();
|
||||
pieces.clear();
|
||||
}
|
||||
|
||||
let mut parts: Vec<(LayerPart, BlendMode)> = (pieces.iter())
|
||||
.filter(|(piece, _)| piece.place == PiecePlace::Beneath)
|
||||
.map(|&(piece, mode)| (LayerPart::Piece(piece), mode))
|
||||
.chain([(LayerPart::Content, blend_mode)])
|
||||
.collect();
|
||||
|
||||
// A shadow not knocked out in the content's layer, flattened or layered, would hide a part placed beneath that layer
|
||||
let shows_through = |piece: &EffectPiece| piece.place == PiecePlace::Beneath && !piece.knocks_out;
|
||||
let mut content_run = parts.iter().rev().skip(1).take_while(|(_, mode)| *mode == BlendMode::Normal);
|
||||
let covered_beneath = content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
|
||||
|
||||
// Interior pieces of normal content blend within its share, in its layer. Below a full fill, a blended one splits off its part through the fill into a layer beneath
|
||||
// the content's, or over it when its mode isn't straight along what lies beneath or a shadow covers that, as every later piece then does to keep their order.
|
||||
let mut into_content = Vec::new();
|
||||
let mut through_beneath = Vec::new();
|
||||
let mut over = false;
|
||||
for &(piece, mode) in pieces.iter().filter(|(piece, _)| piece.place == PiecePlace::Within) {
|
||||
let part = |place: PiecePlace| EffectPiece { place, ..piece };
|
||||
if !shares_content {
|
||||
parts.push((LayerPart::Piece(piece), mode));
|
||||
continue;
|
||||
}
|
||||
|
||||
over |= !blends_into_content && mode != BlendMode::Normal && (covered_beneath || !is_straight_along_backdrop(mode));
|
||||
match (blends_into_content || !over, mode == BlendMode::Normal) {
|
||||
(true, true) => into_content.push(piece),
|
||||
(true, false) if blends_into_content => into_content.push(part(PiecePlace::IntoContent { over: false })),
|
||||
(true, false) => {
|
||||
into_content.push(part(PiecePlace::IntoContent { over: false }));
|
||||
through_beneath.push(part(PiecePlace::Through { over: false }));
|
||||
}
|
||||
(false, _) => {
|
||||
into_content.push(part(PiecePlace::IntoContent { over: true }));
|
||||
parts.push((LayerPart::Piece(part(PiecePlace::Through { over: true })), mode));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Neighboring parts that blend normally composite together into one layer
|
||||
let mut layers: Vec<EffectLayer> = Vec::new();
|
||||
for (part, blend_mode) in parts {
|
||||
match layers.last_mut() {
|
||||
Some(layer) if blend_mode == BlendMode::Normal && layer.blend_mode == BlendMode::Normal => layer.parts.push(part),
|
||||
_ => layers.push(EffectLayer { blend_mode, parts: vec![part] }),
|
||||
}
|
||||
}
|
||||
|
||||
// The parts blending with what shows through the faded content lie directly beneath the normal run holding the content, which still fades as one
|
||||
if let Some(content_layer) = layers.iter().position(EffectLayer::holds_content) {
|
||||
layers[content_layer].parts.extend(into_content.into_iter().map(LayerPart::Piece));
|
||||
let through = through_beneath.into_iter().map(|piece| EffectLayer {
|
||||
blend_mode: piece.blend_mode,
|
||||
parts: vec![LayerPart::Piece(piece)],
|
||||
});
|
||||
layers.splice(content_layer..content_layer, through);
|
||||
}
|
||||
|
||||
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes
|
||||
if blends_into_content && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
|
||||
let content = EffectLayer {
|
||||
blend_mode: BlendMode::Normal,
|
||||
parts: vec![LayerPart::Content],
|
||||
};
|
||||
return Self {
|
||||
flattened: operations.len(),
|
||||
layers: vec![content],
|
||||
trailing_masks: no_rows,
|
||||
};
|
||||
}
|
||||
|
||||
Self { flattened, layers, trailing_masks }
|
||||
}
|
||||
|
||||
/// Like [`Self::plan`], for effects stamped in more than one space (see [`Effects::runs`]), as renderers draw them.
|
||||
/// The runs before the last are flattened into its content, faded by the `fill`, so only the last run's effects can be layered, named by their places in the whole list.
|
||||
pub fn plan_runs(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self {
|
||||
let runs = effects.runs();
|
||||
let Some((_, last_run)) = runs.last().filter(|_| runs.len() > 1) else {
|
||||
return Self::plan(effects, blend_mode, fill, layered);
|
||||
};
|
||||
|
||||
let mut planned = Self::plan(&effects.run(last_run.clone()), blend_mode, 1., layered);
|
||||
planned.flattened += last_run.start;
|
||||
planned.trailing_masks = planned.trailing_masks.start + last_run.start..planned.trailing_masks.end + last_run.start;
|
||||
for part in planned.layers.iter_mut().flat_map(|layer| &mut layer.parts) {
|
||||
if let LayerPart::Piece(piece) = part {
|
||||
piece.capture.index += last_run.start;
|
||||
}
|
||||
}
|
||||
planned
|
||||
}
|
||||
|
||||
/// The index of the layer holding the content.
|
||||
pub fn content_layer(&self) -> Option<usize> {
|
||||
self.layers.iter().position(EffectLayer::holds_content)
|
||||
}
|
||||
|
||||
/// Whether the masks after every other effect fade each finished layer (see [`Self::trailing_masks`]).
|
||||
pub fn fades_layers(&self) -> bool {
|
||||
!self.trailing_masks.is_empty()
|
||||
}
|
||||
|
||||
/// Whether the trailing masks fade the cover [`Self::knockout_cover`] gives the piece that `capture` names, as they do where the content's layer covers it from another layer.
|
||||
pub fn masks_fade_knockout_cover(&self, capture: EffectCapture) -> bool {
|
||||
self.fades_layers() && self.layer_of(capture).is_some_and(|layer| Some(layer) != self.content_layer())
|
||||
}
|
||||
|
||||
/// How strongly the content's layer covers the layered piece beneath it that `capture` names, as a multiple of that layer's alpha, which a knockout hides the piece behind:
|
||||
/// fully from the same layer, through the item's `opacity` from another, and not at all when the content blends by another mode and mixes with the piece instead.
|
||||
/// A piece shown through `1 - cover × a` of the content's layer of alpha `a` is knocked out by `(1 - alpha) / (1 - cover × a)`, for the content's full-strength `alpha`.
|
||||
pub fn knockout_cover(&self, capture: EffectCapture, opacity: f32) -> f32 {
|
||||
let (Some(piece_layer), Some(content_layer)) = (self.layer_of(capture), self.content_layer()) else {
|
||||
return 0.;
|
||||
};
|
||||
|
||||
if piece_layer == content_layer {
|
||||
1.
|
||||
} else if self.layers[content_layer].blend_mode == BlendMode::Normal {
|
||||
opacity
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer drawing the piece of an effect that `capture` names, if it's a layered piece, and the piece there (its first part, for one split in two).
|
||||
pub fn piece(&self, capture: EffectCapture) -> Option<(usize, EffectPiece)> {
|
||||
self.layers.iter().enumerate().find_map(|(index, layer)| {
|
||||
layer.parts.iter().find_map(|part| match part {
|
||||
LayerPart::Piece(piece) if piece.capture == capture => Some((index, *piece)),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The layer drawing the piece of an effect that `capture` names, if it's a layered piece.
|
||||
pub fn layer_of(&self, capture: EffectCapture) -> Option<usize> {
|
||||
self.piece(capture).map(|(layer, _)| layer)
|
||||
}
|
||||
|
||||
/// Whether a part of an interior piece blends with what shows through the content's fill, which reads the share [`EffectCapture::THROUGH_MASK`] names.
|
||||
#[cfg(test)]
|
||||
pub fn reads_through_share(&self) -> bool {
|
||||
(self.layers.iter().flat_map(|layer| &layer.parts)).any(|part| {
|
||||
matches!(
|
||||
part,
|
||||
LayerPart::Piece(EffectPiece {
|
||||
place: PiecePlace::Through { .. } | PiecePlace::IntoContent { over: true },
|
||||
..
|
||||
})
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
|
||||
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer,
|
||||
/// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
|
||||
fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool {
|
||||
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| blend_mode.to_svg_style_name().is_some() || (blend_into_content && piece.place == PiecePlace::Within);
|
||||
!is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in)
|
||||
}
|
||||
|
||||
/// Whether a mode blends a color onto what lies beneath along a straight line in it (`m × backdrop + n` for each channel), which lets a piece in it split exactly by the fill.
|
||||
fn is_straight_along_backdrop(blend_mode: BlendMode) -> bool {
|
||||
matches!(blend_mode, BlendMode::Normal | BlendMode::Multiply | BlendMode::Screen | BlendMode::Exclusion | BlendMode::HardLight)
|
||||
}
|
||||
|
||||
/// Whether an effect row processes the pixels of the content and everything drawn with it so far, as a blur, an adjustment, a mask, or a feather does.
|
||||
/// A solid paint overlay decodes into the color overlay adjustment, but it paints within the content like any other paint overlay.
|
||||
pub fn is_pixel_filter(operation: &EffectOperation) -> bool {
|
||||
match operation {
|
||||
// TODO: Make a mask between other effects fade each layer drawn before it too, as the trailing masks do, rather than flattening those layers.
|
||||
// TODO: Likewise for a trailing feather, faded by the footprint of every layer drawn together (not the content's alone, which would erase shadows past it).
|
||||
EffectOperation::Blur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } => true,
|
||||
EffectOperation::Adjustment(adjustment) => !matches!(adjustment, Adjustment::ColorOverlay { .. }),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows from the first mask after every other effect that changes something to the end, or none without such a mask or an effect before it.
|
||||
fn trailing_masks(operations: &[EffectOperation]) -> Range<usize> {
|
||||
let no_rows = operations.len()..operations.len();
|
||||
let is_mask = |operation: &EffectOperation| matches!(operation, EffectOperation::Mask { .. });
|
||||
|
||||
let Some(last_other) = operations.iter().rposition(|operation| !operation.changes_nothing() && !is_mask(operation)) else {
|
||||
return no_rows;
|
||||
};
|
||||
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing());
|
||||
first_mask.map_or(no_rows, |offset| last_other + 1 + offset..operations.len())
|
||||
}
|
||||
|
||||
/// The pieces the effect at `index` draws, each with the mode it blends by, leaving out those painting no color.
|
||||
fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendMode)> {
|
||||
// Only a drop shadow can show through the content
|
||||
let knocks_out = !matches!(operation, EffectOperation::DropShadow { knockout: false, .. });
|
||||
let piece = |plane: usize, place: PiecePlace, color: Option<Color>, blend_mode: BlendMode| {
|
||||
let capture = EffectCapture { index, plane };
|
||||
let blend_mode = piece_blend_mode(color, blend_mode);
|
||||
let piece = EffectPiece {
|
||||
capture,
|
||||
place,
|
||||
blend_mode,
|
||||
knocks_out: knocks_out && place == PiecePlace::Beneath,
|
||||
};
|
||||
color.is_none_or(|color| color.a() > 0.).then_some((piece, blend_mode))
|
||||
};
|
||||
let glow_color = |paint: &Graphic| match GlowFill::of(paint) {
|
||||
Some(GlowFill::Solid(color)) => Some(color),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
use PiecePlace::*;
|
||||
let pieces = match operation {
|
||||
EffectOperation::DropShadow { color, blend_mode, .. } => vec![piece(0, Beneath, Some(*color), *blend_mode)],
|
||||
EffectOperation::OuterGlow { color, blend_mode, .. } => vec![piece(0, Beneath, glow_color(color), *blend_mode)],
|
||||
EffectOperation::InnerShadow { color, blend_mode, .. } | EffectOperation::Satin { color, blend_mode, .. } => vec![piece(0, Within, Some(*color), *blend_mode)],
|
||||
EffectOperation::InnerGlow { color, blend_mode, .. } => vec![piece(0, Within, glow_color(color), *blend_mode)],
|
||||
EffectOperation::Outline {
|
||||
paint,
|
||||
blend_mode,
|
||||
weight,
|
||||
align,
|
||||
contour_gradient,
|
||||
} => {
|
||||
let color = match OutlineFill::of(paint, *contour_gradient) {
|
||||
Some(OutlineFill::Solid(color)) => Some(color),
|
||||
_ => None,
|
||||
};
|
||||
let (outside, inside) = outline_extents(*weight, *align);
|
||||
let outside = (outside > 0.).then(|| piece(0, Beneath, color, *blend_mode));
|
||||
let inside = (inside > 0.).then(|| piece(1, Within, color, *blend_mode));
|
||||
outside.into_iter().chain(inside).collect()
|
||||
}
|
||||
// Planes 0 and 1 light the slopes inside the content with the highlight and shadow, and 2 and 3 those outside it
|
||||
EffectOperation::BevelAndEmboss {
|
||||
style,
|
||||
highlight_color,
|
||||
highlight_blend_mode,
|
||||
shadow_color,
|
||||
shadow_blend_mode,
|
||||
..
|
||||
} => {
|
||||
let (highlight, shadow) = ((Some(*highlight_color), *highlight_blend_mode), (Some(*shadow_color), *shadow_blend_mode));
|
||||
let inside = (*style != BevelStyle::OuterBevel).then(|| [piece(0, Within, highlight.0, highlight.1), piece(1, Within, shadow.0, shadow.1)]);
|
||||
let outside = (*style != BevelStyle::InnerBevel).then(|| [piece(2, Beneath, highlight.0, highlight.1), piece(3, Beneath, shadow.0, shadow.1)]);
|
||||
inside.into_iter().chain(outside).flatten().collect()
|
||||
}
|
||||
EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)],
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)],
|
||||
EffectOperation::Blur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } | EffectOperation::Adjustment(_) => Vec::new(),
|
||||
};
|
||||
pieces.into_iter().flatten().collect()
|
||||
}
|
||||
|
||||
/// The mode a piece of a solid `color` (or of no single color) blends by, which is normal where it blends the same either way, whatever lies beneath it, like black multiplying or white screening.
|
||||
pub fn piece_blend_mode(color: Option<Color>, blend_mode: BlendMode) -> BlendMode {
|
||||
let channels = color.map(|color| [color.r(), color.g(), color.b()]);
|
||||
let all = |value: f32| channels.is_some_and(|channels| channels.iter().all(|&channel| channel == value));
|
||||
|
||||
let normal = match blend_mode {
|
||||
BlendMode::Multiply | BlendMode::Darken => all(0.),
|
||||
BlendMode::Screen | BlendMode::Lighten => all(1.),
|
||||
_ => false,
|
||||
};
|
||||
if normal { BlendMode::Normal } else { blend_mode }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::effects::EffectKind;
|
||||
|
||||
/// The default effect of `kind` in another color and blend mode.
|
||||
fn shadow(kind: EffectKind, new_color: Color, new_blend_mode: BlendMode) -> EffectOperation {
|
||||
let mut operation = EffectOperation::default_for(kind);
|
||||
if let EffectOperation::DropShadow { color, blend_mode, .. } | EffectOperation::InnerShadow { color, blend_mode, .. } = &mut operation {
|
||||
(*color, *blend_mode) = (new_color, new_blend_mode);
|
||||
}
|
||||
operation
|
||||
}
|
||||
|
||||
fn drop_shadow(color: Color, blend_mode: BlendMode) -> EffectOperation {
|
||||
shadow(EffectKind::DropShadow, color, blend_mode)
|
||||
}
|
||||
|
||||
fn inner_shadow(color: Color, blend_mode: BlendMode) -> EffectOperation {
|
||||
shadow(EffectKind::InnerShadow, color, blend_mode)
|
||||
}
|
||||
|
||||
fn capture(index: usize, plane: usize) -> EffectCapture {
|
||||
EffectCapture { index, plane }
|
||||
}
|
||||
|
||||
fn modes(layers: &EffectLayers) -> Vec<BlendMode> {
|
||||
layers.layers.iter().map(|layer| layer.blend_mode).collect()
|
||||
}
|
||||
|
||||
/// Each layer's parts as the row and plane of each piece with its place, or `None` for the content.
|
||||
fn parts(layers: &EffectLayers) -> Vec<Vec<Option<(usize, usize, PiecePlace)>>> {
|
||||
let part = |part: &LayerPart| match part {
|
||||
LayerPart::Piece(piece) => Some((piece.capture.index, piece.capture.plane, piece.place)),
|
||||
LayerPart::Content => None,
|
||||
};
|
||||
layers.layers.iter().map(|layer| layer.parts.iter().map(part).collect()).collect()
|
||||
}
|
||||
|
||||
const RED: Color = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
|
||||
const INTO: PiecePlace = PiecePlace::IntoContent { over: false };
|
||||
|
||||
#[test]
|
||||
fn effects_blending_normally_draw_as_one_layer_with_the_content() {
|
||||
// The default black shadow multiplies, which is the same as blending normally
|
||||
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::DropShadow), EffectOperation::default_for(EffectKind::Satin)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
|
||||
assert_eq!(layers.flattened, 0);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal]);
|
||||
assert_eq!(parts(&layers), [[Some((0, 0, PiecePlace::Beneath)), None, Some((1, 0, PiecePlace::Within))]]);
|
||||
|
||||
// At a full fill, that layer draws the same with everything flattened into the content's image
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(parts(&layers), [[None]]);
|
||||
|
||||
// White screening is the same as white drawn normally
|
||||
let screen = drop_shadow(Color::WHITE, BlendMode::Screen);
|
||||
assert_eq!(modes(&EffectLayers::plan(&Effects::from_operations([screen]), BlendMode::Normal, 1., true)), [BlendMode::Normal]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interior_pieces_of_normal_content_blend_within_its_layer_at_a_full_fill() {
|
||||
let red = RED.with_alpha(0.75);
|
||||
let effects = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::Screen), inner_shadow(red, BlendMode::Normal)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
assert_eq!(parts(&layers)[1], [None, Some((1, 0, INTO)), Some((2, 0, PiecePlace::Within))]);
|
||||
|
||||
// Content in a mode of its own leaves each blended piece a layer of its own
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]);
|
||||
|
||||
// A mode CSS lacks is drawn normally, so it's planned that way, and an interior piece blending within the content's layer may take one too
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]);
|
||||
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0);
|
||||
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interior_pieces_split_by_a_partial_fill() {
|
||||
let red = RED.with_alpha(0.75);
|
||||
|
||||
// A mode straight along what lies beneath leaves its part through the fill beneath the content's layer
|
||||
let screen = EffectLayers::plan(&Effects::from_operations([inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(modes(&screen), [BlendMode::Screen, BlendMode::Normal]);
|
||||
assert_eq!(parts(&screen), [vec![Some((0, 0, PiecePlace::Through { over: false }))], vec![None, Some((0, 0, INTO))]]);
|
||||
assert!(screen.reads_through_share());
|
||||
|
||||
// One that bends puts it over the content's layer, which keeps the rest
|
||||
let overlay = EffectLayers::plan(&Effects::from_operations([inner_shadow(red, BlendMode::Overlay)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(modes(&overlay), [BlendMode::Normal, BlendMode::Overlay]);
|
||||
let over = PiecePlace::IntoContent { over: true };
|
||||
assert_eq!(parts(&overlay), [vec![None, Some((0, 0, over))], vec![Some((0, 0, PiecePlace::Through { over: true }))]]);
|
||||
|
||||
// Normal pieces blend the same either way and stay whole
|
||||
let normal = EffectLayers::plan(&Effects::from_operations([inner_shadow(red, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(parts(&normal), [[None, Some((0, 0, PiecePlace::Within))]]);
|
||||
assert!(!normal.reads_through_share());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interior_pieces_after_one_over_the_content_go_over_it_too() {
|
||||
let red = RED.with_alpha(0.75);
|
||||
let (over, through_over) = (PiecePlace::IntoContent { over: true }, PiecePlace::Through { over: true });
|
||||
|
||||
// A piece that bends goes over the content, and so does each piece after it, normal or straight, to keep their order
|
||||
let effects = Effects::from_operations([inner_shadow(red, BlendMode::Overlay), inner_shadow(red, BlendMode::Normal), inner_shadow(red, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Overlay, BlendMode::Normal, BlendMode::Multiply]);
|
||||
assert_eq!(
|
||||
parts(&layers),
|
||||
[
|
||||
vec![None, Some((0, 0, over)), Some((1, 0, over)), Some((2, 0, over))],
|
||||
vec![Some((0, 0, through_over))],
|
||||
vec![Some((1, 0, through_over))],
|
||||
vec![Some((2, 0, through_over))]
|
||||
]
|
||||
);
|
||||
|
||||
// Pieces before it keep their places
|
||||
let effects = Effects::from_operations([inner_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::Overlay)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(parts(&layers)[0], [Some((0, 0, PiecePlace::Through { over: false }))]);
|
||||
assert_eq!(parts(&layers)[1], [None, Some((0, 0, INTO)), Some((1, 0, over))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interior_pieces_go_over_the_content_where_its_layer_covers_what_lies_beneath_it() {
|
||||
let red = RED.with_alpha(0.75);
|
||||
let through_over = PiecePlace::Through { over: true };
|
||||
|
||||
let with_knockout = |knocks_out: bool| {
|
||||
let mut shadow = drop_shadow(Color::BLACK.with_alpha(0.75), BlendMode::Multiply);
|
||||
if let EffectOperation::DropShadow { knockout, .. } = &mut shadow {
|
||||
*knockout = knocks_out;
|
||||
}
|
||||
shadow
|
||||
};
|
||||
|
||||
// A shadow not knocked out beneath the content in its layer would hide even a straight piece's part beneath that layer
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(false), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen]);
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
|
||||
|
||||
// A knocked-out shadow doesn't cover it there
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]);
|
||||
|
||||
// One flattened for a mode CSS lacks covers it too
|
||||
let mut flattened_shadow = with_knockout(false);
|
||||
if let EffectOperation::DropShadow { blend_mode, .. } = &mut flattened_shadow {
|
||||
*blend_mode = BlendMode::LinearBurn;
|
||||
}
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([flattened_shadow, inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 1);
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outlines_and_bevels_draw_pieces_on_both_sides_of_the_content() {
|
||||
let outline = EffectOperation::Outline {
|
||||
paint: Graphic::from(RED),
|
||||
blend_mode: BlendMode::Multiply,
|
||||
weight: 4.,
|
||||
align: vector_types::vector::style::StrokeAlign::Center,
|
||||
contour_gradient: false,
|
||||
};
|
||||
let mut bevel = EffectOperation::default_for(EffectKind::BevelAndEmboss);
|
||||
if let EffectOperation::BevelAndEmboss { style, highlight_color, .. } = &mut bevel {
|
||||
*style = BevelStyle::Emboss;
|
||||
// A highlight painting nothing draws no pieces
|
||||
*highlight_color = Color::TRANSPARENT;
|
||||
}
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([outline, bevel]), BlendMode::Normal, 1., true);
|
||||
|
||||
let all: Vec<_> = parts(&layers).into_iter().flatten().collect();
|
||||
let (beneath, within) = (PiecePlace::Beneath, PiecePlace::Within);
|
||||
assert_eq!(all, [Some((0, 0, beneath)), Some((1, 3, beneath)), None, Some((0, 1, INTO)), Some((1, 1, within))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_that_change_nothing_neither_flatten_nor_split_the_others() {
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), no_blur]), BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 0);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
|
||||
// A solid overlay at no opacity paints nothing, so the normal pieces around it stay one layer with the content
|
||||
let no_overlay = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: RED,
|
||||
blend_mode: BlendMode::LinearBurn,
|
||||
opacity: 0.,
|
||||
});
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Normal), no_overlay, inner_shadow(RED, BlendMode::Normal)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 0);
|
||||
assert_eq!(parts(&layers), [[Some((0, 0, PiecePlace::Beneath)), None, Some((2, 0, PiecePlace::Within))]]);
|
||||
}
|
||||
|
||||
fn mask() -> EffectOperation {
|
||||
EffectOperation::default_for(EffectKind::Mask)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_between_other_effects_flatten_those_before_them_into_the_content() {
|
||||
// The shadow before the mask is hidden with the content, while the one after it is cast from the masked content as a layer of its own
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), mask(), drop_shadow(RED, BlendMode::Screen)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(modes(&layers), [BlendMode::Screen, BlendMode::Normal]);
|
||||
assert!(!layers.fades_layers());
|
||||
|
||||
// Masks with no other effect before them shape the content alone
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([mask(), mask()]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!((layers.flattened, layers.fades_layers()), (2, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_masks_fade_each_layer_in_its_own_blend_mode() {
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
// The shadow before the masks keeps its layer and its mode, and the content's layer covers it as far as the masks leave of that layer
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), mask()]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (0, 1..2));
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
assert!(layers.masks_fade_knockout_cover(capture(0, 0)));
|
||||
|
||||
// Rows that change nothing don't end the trailing masks, and a mask before the other effects still shapes the content
|
||||
let effects = Effects::from_operations([mask(), drop_shadow(RED, BlendMode::Multiply), mask(), no_blur, mask()]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (1, 2..5));
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
|
||||
// A piece in the content's own layer fades with it as a whole
|
||||
let normal = Effects::from_operations([drop_shadow(RED, BlendMode::Normal), mask()]);
|
||||
let layers = EffectLayers::plan(&normal, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (0, 1..2));
|
||||
assert!(!layers.masks_fade_knockout_cover(capture(0, 0)));
|
||||
|
||||
// With everything flattened, the masks are carried out within the content's image like any other
|
||||
let layers = EffectLayers::plan(&normal, BlendMode::Normal, 1., true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2));
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5));
|
||||
let unmerged = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply), mask()]);
|
||||
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 1., true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (3, 3..3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_before_a_blur_or_a_mode_css_lacks_are_flattened() {
|
||||
let blur = EffectOperation::Blur {
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), blur, drop_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
|
||||
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), drop_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
|
||||
// A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal]);
|
||||
|
||||
// Clipped content flattens everything
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(parts(&layers), [[None]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knocked_out_pieces_hide_behind_however_the_content_covers_them() {
|
||||
let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(same_layer.knockout_cover(capture(0, 0), 0.4), 1.);
|
||||
|
||||
let own_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Multiply)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(own_layer.knockout_cover(capture(0, 0), 0.4), 0.4);
|
||||
|
||||
let blended_content = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Multiply)]), BlendMode::Screen, 0.5, true);
|
||||
assert_eq!(blended_content.knockout_cover(capture(0, 0), 0.4), 0.);
|
||||
|
||||
// A shadow with knockout off shows through the content
|
||||
let mut shown_through = drop_shadow(RED, BlendMode::Normal);
|
||||
if let EffectOperation::DropShadow { knockout, .. } = &mut shown_through {
|
||||
*knockout = false;
|
||||
}
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([shown_through]), BlendMode::Normal, 0.5, true);
|
||||
assert!(layers.piece(capture(0, 0)).is_some_and(|(_, piece)| !piece.knocks_out));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,7 @@ use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DAffine2;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use std::any::Any;
|
||||
|
||||
/// Style of noise pattern.
|
||||
@@ -109,23 +109,139 @@ pub struct NoiseSettings {
|
||||
pub cellular_jitter: f64,
|
||||
}
|
||||
|
||||
/// The fractal's family, from the classic Mandelbrot set to variations with their own signature shapes.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
pub enum MandelbrotFractal {
|
||||
/// A cardioid body ringed by rounded bulbs and branching filaments (at the default settings).
|
||||
#[default]
|
||||
ClassicMandelbrot,
|
||||
/// A curved triangular body with a bulb-and-spike arm on each corner (at the default settings).
|
||||
Tricorn,
|
||||
/// An asymmetric body fringed with jagged spires and flame-like detail (at the default settings).
|
||||
BurningShip,
|
||||
}
|
||||
|
||||
/// What the brightness outside the set comes from.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum MandelbrotExterior {
|
||||
/// No brightness throughout, leaving the set as a silhouette.
|
||||
Flat,
|
||||
#[menu_separator]
|
||||
/// How many iterations a point takes to escape, in a flat band for each iteration.
|
||||
DiscreteEscape,
|
||||
/// How many iterations a point takes to escape, smoothed into soft gradients.
|
||||
#[default]
|
||||
SmoothEscape,
|
||||
#[menu_separator]
|
||||
/// How close a point lies to the set's edge, revealing its finest filaments. This is the classic distance estimate, worked out from how quickly the orbit's derivative grows.
|
||||
Proximity,
|
||||
/// Which way around the set a point lies, as one turn of brightness circling it. This is the set's external angle, worked out from the directions its orbit escapes in, and the counterpart of the internal angle inside each bulb. It levels off when zoomed in far.
|
||||
Angle,
|
||||
/// Rays radiating out from the set along the directions points escape in. These are the set's external rays, also called its field lines.
|
||||
Rays,
|
||||
#[menu_separator]
|
||||
/// How close a point's orbit comes to the origin before escaping, relative to where its first iteration lands, casting soft shadows around each bulb. This is the classic orbit trap coloring, with the trap at the origin.
|
||||
ClosestApproach,
|
||||
/// The iteration bringing a point's orbit closest to the origin before it escapes, in a flat band for each, which ring the bulbs like the Closest Iteration's petals inside them.
|
||||
ClosestIteration,
|
||||
/// Streaks following the paths points take as they escape. This is the classic stripe average coloring, which averages the direction each iteration's value points in.
|
||||
Tendrils,
|
||||
}
|
||||
|
||||
/// What the brightness inside the set comes from.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum MandelbrotInterior {
|
||||
/// Full brightness throughout.
|
||||
#[default]
|
||||
Flat,
|
||||
#[menu_separator]
|
||||
/// How many iterations a point's orbit takes to settle into its cycle, in a flat band for each iteration, darkest at each bulb's center. This is the counterpart of the Discrete Escape outside the set.
|
||||
DiscreteSettling,
|
||||
/// How slowly a point's orbit settles into its cycle, as a smooth gradient darkest at each bulb's center, the counterpart of the Smooth Escape outside the set. It shows how weakly the orbit is drawn together, which is its Lyapunov exponent as the average factor each iteration scales distances by.
|
||||
SmoothSettling,
|
||||
#[menu_separator]
|
||||
/// How far a point lies from its bulb's center toward its edge, measured by how weakly its orbit is drawn into its cycle. This is the bulb's internal radius.
|
||||
Radius,
|
||||
/// How close a point lies to its bulb's edge, brightening toward the set's edge like the Proximity outside. This is the classic interior distance estimate, worked out from how its cycle's multiplier changes from point to point, so it dims toward the Julia end, where every point inside shares one cycle.
|
||||
Proximity,
|
||||
/// Which way a point lies from its bulb's center, measured by how its orbit turns around its cycle, giving rays out from each center. This is the bulb's internal angle.
|
||||
Angle,
|
||||
/// Rays radiating out from each bulb's center along the directions its orbit turns around its cycle, as many for each turn as the Frequency. These are the bulb's internal rays, the counterpart of the external rays outside the set.
|
||||
Rays,
|
||||
/// How many values a point's orbit cycles through, which is the same across each bulb of the set.
|
||||
Period,
|
||||
#[menu_separator]
|
||||
/// How close a point's orbit comes to the origin, relative to where its first iteration lands.
|
||||
ClosestApproach,
|
||||
/// The iteration bringing a point's orbit closest to the origin, splitting each bulb into petal-shaped bands. This is the classic closest approach iteration coloring.
|
||||
ClosestIteration,
|
||||
/// How far from the origin a point's value lies after the last iteration, which is the orbit's final magnitude.
|
||||
FinalDistance,
|
||||
/// Which way from the origin a point's value lies after the last iteration, which changes along with the number of iterations.
|
||||
FinalAngle,
|
||||
}
|
||||
|
||||
/// The settings of a Mandelbrot-style fractal, with Mandelbrot-to-Julia in percent like the Mandelbrot node's parameter.
|
||||
#[derive(Debug, Clone, Default, PartialEq, CacheHash)]
|
||||
pub struct MandelbrotSettings {
|
||||
pub fractal: MandelbrotFractal,
|
||||
pub exterior: MandelbrotExterior,
|
||||
pub interior: MandelbrotInterior,
|
||||
pub frequency: i64,
|
||||
pub scale: f64,
|
||||
pub iterations: i64,
|
||||
pub power: f64,
|
||||
pub mandelbrot_to_julia: f64,
|
||||
pub mandelbrot_slice: DVec2,
|
||||
pub julia_slice: DVec2,
|
||||
}
|
||||
|
||||
impl MandelbrotSettings {
|
||||
/// Stamps every setting onto the generator's item, whatever its value, so which attributes the item carries doesn't depend on them.
|
||||
pub fn stamp(&self, item: &mut Item<Generator>) {
|
||||
self.clone().visit_parameters(&mut StampParameters(item));
|
||||
}
|
||||
|
||||
/// Visits each setting with the attribute it rides, named after the Mandelbrot node's parameter, and its default, which is the node's.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
visitor.parameter("fractal", &mut self.fractal, MandelbrotFractal::default());
|
||||
visitor.parameter("exterior", &mut self.exterior, MandelbrotExterior::default());
|
||||
visitor.parameter("interior", &mut self.interior, MandelbrotInterior::default());
|
||||
visitor.parameter("frequency", &mut self.frequency, 1);
|
||||
visitor.parameter("scale", &mut self.scale, 100.);
|
||||
visitor.parameter("iterations", &mut self.iterations, 256);
|
||||
visitor.parameter("power", &mut self.power, 2.);
|
||||
visitor.parameter("mandelbrot_to_julia", &mut self.mandelbrot_to_julia, 0.);
|
||||
visitor.parameter("mandelbrot_slice", &mut self.mandelbrot_slice, DVec2::ZERO);
|
||||
visitor.parameter("julia_slice", &mut self.julia_slice, DVec2::new(-0.8, 0.156));
|
||||
}
|
||||
}
|
||||
|
||||
/// A procedural pattern, a function of position in its own space that renders across any area at any resolution.
|
||||
#[derive(Debug, Clone, PartialEq, CacheHash)]
|
||||
pub enum GeneratorPattern {
|
||||
Noise(NoiseSettings),
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
/// A Mandelbrot-style fractal, with its space's origin at the complex plane's and the scale's number of units spanning one unit of the plane.
|
||||
Mandelbrot(MandelbrotSettings),
|
||||
}
|
||||
|
||||
/// A procedural pattern filling the whole plane, which renderers draw at whatever resolution they need across whatever part they see.
|
||||
/// The item's transform places the pattern's own space, and a noise pattern's settings ride the item as attributes named after the Noise Pattern node's parameters.
|
||||
/// The item's transform places the pattern's own space, and its settings ride the item as attributes named after its node's parameters.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny)]
|
||||
pub enum Generator {
|
||||
#[default]
|
||||
Noise,
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
/// A Mandelbrot-style fractal, with its space's origin at the complex plane's and the scale's number of units spanning one unit of the plane.
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
@@ -177,7 +293,7 @@ impl NoiseSettings {
|
||||
}
|
||||
|
||||
impl GeneratorPattern {
|
||||
/// The pattern a generator draws, reading a noise pattern's settings with `attribute`, which looks one of the item's attributes up by key.
|
||||
/// The pattern a generator draws, reading its settings with `attribute`, which looks one of the item's attributes up by key.
|
||||
/// Each setting the item lacks takes its default.
|
||||
pub fn decode<'a>(generator: Generator, attribute: &'a dyn Fn(&str) -> Option<&'a dyn Any>) -> Self {
|
||||
match generator {
|
||||
@@ -186,7 +302,11 @@ impl GeneratorPattern {
|
||||
settings.visit_parameters(&mut ReadParameters(attribute));
|
||||
Self::Noise(settings)
|
||||
}
|
||||
Generator::Mandelbrot => Self::Mandelbrot,
|
||||
Generator::Mandelbrot => {
|
||||
let mut settings = MandelbrotSettings::default();
|
||||
settings.visit_parameters(&mut ReadParameters(attribute));
|
||||
Self::Mandelbrot(settings)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -627,11 +627,15 @@ impl Graphic {
|
||||
}
|
||||
|
||||
pub fn can_reduce_to_clip_path(&self) -> bool {
|
||||
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
||||
match self {
|
||||
Graphic::Vector(item) => vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE)),
|
||||
Graphic::VectorList(list) => {
|
||||
(0..list.len()).all(|index| vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index)))
|
||||
Graphic::Vector(item) => {
|
||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none() && vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
|
||||
}
|
||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none()
|
||||
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user