mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c54608c12d | ||
|
|
c403654745 | ||
|
|
6c3232ee8c | ||
|
|
30164b921e | ||
|
|
b10aa51efb | ||
|
|
5d00e45354 | ||
|
|
69c0dd140d | ||
|
|
9a8269c953 | ||
|
|
76361baaa1 | ||
|
|
f569120bf6 | ||
|
|
0df1e16233 | ||
|
|
65bb0ff838 | ||
|
|
d5a7504e3a | ||
|
|
fa65c1f8dc |
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
+23
-145
@@ -1238,7 +1238,7 @@ dependencies = [
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
"tinyvec",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
@@ -2135,9 +2135,6 @@ name = "float-cmp"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
@@ -2157,15 +2154,6 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.12.7"
|
||||
@@ -2207,7 +2195,7 @@ dependencies = [
|
||||
"linebender_resource_handle",
|
||||
"memmap2",
|
||||
"parlance",
|
||||
"read-fonts 0.41.0",
|
||||
"read-fonts",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -2444,21 +2432,6 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glifo"
|
||||
version = "0.4.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"foldhash 0.2.0",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"peniko",
|
||||
"skrifa 0.44.0",
|
||||
"smallvec",
|
||||
"vello_common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.4"
|
||||
@@ -2561,6 +2534,18 @@ dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graph-text"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"convert_case 0.12.0",
|
||||
"core-types",
|
||||
"glam",
|
||||
"log",
|
||||
"proc-macro2",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graphene-animation"
|
||||
version = "0.0.0"
|
||||
@@ -2691,6 +2676,7 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graph-text",
|
||||
"graphene-application-io",
|
||||
"graphene-canvas-utils",
|
||||
"graphene-core",
|
||||
@@ -3066,7 +3052,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"read-fonts 0.41.0",
|
||||
"read-fonts",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -3454,12 +3440,6 @@ dependencies = [
|
||||
"quick-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "imagesize"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
|
||||
|
||||
[[package]]
|
||||
name = "imagesize"
|
||||
version = "0.15.0"
|
||||
@@ -3832,33 +3812,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
"flate2",
|
||||
"float-cmp",
|
||||
"gif",
|
||||
"image-webp",
|
||||
"imagesize 0.14.0",
|
||||
"indexmap",
|
||||
"pdf-writer",
|
||||
"png 0.18.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"siphasher",
|
||||
"skrifa 0.42.1",
|
||||
"smallvec",
|
||||
"subsetter",
|
||||
"tiny-skia-path",
|
||||
"xmp-writer",
|
||||
"yoke",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kurbo"
|
||||
version = "0.13.1"
|
||||
@@ -5092,7 +5045,7 @@ dependencies = [
|
||||
"parlance",
|
||||
"parley_data",
|
||||
"parley_emoji",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5123,18 +5076,6 @@ dependencies = [
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdf-writer"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peer-transport"
|
||||
version = "0.0.0"
|
||||
@@ -5937,16 +5878,6 @@ dependencies = [
|
||||
"yasna",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.39.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.41.0"
|
||||
@@ -5954,7 +5885,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.12.7",
|
||||
"font-types",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
@@ -6097,19 +6028,16 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"glifo",
|
||||
"graphene-application-io",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"krilla",
|
||||
"kurbo",
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
@@ -6687,12 +6615,6 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
@@ -7054,16 +6976,6 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.42.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
@@ -7071,7 +6983,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.41.0",
|
||||
"read-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7250,18 +7162,6 @@ version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subsetter"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"rustc-hash 2.1.3",
|
||||
"skrifa 0.42.1",
|
||||
"write-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "substring"
|
||||
version = "1.4.5"
|
||||
@@ -7444,7 +7344,7 @@ dependencies = [
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
"thiserror 2.0.21",
|
||||
"titlecase",
|
||||
"tsify",
|
||||
@@ -8044,14 +7944,14 @@ dependencies = [
|
||||
"flate2",
|
||||
"fontdb",
|
||||
"harfrust",
|
||||
"imagesize 0.15.0",
|
||||
"imagesize",
|
||||
"kurbo",
|
||||
"log",
|
||||
"pico-args",
|
||||
"roxmltree 0.21.2",
|
||||
"simplecss",
|
||||
"siphasher",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
"strict-num",
|
||||
"svgtypes",
|
||||
"tiny-skia-path",
|
||||
@@ -8136,7 +8036,6 @@ dependencies = [
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsify",
|
||||
@@ -8213,7 +8112,6 @@ version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"glifo",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
@@ -8696,7 +8594,6 @@ dependencies = [
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"vello_gpu",
|
||||
"web-sys",
|
||||
@@ -9397,19 +9294,6 @@ dependencies = [
|
||||
"toml 0.5.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "write-fonts"
|
||||
version = "0.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
|
||||
dependencies = [
|
||||
"font-types 0.11.3",
|
||||
"indexmap",
|
||||
"kurbo",
|
||||
"log",
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
@@ -9550,12 +9434,6 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||
|
||||
[[package]]
|
||||
name = "xmp-writer"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "yansi"
|
||||
version = "1.0.1"
|
||||
|
||||
+2
-4
@@ -93,6 +93,7 @@ graphene-application-io = { path = "node-graph/libraries/application-io" }
|
||||
graphene-resource = { path = "node-graph/libraries/resources" }
|
||||
graphene-animation = { path = "node-graph/libraries/animation" }
|
||||
core-types = { path = "node-graph/libraries/core-types" }
|
||||
graph-text = { path = "node-graph/libraries/graph-text" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
@@ -215,9 +216,7 @@ url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support", "text"] }
|
||||
glifo = { version = "0.4", default-features = false, features = ["std"] }
|
||||
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
|
||||
usvg = "0.49"
|
||||
simplecss = "0.2"
|
||||
parley = { version = "0.12", default-features = false, features = ["std"] }
|
||||
@@ -320,4 +319,3 @@ fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "2
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
glifo = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -103,7 +103,22 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
DialogMessage::RequestExportDialog => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
self.export_dialog.artboards = document.artboard_names().into_iter().collect();
|
||||
let artboards = document
|
||||
.metadata()
|
||||
.all_layers()
|
||||
.filter(|&layer| document.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| {
|
||||
let name = document
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
.collect();
|
||||
|
||||
self.export_dialog.artboards = artboards;
|
||||
|
||||
if let ExportBounds::Artboard(layer) = self.export_dialog.bounds
|
||||
&& !self.export_dialog.artboards.contains_key(&layer)
|
||||
|
||||
@@ -94,9 +94,9 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||
|
||||
impl LayoutHolder for ExportDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
// The vector types, then the raster ones
|
||||
// The vector type, then the raster ones
|
||||
let file_types = [
|
||||
vec![(FileType::Svg, "SVG"), (FileType::Pdf, "PDF")],
|
||||
vec![(FileType::Svg, "SVG")],
|
||||
vec![
|
||||
(FileType::Png, "PNG"),
|
||||
(FileType::Jpg, "JPG"),
|
||||
@@ -131,25 +131,14 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let scale_description = match self.file_type {
|
||||
FileType::Pdf => "Resolution of the images of effects and other content PDF can't draw itself, where 1 is 300 DPI.",
|
||||
_ => "Size of the exported image relative to the document's size.",
|
||||
};
|
||||
let resolution = vec![
|
||||
TextLabel::new("Scale Factor")
|
||||
.table_align(true)
|
||||
.sizing(WidgetSizing::fixed(100))
|
||||
.tooltip_label("Scale Factor")
|
||||
.tooltip_description(scale_description)
|
||||
.widget_instance(),
|
||||
TextLabel::new("Scale Factor").table_align(true).sizing(WidgetSizing::fixed(100)).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.scale_factor))
|
||||
.unit("")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.increment_step(0.5)
|
||||
.tooltip_label("Scale Factor")
|
||||
.tooltip_description(scale_description)
|
||||
.disabled(self.file_type == FileType::Svg)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
||||
.sizing(WidgetSizing::default().min_width(200))
|
||||
|
||||
@@ -78,7 +78,6 @@ pub enum FileType {
|
||||
Tga,
|
||||
Ico,
|
||||
Svg,
|
||||
Pdf,
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
@@ -92,15 +91,9 @@ impl FileType {
|
||||
FileType::Tga => "tga",
|
||||
FileType::Ico => "ico",
|
||||
FileType::Svg => "svg",
|
||||
FileType::Pdf => "pdf",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file holds vector content rather than an image of the export's area.
|
||||
pub fn is_vector(self) -> bool {
|
||||
matches!(self, FileType::Svg | FileType::Pdf)
|
||||
}
|
||||
|
||||
pub fn file_filter(self) -> FileFilter {
|
||||
let name = match self {
|
||||
FileType::Png => "PNG Image",
|
||||
@@ -111,7 +104,6 @@ impl FileType {
|
||||
FileType::Tga => "TGA Image",
|
||||
FileType::Ico => "ICO Image",
|
||||
FileType::Svg => "SVG Image",
|
||||
FileType::Pdf => "PDF Document",
|
||||
};
|
||||
FileFilter {
|
||||
name: name.into(),
|
||||
@@ -137,7 +129,7 @@ impl FileType {
|
||||
FileType::Bmp => ImageFormat::Bmp,
|
||||
FileType::Tga => ImageFormat::Tga,
|
||||
FileType::Ico => ImageFormat::Ico,
|
||||
FileType::Svg | FileType::Pdf => return Err(format!("{} cannot be exported from an image buffer", self.extension().to_uppercase())),
|
||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||
};
|
||||
if self == FileType::Ico && (width > 256 || height > 256) {
|
||||
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
|
||||
@@ -236,7 +228,6 @@ mod tests {
|
||||
#[test]
|
||||
fn file_types_that_cannot_hold_the_image_say_so() {
|
||||
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Pdf.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
|
||||
|
||||
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
|
||||
|
||||
@@ -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;
|
||||
@@ -1265,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,
|
||||
@@ -1446,6 +1454,11 @@ macro_rules! known_item_types {
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
|
||||
@@ -2445,20 +2445,6 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
/// The document's artboards with their names, called "Artboard" while left unnamed.
|
||||
pub fn artboard_names(&self) -> Vec<(LayerNodeIdentifier, String)> {
|
||||
(self.metadata().all_layers())
|
||||
.filter(|&layer| self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| {
|
||||
let name = (self.network_interface.node_metadata(&layer.to_node(), &[]))
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
|
||||
&self.breadcrumb_network_path
|
||||
}
|
||||
|
||||
@@ -206,6 +206,9 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||
]);
|
||||
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
|
||||
.expect("Text to Vector node does not exist")
|
||||
.default_node_template();
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
@@ -213,13 +216,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.expect("Fill node does not exist")
|
||||
.default_node_template();
|
||||
|
||||
// Build the chain `Text -> Transform -> Fill -> layer`, keeping the text native so backends lay out and draw its glyphs
|
||||
// Build the chain `Text -> Text to Vector -> Transform -> Fill -> layer`
|
||||
let text_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_id, text, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
|
||||
|
||||
self.responses.add(DocumentMessage::Resource(ResourceMessage::AddFont { resource_id: font_resource_id, font }));
|
||||
|
||||
let text_to_vector_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_to_vector_id, text_to_vector, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_to_vector_id, layer, &[], self.import);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
|
||||
|
||||
@@ -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;
|
||||
@@ -54,6 +56,8 @@ impl NodeInspectorContext<'_> {
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
|
||||
/// 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;
|
||||
/// Input position of the clip parameter on the "Artboard" layer template.
|
||||
pub const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||
/// Input position of the control path parameter on the "Blend" network node template.
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
|
||||
|
||||
@@ -107,8 +111,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 +139,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 +209,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,62 +262,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,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_scale".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -1100,6 +479,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
||||
)])
|
||||
@@ -1116,6 +496,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
||||
)])
|
||||
@@ -1222,6 +603,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
" px",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -1237,6 +619,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"H",
|
||||
"x",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -1357,7 +740,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, false)])
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)])
|
||||
}),
|
||||
);
|
||||
map
|
||||
@@ -1605,6 +988,29 @@ mod test {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// A graph text 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() {
|
||||
let sources = graphene_std::registry::GRAPH_SOURCES.lock().unwrap().len();
|
||||
let graphs = &*graphene_std::graph_text::GRAPHS;
|
||||
assert!(!graphs.is_empty(), "the graphs in `graphene_std` should be registered");
|
||||
assert_eq!(graphs.len(), sources, "every registered graph should resolve");
|
||||
|
||||
for graph in graphs {
|
||||
assert!(resolve_network_node_type(graph.identifier).is_some(), "the '{}' graph should have a definition", graph.identifier);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_index_constants_match_the_graphs() {
|
||||
use graphene_std::graph_text::import_index;
|
||||
|
||||
assert_eq!(import_index("Artboard", "location"), Some(super::ARTBOARD_LOCATION_INPUT_INDEX));
|
||||
assert_eq!(import_index("Artboard", "dimensions"), Some(super::ARTBOARD_DIMENSIONS_INPUT_INDEX));
|
||||
assert_eq!(import_index("Artboard", "clip"), Some(super::ARTBOARD_CLIP_INPUT_INDEX));
|
||||
assert_eq!(import_index("Blend", "path"), Some(super::BLEND_PATH_INPUT_INDEX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||
use glam::{DAffine2, UVec2};
|
||||
@@ -1745,21 +1151,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]
|
||||
@@ -1776,7 +1197,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)));
|
||||
@@ -1790,7 +1211,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)));
|
||||
@@ -1799,8 +1220,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 {
|
||||
|
||||
+422
-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,241 @@ 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);
|
||||
}
|
||||
add_graph_definitions(graph_text::GRAPHS.clone(), &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 text 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 in graph text, 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 in graph text.
|
||||
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();
|
||||
|
||||
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 = IVec2::from(node.position);
|
||||
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
|
||||
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).map_err(|reason| GraphDefinitionError::Invalid(format!("input {input_index} of its node {index}, '{name}', is invalid: {reason}")))?;
|
||||
}
|
||||
|
||||
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::<Result<_, _>>()
|
||||
.map_err(GraphDefinitionError::Invalid)?;
|
||||
|
||||
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.
|
||||
/// A value must have the type of that default, if it has one.
|
||||
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> Result<NodeInput, String> {
|
||||
Ok(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 value = graph_value(value);
|
||||
if let NodeInput::Value { tagged_value, .. } = default
|
||||
&& **tagged_value != TaggedValue::None
|
||||
&& element_type(&tagged_value.ty()) != element_type(&value.ty())
|
||||
{
|
||||
return Err(format!("its value `{value:?}` doesn't have the input's type, `{:?}`", tagged_value.ty()));
|
||||
}
|
||||
NodeInput::value(value, 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.clone()
|
||||
}
|
||||
|
||||
fn graph_value(value: &GraphValue) -> TaggedValue {
|
||||
match value {
|
||||
GraphValue::Integer(integer) => TaggedValue::Integer(*integer),
|
||||
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 +341,192 @@ 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",
|
||||
identifier: "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,
|
||||
path: identifier,
|
||||
category: "Test",
|
||||
icon: None,
|
||||
description: "",
|
||||
version: 1,
|
||||
layer: false,
|
||||
imports: vec![number_import()],
|
||||
exports: vec![GraphExportMetadata {
|
||||
name: "Out",
|
||||
identifier: "out",
|
||||
description: "",
|
||||
source: GraphInputSource::Node { node: 0, output: 0 },
|
||||
}],
|
||||
nodes: vec![GraphNodeMetadata {
|
||||
implementation,
|
||||
inputs,
|
||||
position: (0, 0),
|
||||
layer: false,
|
||||
display_name: None,
|
||||
hidden: false,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
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", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), 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", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), 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", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
|
||||
let second = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), 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 a_value_must_have_the_type_of_the_input_it_feeds() {
|
||||
let number_input = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
let value = |value| GraphInputSource::Value { value, exposed: None };
|
||||
|
||||
assert!(graph_input(&value(GraphValue::Integer(3)), &number_input).is_err());
|
||||
assert!(matches!(graph_input(&value(GraphValue::Number(3.)), &number_input), Ok(NodeInput::Value { .. })));
|
||||
}
|
||||
|
||||
#[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", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), 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::graph_text::import_index("Artboard", "location").expect("Artboard should have a location import");
|
||||
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(),
|
||||
//
|
||||
|
||||
@@ -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, 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
|
||||
// ============
|
||||
@@ -442,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(),
|
||||
@@ -880,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, disabled: 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 {
|
||||
@@ -895,7 +959,7 @@ 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))))
|
||||
@@ -906,7 +970,7 @@ 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()))))
|
||||
@@ -921,7 +985,7 @@ 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))))
|
||||
@@ -932,7 +996,7 @@ 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()))))
|
||||
@@ -2377,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);
|
||||
|
||||
@@ -2416,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(),
|
||||
]);
|
||||
@@ -2432,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),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2760,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, 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, false);
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
|
||||
widgets.push(spacing);
|
||||
}
|
||||
}
|
||||
@@ -2903,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)]
|
||||
@@ -3225,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;
|
||||
}
|
||||
|
||||
@@ -3274,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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,7 @@
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_CLIP_INPUT_INDEX;
|
||||
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 +800,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 +827,26 @@ 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 graph text describes 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 field = graphene_std::graph_text::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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -472,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",
|
||||
@@ -484,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"],
|
||||
},
|
||||
// ================================
|
||||
@@ -539,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",
|
||||
@@ -548,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 {
|
||||
@@ -652,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,
|
||||
@@ -1280,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
|
||||
@@ -1566,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 {
|
||||
@@ -1631,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 {
|
||||
@@ -1761,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
|
||||
@@ -2201,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
|
||||
@@ -2370,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 {
|
||||
@@ -2604,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()) {
|
||||
@@ -2815,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);
|
||||
|
||||
@@ -4006,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
|
||||
@@ -4558,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::*;
|
||||
@@ -5044,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, &[]);
|
||||
@@ -5061,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)
|
||||
);
|
||||
}
|
||||
@@ -5078,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, &[]);
|
||||
|
||||
@@ -5088,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.)));
|
||||
}
|
||||
|
||||
@@ -5170,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);
|
||||
@@ -5185,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))
|
||||
);
|
||||
}
|
||||
@@ -5713,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() {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -7,7 +7,7 @@ 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;
|
||||
@@ -27,7 +27,7 @@ mod recompile_tests;
|
||||
mod runtime;
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ExecutionRequest {
|
||||
execution_id: u64,
|
||||
render_config: RenderConfig,
|
||||
@@ -284,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();
|
||||
@@ -356,7 +355,6 @@ impl NodeGraphExecutor {
|
||||
render_mode: document.render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
metadata: None,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -424,7 +422,6 @@ impl NodeGraphExecutor {
|
||||
render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: true,
|
||||
metadata: None,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -449,12 +446,10 @@ impl NodeGraphExecutor {
|
||||
let previewed = document.network_interface.previewed_nodes();
|
||||
let resources = document.resources.registry.clone();
|
||||
|
||||
let export_format = match export_config.file_type {
|
||||
FileType::Svg => graphene_std::application_io::ExportFormat::Svg,
|
||||
FileType::Pdf => graphene_std::application_io::ExportFormat::Pdf {
|
||||
artboards_as_pages: export_config.bounds == ExportBounds::AllArtwork,
|
||||
},
|
||||
_ => graphene_std::application_io::ExportFormat::Raster,
|
||||
let export_format = if export_config.file_type == FileType::Svg {
|
||||
graphene_std::application_io::ExportFormat::Svg
|
||||
} else {
|
||||
graphene_std::application_io::ExportFormat::Raster
|
||||
};
|
||||
|
||||
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
|
||||
@@ -487,10 +482,6 @@ impl NodeGraphExecutor {
|
||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
metadata: Some(graphene_std::application_io::ExportMetadata {
|
||||
title: export_config.name.clone(),
|
||||
artboard_names: (document.artboard_names().into_iter()).map(|(layer, name)| (layer.to_node(), name)).collect(),
|
||||
}),
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -709,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;
|
||||
}
|
||||
|
||||
@@ -932,7 +916,6 @@ impl NodeGraphExecutor {
|
||||
render_mode: document.render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
metadata: None,
|
||||
};
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
@@ -1064,11 +1047,6 @@ impl NodeGraphExecutor {
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
return;
|
||||
}
|
||||
RenderOutputType::Pdf { data } => {
|
||||
log::error!("Invalid node graph output type: a PDF document of {} bytes", data.len());
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let RenderMetadata {
|
||||
@@ -1136,20 +1114,10 @@ impl NodeGraphExecutor {
|
||||
content: svg.into_bytes().into(),
|
||||
});
|
||||
}
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Pdf { data }, ..
|
||||
}) if file_type == FileType::Pdf => {
|
||||
responses.add(FrontendMessage::TriggerSaveFile {
|
||||
name,
|
||||
folder,
|
||||
filters,
|
||||
content: data.into(),
|
||||
});
|
||||
}
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Buffer { data, width, height },
|
||||
..
|
||||
}) if !file_type.is_vector() => {
|
||||
}) if file_type != FileType::Svg => {
|
||||
let content = match file_type.encode(width, height, data) {
|
||||
Ok(content) => content.into(),
|
||||
Err(description) => {
|
||||
|
||||
@@ -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);
|
||||
@@ -294,12 +274,12 @@ impl NodeRuntime {
|
||||
let dirty = self.dirty.swap(false, Ordering::Acquire);
|
||||
let mut texture = None;
|
||||
|
||||
if let Some(export) = self.pending_export.clone() {
|
||||
if let Some(export) = self.pending_export {
|
||||
if dirty {
|
||||
self.run_export(export).await;
|
||||
}
|
||||
} else {
|
||||
let viewport = if dirty { self.pending.clone() } else { None };
|
||||
let viewport = if dirty { self.pending } else { None };
|
||||
|
||||
if let Some(document_id) = self.pending_thumbnails.take()
|
||||
&& viewport.is_none()
|
||||
@@ -336,10 +316,9 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> {
|
||||
let execution_id = request.execution_id;
|
||||
self.thumbnails.set_scale(request.render_config.scale);
|
||||
|
||||
let mut result = self.evaluate(request.clone())?;
|
||||
let mut result = self.evaluate(request)?;
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
@@ -391,7 +370,7 @@ impl NodeRuntime {
|
||||
None
|
||||
};
|
||||
|
||||
self.respond(execution_id, result, observations).await;
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
texture
|
||||
}
|
||||
|
||||
@@ -436,7 +415,6 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
async fn run_export(&mut self, request: ExecutionRequest) {
|
||||
let execution_id = request.execution_id;
|
||||
let result = self.evaluate(request);
|
||||
if matches!(result, Some(ExecutionResult::Pending)) {
|
||||
return;
|
||||
@@ -453,12 +431,12 @@ impl NodeRuntime {
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
}
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.respond(execution_id, result, observations).await;
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
}
|
||||
|
||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||
// Eyedropper should use the same time and pointer to not invalidate the cache
|
||||
if let Some(viewport) = &self.pending {
|
||||
if let Some(viewport) = self.pending {
|
||||
request.render_config.time = viewport.render_config.time;
|
||||
request.render_config.pointer = viewport.render_config.pointer;
|
||||
}
|
||||
@@ -486,11 +464,10 @@ impl NodeRuntime {
|
||||
render_config.export_format = ExportFormat::Svg;
|
||||
}
|
||||
|
||||
let for_export = render_config.for_export;
|
||||
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 for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
||||
Ok(Ok(Poll::Fallback(boxed))) => {
|
||||
@@ -544,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");
|
||||
@@ -575,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:?}"))
|
||||
});
|
||||
@@ -594,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);
|
||||
@@ -791,7 +761,7 @@ mod tests {
|
||||
|
||||
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
|
||||
fn last_request(editor: &EditorTestUtils) -> Option<u64> {
|
||||
editor.runtime.pending.as_ref().map(|request| request.execution_id)
|
||||
editor.runtime.pending.map(|request| request.execution_id)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -911,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;
|
||||
@@ -990,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]
|
||||
@@ -1083,60 +995,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pdf_export_saves_a_pdf_document() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
send_export(&mut editor, FileType::Pdf);
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
|
||||
let saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveFile { name, content, .. } => Some((name, content)),
|
||||
_ => None,
|
||||
});
|
||||
let Some((name, content)) = saved else { panic!("the export should save a file") };
|
||||
|
||||
assert!(name.ends_with(".pdf"), "the file should be named as a PDF: {name}");
|
||||
assert!(content.starts_with(b"%PDF-"), "the file should hold a PDF document");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_pdf_export_draws_effects_as_images_the_gpu_renders() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use graphene_std::blending_nodes::effects::drop_shadow;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
let node_type = DefinitionIdentifier::ProtoNode(drop_shadow::IDENTIFIER);
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||
|
||||
// The export waits for the render node to read the image of the shadowed rectangle back into the PDF
|
||||
send_export(&mut editor, FileType::Pdf);
|
||||
let mut saved = None;
|
||||
for _ in 0..100 {
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
|
||||
_ => None,
|
||||
});
|
||||
if saved.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(saved) = saved else { panic!("the export never finished") };
|
||||
|
||||
assert!(saved.starts_with(b"%PDF-"), "the file should hold a PDF document");
|
||||
let embeds_image = saved.windows(b"/Subtype/Image".len()).any(|window| window == b"/Subtype/Image");
|
||||
assert!(embeds_image, "the shadowed rectangle should be an image the GPU rendered");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_svg_export_draws_effects_svg_filters_cannot_carry_out_as_images_the_gpu_renders() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 },
|
||||
|
||||
+35
-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 its graph text (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
|
||||
|
||||
## Inspector
|
||||
|
||||
@@ -127,7 +127,40 @@ 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 is written in graph text, a Rust-like syntax parsed at runtime by the `graph-text` crate. Built-in graphs are registered with the `core_types::graph!` macro, which only records the text and where it's written. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
|
||||
|
||||
```rs
|
||||
graph! {
|
||||
#![syntax(1)]
|
||||
use graphene_std::platform_application_io::{bytes_to_image@1, load_resource@1};
|
||||
|
||||
/// Loads an image from a given URL.
|
||||
#[category("Data: I/O"), icon("NodeLoadImage")]
|
||||
fn load_image@1(
|
||||
_,
|
||||
/// The web address or local asset path of the image to load.
|
||||
#[name("URL")]
|
||||
url,
|
||||
) -> (
|
||||
/// The loaded image.
|
||||
image,
|
||||
) {
|
||||
load_resource(url) >> bytes_to_image()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The text starts with its syntax version, `#![syntax(1)]`. The `use` section names each node by its identifier's module path and function name, at the declaration version it was written for, and `as` renames one. A graph's own version follows its name, like `load_image@1`. The graph's attributes are `category`, `icon`, `name`, and `layer`, and its name (or the title derived from its function name) is its catalog identifier, which documents store.
|
||||
|
||||
The function's parameters are the subgraph's imports, written without types, and `_` is a primary import that takes nothing. An import inherits its type, default, description, and widget settings from the inner parameter of its own name that it feeds, or else from the first one, and its attributes override those: `name`, `expose`, `default`, `widget`, `unit`, `hard`, `soft`, `range`, `step`, `display_decimal_places`, `multiline`, `progression`, `labels`, `integer`, and `blank_assist`. The exports are named in parentheses after `->`.
|
||||
|
||||
In the body, `let` binds a node, `>>` 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. A value has the type it's written with, so `1` is an integer and `1.` a number, and `#[exposed]` before an argument exposes its value. State methods after a call, each written once, set the node's display name (`.named("…")`) and flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`). Nodes are placed left of the node they feed, so positions are only written to adjust that, with `.offset(x, y)` or `.at(x, y)` in grid units. A graph's output name after a call or binding, like `.captures`, wires from that output instead of the primary one. The body ends with one value per export.
|
||||
|
||||
The `every_graph_resolves` test in `subgraphs.rs` reports any graph whose text doesn't resolve, with the place it's written. Every input a call leaves out keeps the default from the node's own definition.
|
||||
|
||||
## Executing a document `NodeNetwork`
|
||||
|
||||
|
||||
@@ -540,6 +540,11 @@ tagged_value! {
|
||||
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),
|
||||
@@ -690,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) => {
|
||||
@@ -709,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)
|
||||
}
|
||||
@@ -924,8 +974,6 @@ pub enum RenderOutputType {
|
||||
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
|
||||
image_data: Vec<(u64, CanvasImage)>,
|
||||
},
|
||||
/// A PDF document's file contents.
|
||||
Pdf { data: Vec<u8> },
|
||||
#[cfg(target_family = "wasm")]
|
||||
CanvasFrame { canvas_id: u64, resolution: DVec2 },
|
||||
}
|
||||
@@ -944,7 +992,6 @@ impl CacheHash for RenderOutputType {
|
||||
svg.cache_hash(state);
|
||||
image_data.cache_hash(state);
|
||||
}
|
||||
Self::Pdf { data } => data.cache_hash(state),
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::CanvasFrame { canvas_id, resolution } => {
|
||||
canvas_id.cache_hash(state);
|
||||
|
||||
@@ -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};
|
||||
@@ -18,7 +17,6 @@ use std::time::Duration;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FileType {
|
||||
Svg,
|
||||
Pdf,
|
||||
Png,
|
||||
Jpg,
|
||||
Webp,
|
||||
@@ -30,7 +28,7 @@ pub enum FileType {
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
/// The image format of a file type encoded from a single image, which excludes SVG, PDF, and GIF.
|
||||
/// The image format of a file type encoded from a single image, which excludes SVG and GIF.
|
||||
fn raster_format(self) -> Option<ImageFormat> {
|
||||
match self {
|
||||
FileType::Png => Some(ImageFormat::Png),
|
||||
@@ -40,7 +38,7 @@ impl FileType {
|
||||
FileType::Bmp => Some(ImageFormat::Bmp),
|
||||
FileType::Tga => Some(ImageFormat::Tga),
|
||||
FileType::Ico => Some(ImageFormat::Ico),
|
||||
FileType::Svg | FileType::Pdf | FileType::Gif => None,
|
||||
FileType::Svg | FileType::Gif => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +46,6 @@ impl FileType {
|
||||
pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
|
||||
match path.extension().and_then(|s| s.to_str()) {
|
||||
Some("svg") => Ok(FileType::Svg),
|
||||
Some("pdf") => Ok(FileType::Pdf),
|
||||
Some("png") => Ok(FileType::Png),
|
||||
Some("jpg" | "jpeg") => Ok(FileType::Jpg),
|
||||
Some("webp") => Ok(FileType::Webp),
|
||||
@@ -57,14 +54,13 @@ pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
|
||||
Some("tga") => Ok(FileType::Tga),
|
||||
Some("ico") => Ok(FileType::Ico),
|
||||
Some("gif") => Ok(FileType::Gif),
|
||||
_ => Err("Unsupported file extension. Supported formats: .svg, .pdf, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif".to_string()),
|
||||
_ => Err("Unsupported file extension. Supported formats: .svg, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// One rendered frame of the document, as SVG text, a PDF document, or 8-bit RGBA pixels with straight alpha.
|
||||
/// One rendered frame of the document, as SVG text or as 8-bit RGBA pixels with straight alpha.
|
||||
pub enum RenderedFrame {
|
||||
Svg(String),
|
||||
Pdf(Vec<u8>),
|
||||
Raster { data: Vec<u8>, width: u32, height: u32 },
|
||||
}
|
||||
|
||||
@@ -91,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(),
|
||||
@@ -108,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 {
|
||||
@@ -121,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());
|
||||
};
|
||||
|
||||
@@ -156,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,
|
||||
@@ -168,11 +165,7 @@ pub(crate) async fn render_frame(
|
||||
size: (width, height),
|
||||
..
|
||||
} = settings;
|
||||
let export_format = match file_type {
|
||||
FileType::Svg => ExportFormat::Svg,
|
||||
FileType::Pdf => ExportFormat::Pdf { artboards_as_pages: false },
|
||||
_ => ExportFormat::Raster,
|
||||
};
|
||||
let export_format = if file_type == FileType::Svg { ExportFormat::Svg } else { ExportFormat::Raster };
|
||||
|
||||
// Create render config with export settings and the animation time
|
||||
let mut render_config = RenderConfig {
|
||||
@@ -194,10 +187,9 @@ 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::Pdf { data } => Ok(RenderedFrame::Pdf(data)),
|
||||
RenderOutputType::Texture(texture) => {
|
||||
// Convert GPU texture to CPU buffer
|
||||
let gpu_raster = Raster::<GPU>::new_gpu(texture);
|
||||
@@ -207,7 +199,7 @@ pub(crate) async fn render_frame(
|
||||
}
|
||||
RenderOutputType::Buffer { data, width, height } => Ok(RenderedFrame::Raster { data, width, height }),
|
||||
#[cfg(target_family = "wasm")]
|
||||
other => Err(format!("Unexpected render output type: {other:?}. Expected Texture or Buffer for raster export, Svg for SVG export, or Pdf for PDF export.").into()),
|
||||
other => Err(format!("Unexpected render output type: {other:?}. Expected Texture, Buffer for raster export or Svg for SVG export.").into()),
|
||||
},
|
||||
other => Err(format!("Expected RenderOutput, got: {other:?}").into()),
|
||||
}
|
||||
@@ -217,7 +209,6 @@ pub(crate) async fn render_frame(
|
||||
fn write_frame(path: &Path, settings: ExportSettings, frame: RenderedFrame) -> Result<(), Box<dyn Error>> {
|
||||
let contents = match frame {
|
||||
RenderedFrame::Svg(svg) => svg.into_bytes(),
|
||||
RenderedFrame::Pdf(pdf) => pdf,
|
||||
RenderedFrame::Raster { data, width, height } => encode_raster(settings.file_type, data, width, height, settings.transparent)?,
|
||||
};
|
||||
std::fs::write(path, contents)?;
|
||||
@@ -272,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());
|
||||
@@ -314,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,
|
||||
@@ -343,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());
|
||||
};
|
||||
|
||||
@@ -364,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,
|
||||
@@ -387,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)?;
|
||||
}
|
||||
@@ -399,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.clone().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()?;
|
||||
@@ -478,7 +480,6 @@ mod tests {
|
||||
assert_eq!(detect_file_type(Path::new("frame.tif")), Ok(FileType::Tiff));
|
||||
assert_eq!(detect_file_type(Path::new("frame.jpeg")), Ok(FileType::Jpg));
|
||||
assert_eq!(detect_file_type(Path::new("frame.webp")), Ok(FileType::Webp));
|
||||
assert_eq!(detect_file_type(Path::new("frame.pdf")), Ok(FileType::Pdf));
|
||||
assert!(detect_file_type(Path::new("frame.exr")).is_err());
|
||||
assert!(detect_file_type(Path::new("frame")).is_err());
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ enum Command {
|
||||
/// Path to the .graphite document
|
||||
document: PathBuf,
|
||||
|
||||
/// Output file path (extension determines format: .svg, .pdf, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif)
|
||||
/// Output file path (extension determines format: .svg, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif)
|
||||
#[clap(long, short = 'o')]
|
||||
output: PathBuf,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{Context, Generations, OwnedContextImpl};
|
||||
use dyn_any::{DynAny, StaticType, StaticTypeSized};
|
||||
use glam::DVec2;
|
||||
@@ -44,19 +43,6 @@ pub enum ExportFormat {
|
||||
#[default]
|
||||
Svg,
|
||||
Raster,
|
||||
Pdf {
|
||||
/// Puts each artboard on a page of its own, sized to it, rather than all of the export's area on one page.
|
||||
artboards_as_pages: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// What an exported document records about itself, where its format has a place for it.
|
||||
#[derive(Debug, Default, Clone, PartialEq, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ExportMetadata {
|
||||
pub title: String,
|
||||
/// The names of the artboards by the IDs of their layers, which a PDF's bookmarks of their pages take.
|
||||
pub artboard_names: Vec<(NodeId, String)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
|
||||
@@ -66,7 +52,7 @@ pub struct TimingInformation {
|
||||
pub animation_time: Duration,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, DynAny, CacheHash)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, DynAny, CacheHash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct RenderConfig {
|
||||
pub viewport: Footprint,
|
||||
@@ -78,9 +64,6 @@ pub struct RenderConfig {
|
||||
pub export_format: ExportFormat,
|
||||
pub for_export: bool,
|
||||
pub for_eyedropper: bool,
|
||||
/// What an exported document records about itself.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub metadata: Option<ExportMetadata>,
|
||||
}
|
||||
|
||||
impl RenderConfig {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -35,6 +35,8 @@ pub struct NodeFlags {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FieldMetadata {
|
||||
pub name: &'static str,
|
||||
/// The parameter's name in the node function, which graph text uses to set it.
|
||||
pub identifier: &'static str,
|
||||
pub description: &'static str,
|
||||
/// Whether the parameter is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
||||
pub internal: bool,
|
||||
@@ -60,6 +62,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 +230,146 @@ 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()));
|
||||
|
||||
/// The graph text of every `graph!` invocation, in registration order.
|
||||
pub static GRAPH_SOURCES: LazyLock<Mutex<Vec<GraphSource>>> = LazyLock::new(|| Mutex::new(Vec::new()));
|
||||
|
||||
/// The text of one `graph!` invocation and where it's written, for error messages.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphSource {
|
||||
/// The module the graph is defined in, which qualifies its name in `use` paths.
|
||||
pub module_path: &'static str,
|
||||
pub file: &'static str,
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
pub text: &'static str,
|
||||
}
|
||||
|
||||
/// Registers graph text as a built-in subgraph node, which the editor turns into a catalog definition.
|
||||
///
|
||||
/// Each invocation registers itself under a symbol named after its crate, line, and column, so two invocations at the
|
||||
/// same line and column in different files of one crate fail to link.
|
||||
#[macro_export]
|
||||
macro_rules! graph {
|
||||
($($source:tt)*) => {
|
||||
const _: () = {
|
||||
use $crate as gcore;
|
||||
use gcore::ctor::ctor;
|
||||
|
||||
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = gcore::ctor))]
|
||||
#[unsafe(export_name = concat!("__node_registry_graph_", env!("CARGO_CRATE_NAME"), "_", line!(), "_", column!()))]
|
||||
extern "C" fn register_graph() {
|
||||
gcore::registry::GRAPH_SOURCES.lock().unwrap().push(gcore::registry::GraphSource {
|
||||
module_path: module_path!(),
|
||||
file: file!(),
|
||||
line: line!(),
|
||||
column: column!(),
|
||||
text: stringify!($($source)*),
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/// A node defined as a subgraph in graph text, 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,
|
||||
/// The module path and function name that `use` paths in graph text name the graph by.
|
||||
pub path: &'static str,
|
||||
pub category: &'static str,
|
||||
pub icon: Option<&'static str>,
|
||||
pub description: &'static str,
|
||||
/// The declaration version from `fn name@N`, starting at 1.
|
||||
pub version: u32,
|
||||
/// Whether a new instance starts as a layer, from `#[layer]`.
|
||||
pub layer: bool,
|
||||
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
|
||||
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,
|
||||
/// The export's name in graph text, which chooses it as an output.
|
||||
pub identifier: &'static str,
|
||||
pub description: &'static str,
|
||||
pub source: GraphInputSource,
|
||||
}
|
||||
|
||||
/// A node inside a subgraph defined in graph text.
|
||||
#[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 position in grid units.
|
||||
pub position: (i32, i32),
|
||||
pub layer: bool,
|
||||
pub display_name: Option<&'static str>,
|
||||
pub hidden: bool,
|
||||
pub locked: bool,
|
||||
pub pinned: bool,
|
||||
}
|
||||
|
||||
/// What a node inside a subgraph is an instance of.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GraphNodeImplementation {
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
/// Another subgraph node, named by its identifier.
|
||||
Graph(&'static str),
|
||||
}
|
||||
|
||||
/// What feeds an input, or an export, of a subgraph defined in graph text.
|
||||
#[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 graph text, whose type is set by how it's written.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GraphValue {
|
||||
/// A number written without a fractional part.
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(|| {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "graph-text"
|
||||
description = "Parses the graph text format, which defines subgraph nodes in a Rust-like syntax"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
syn = { workspace = true }
|
||||
proc-macro2 = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
convert_case = { workspace = true }
|
||||
log = { workspace = true }
|
||||
@@ -0,0 +1,106 @@
|
||||
//! The default placement of a graph's nodes, relative to the nodes they feed.
|
||||
|
||||
/// How far apart, in grid units, a node is placed from the node it feeds.
|
||||
const COLUMN_WIDTH: i32 = 7;
|
||||
|
||||
/// A node's wires and its written placement, as the layout reads them.
|
||||
pub struct LayoutNode {
|
||||
/// The node feeding the primary input.
|
||||
pub primary: Option<usize>,
|
||||
/// The nodes feeding the other inputs, in the order they're written.
|
||||
pub secondaries: Vec<usize>,
|
||||
/// The absolute position from `.at(x, y)`, which replaces the default one.
|
||||
pub at: Option<(i32, i32)>,
|
||||
/// The nudge from `.offset(x, y)`, added to the default position.
|
||||
pub offset: (i32, i32),
|
||||
}
|
||||
|
||||
/// Places each node in the column left of the first node it feeds. A node feeding a primary input shares that node's row,
|
||||
/// and one feeding another input goes in a new row below everything placed so far. Each export's node starts a new row.
|
||||
pub fn layout(nodes: &[LayoutNode], roots: &[usize]) -> Vec<(i32, i32)> {
|
||||
let mut placement = Placement {
|
||||
nodes,
|
||||
positions: vec![None; nodes.len()],
|
||||
bottom: None,
|
||||
};
|
||||
|
||||
for &root in roots {
|
||||
let row = placement.next_row();
|
||||
placement.place(root, 0, row);
|
||||
}
|
||||
for node in 0..nodes.len() {
|
||||
let row = placement.next_row();
|
||||
placement.place(node, 0, row);
|
||||
}
|
||||
|
||||
placement.positions.into_iter().map(Option::unwrap_or_default).collect()
|
||||
}
|
||||
|
||||
struct Placement<'a> {
|
||||
nodes: &'a [LayoutNode],
|
||||
positions: Vec<Option<(i32, i32)>>,
|
||||
/// The lowest row used so far.
|
||||
bottom: Option<i32>,
|
||||
}
|
||||
|
||||
impl Placement<'_> {
|
||||
fn next_row(&self) -> i32 {
|
||||
self.bottom.map_or(0, |bottom| bottom + 1)
|
||||
}
|
||||
|
||||
fn place(&mut self, node: usize, x: i32, y: i32) {
|
||||
if self.positions[node].is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let LayoutNode { primary, secondaries, at, offset } = &self.nodes[node];
|
||||
let (x, y) = at.unwrap_or((x + offset.0, y + offset.1));
|
||||
self.positions[node] = Some((x, y));
|
||||
self.bottom = Some(self.bottom.map_or(y, |bottom| bottom.max(y)));
|
||||
|
||||
if let Some(primary) = primary {
|
||||
self.place(*primary, x - COLUMN_WIDTH, y);
|
||||
}
|
||||
for &secondary in secondaries {
|
||||
let row = self.next_row();
|
||||
self.place(secondary, x - COLUMN_WIDTH, row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn node(primary: Option<usize>, secondaries: Vec<usize>) -> LayoutNode {
|
||||
LayoutNode {
|
||||
primary,
|
||||
secondaries,
|
||||
at: None,
|
||||
offset: (0, 0),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chains_run_left_and_side_inputs_go_below() {
|
||||
// Merge: `base >> as_graphic() >> extend(new = content >> into_group())`
|
||||
let nodes = [node(None, vec![]), node(None, vec![]), node(Some(0), vec![1])];
|
||||
assert_eq!(layout(&nodes, &[2]), [(-7, 0), (-7, 1), (0, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn written_placement_moves_a_node_and_its_upstream() {
|
||||
let mut offset = node(None, vec![]);
|
||||
offset.offset = (0, 2);
|
||||
let mut at = node(Some(0), vec![]);
|
||||
at.at = Some((10, -4));
|
||||
|
||||
assert_eq!(layout(&[offset, at], &[1]), [(3, -2), (10, -4)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_export_and_unexported_node_starts_a_new_row() {
|
||||
let nodes = [node(None, vec![]), node(None, vec![]), node(None, vec![])];
|
||||
assert_eq!(layout(&nodes, &[0, 1]), [(0, 0), (0, 1), (0, 2)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Graph text, which defines a subgraph node in a Rust-like syntax that is parsed at runtime.
|
||||
//!
|
||||
//! Built-in graphs are written in `core_types::graph!` invocations, which register their text at startup.
|
||||
|
||||
mod layout;
|
||||
mod resolve;
|
||||
mod syntax;
|
||||
|
||||
use core_types::ProtoNodeIdentifier;
|
||||
use core_types::registry::{GRAPH_SOURCES, GraphMetadata, GraphSource, NODE_METADATA, NodeMetadata};
|
||||
use resolve::{Context, ResolveError};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::sync::LazyLock;
|
||||
pub use syntax::SYNTAX_VERSION;
|
||||
|
||||
/// Every registered graph that resolves, in registration order. Resolved on first access, which must happen after
|
||||
/// startup registration of the nodes and graphs completes. Each graph that fails is left out and its error logged.
|
||||
pub static GRAPHS: LazyLock<Vec<GraphMetadata>> = LazyLock::new(|| {
|
||||
let sources = GRAPH_SOURCES.lock().map(|sources| sources.clone()).unwrap_or_default();
|
||||
let Ok(proto_nodes) = NODE_METADATA.lock() else {
|
||||
log::error!("The node metadata is poisoned, so no graph resolves");
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let (graphs, errors) = resolve_sources(&sources, &proto_nodes);
|
||||
for error in errors {
|
||||
log::error!("{error}");
|
||||
}
|
||||
graphs
|
||||
});
|
||||
|
||||
/// The position of a registered graph's import, by the graph's identifier and the import's name.
|
||||
pub fn import_index(graph: &str, import: &str) -> Option<usize> {
|
||||
GRAPHS.iter().find(|metadata| metadata.identifier == graph)?.imports.iter().position(|field| field.identifier == import)
|
||||
}
|
||||
|
||||
/// An error in graph text, with the place it's written.
|
||||
#[derive(Debug)]
|
||||
pub struct GraphTextError {
|
||||
pub message: String,
|
||||
pub file: &'static str,
|
||||
pub line: u32,
|
||||
pub column: u32,
|
||||
/// The graph text from the error onward, which locates it within the text.
|
||||
pub excerpt: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for GraphTextError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "{}:{}:{}: {} (at `{}`)", self.file, self.line, self.column, self.message, self.excerpt)
|
||||
}
|
||||
}
|
||||
|
||||
impl GraphTextError {
|
||||
fn new(source: &GraphSource, error: syn::Error) -> Vec<Self> {
|
||||
error
|
||||
.into_iter()
|
||||
.map(|error| {
|
||||
let start = error.span().start();
|
||||
let excerpt = source
|
||||
.text
|
||||
.lines()
|
||||
.nth(start.line.saturating_sub(1))
|
||||
.map(|line| line.chars().skip(start.column).take(40).collect::<String>())
|
||||
.unwrap_or_default();
|
||||
|
||||
Self {
|
||||
message: error.to_string(),
|
||||
file: source.file,
|
||||
line: source.line,
|
||||
column: source.column,
|
||||
excerpt: excerpt.trim().to_string(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses and resolves graph sources. A graph using another one resolves once that one has, whatever the order.
|
||||
pub fn resolve_sources(sources: &[GraphSource], proto_nodes: &HashMap<ProtoNodeIdentifier, NodeMetadata>) -> (Vec<GraphMetadata>, Vec<GraphTextError>) {
|
||||
let mut errors = Vec::new();
|
||||
|
||||
let mut pending = Vec::new();
|
||||
for source in sources {
|
||||
match syn::parse_str::<syntax::Source>(source.text) {
|
||||
Ok(parsed) => pending.push((source, parsed, None)),
|
||||
Err(error) => errors.extend(GraphTextError::new(source, error)),
|
||||
}
|
||||
}
|
||||
|
||||
let mut graphs = Vec::new();
|
||||
loop {
|
||||
let pending_count = pending.len();
|
||||
|
||||
let mut still_pending = Vec::new();
|
||||
for (source, parsed, _) in pending {
|
||||
let context = Context { proto_nodes, graphs: &graphs };
|
||||
match resolve::resolve(&parsed, source.module_path, &context) {
|
||||
Ok(graph) => graphs.push(graph),
|
||||
Err(ResolveError::Invalid(error)) => errors.extend(GraphTextError::new(source, error)),
|
||||
Err(ResolveError::Unresolved(error)) => still_pending.push((source, parsed, Some(error))),
|
||||
}
|
||||
}
|
||||
pending = still_pending;
|
||||
|
||||
if pending.is_empty() || pending.len() == pending_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (source, _, error) in pending {
|
||||
if let Some(error) = error {
|
||||
errors.extend(GraphTextError::new(source, error));
|
||||
}
|
||||
}
|
||||
|
||||
(graphs, errors)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,749 @@
|
||||
//! Resolves parsed graph text against the registered nodes and graphs, producing the graph's `GraphMetadata`.
|
||||
|
||||
use crate::layout::{LayoutNode, layout};
|
||||
use crate::syntax::{Attribute, Expression, GraphItem, Import, Source, StateKind, Use, ValueKind, doc_comment};
|
||||
use convert_case::{Case, Casing};
|
||||
use core_types::registry::{
|
||||
FieldMetadata, GraphExportMetadata, GraphInputSource, GraphMetadata, GraphNodeImplementation, GraphNodeMetadata, GraphValue, NodeMetadata, RegistryValueSource, RegistryWidgetOverride,
|
||||
};
|
||||
use core_types::{ProtoNodeIdentifier, Type, concrete, generic};
|
||||
use proc_macro2::Span;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use syn::ext::IdentExt;
|
||||
use syn::parse::{ParseStream, Parser};
|
||||
use syn::{Error, Ident, LitBool, LitInt, LitStr, Token};
|
||||
|
||||
/// The registered nodes and the graphs resolved so far, which graph text can use.
|
||||
pub struct Context<'a> {
|
||||
pub proto_nodes: &'a HashMap<ProtoNodeIdentifier, NodeMetadata>,
|
||||
pub graphs: &'a [GraphMetadata],
|
||||
}
|
||||
|
||||
pub enum ResolveError {
|
||||
/// A used name matches nothing yet, which may be a graph that resolves later.
|
||||
Unresolved(Error),
|
||||
Invalid(Error),
|
||||
}
|
||||
|
||||
impl From<Error> for ResolveError {
|
||||
fn from(error: Error) -> Self {
|
||||
Self::Invalid(error)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a used name refers to.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Target<'a> {
|
||||
ProtoNode(&'a ProtoNodeIdentifier, &'a NodeMetadata),
|
||||
Graph(&'a GraphMetadata),
|
||||
}
|
||||
|
||||
impl<'a> Target<'a> {
|
||||
fn parameters(&self) -> &'a [FieldMetadata] {
|
||||
match self {
|
||||
Self::ProtoNode(_, metadata) => &metadata.fields,
|
||||
Self::Graph(graph) => &graph.imports,
|
||||
}
|
||||
}
|
||||
|
||||
fn implementation(&self) -> GraphNodeImplementation {
|
||||
match self {
|
||||
Self::ProtoNode(identifier, _) => GraphNodeImplementation::ProtoNode((*identifier).clone()),
|
||||
Self::Graph(graph) => GraphNodeImplementation::Graph(graph.identifier),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What feeds an input or export while the body is read.
|
||||
#[derive(Clone)]
|
||||
enum Feed {
|
||||
/// A node's output, chosen by name, or else its primary output.
|
||||
Node {
|
||||
node: usize,
|
||||
output: Option<usize>,
|
||||
},
|
||||
Import(usize),
|
||||
Value {
|
||||
value: GraphValue,
|
||||
exposed: Option<bool>,
|
||||
},
|
||||
Scope(String),
|
||||
NodePath,
|
||||
SourceId,
|
||||
}
|
||||
|
||||
struct Node<'a> {
|
||||
target: Target<'a>,
|
||||
name: Ident,
|
||||
inputs: Vec<(usize, Feed)>,
|
||||
states: Vec<StateKind>,
|
||||
}
|
||||
|
||||
struct Resolver<'a> {
|
||||
context: &'a Context<'a>,
|
||||
graph_path: String,
|
||||
uses: HashMap<String, &'a Use>,
|
||||
used: HashSet<String>,
|
||||
imports: &'a [Import],
|
||||
bindings: HashMap<String, Feed>,
|
||||
nodes: Vec<Node<'a>>,
|
||||
/// The parameters of the inner inputs each import feeds, in the order they're written.
|
||||
import_consumers: Vec<Vec<FieldMetadata>>,
|
||||
}
|
||||
|
||||
/// Resolves a parsed graph text, given the module path its graph is defined in.
|
||||
pub fn resolve(source: &Source, module_path: &str, context: &Context) -> Result<GraphMetadata, ResolveError> {
|
||||
let graph = &source.graph;
|
||||
let graph_path = format!("{module_path}::{}", graph.name);
|
||||
|
||||
let mut uses = HashMap::new();
|
||||
for entry in &source.uses {
|
||||
let local_name = entry.local_name();
|
||||
if uses.insert(local_name.to_string(), entry).is_some() {
|
||||
return Err(Error::new(local_name.span(), format!("`{local_name}` is used twice. Rename one with `as`")).into());
|
||||
}
|
||||
}
|
||||
|
||||
let mut resolver = Resolver {
|
||||
context,
|
||||
graph_path,
|
||||
uses,
|
||||
used: HashSet::new(),
|
||||
imports: &graph.imports,
|
||||
bindings: HashMap::new(),
|
||||
nodes: Vec::new(),
|
||||
import_consumers: vec![Vec::new(); graph.imports.len()],
|
||||
};
|
||||
|
||||
for binding in &graph.bindings {
|
||||
let name = binding.name.to_string();
|
||||
if resolver.bindings.contains_key(&name) || resolver.import_index(&binding.name).is_some() {
|
||||
return Err(Error::new(binding.name.span(), format!("`{name}` is already the name of a binding or import")).into());
|
||||
}
|
||||
let feed = resolver.read(&binding.value)?;
|
||||
resolver.bindings.insert(name, feed);
|
||||
}
|
||||
|
||||
let export_feeds = resolver.read_exports(&graph.result, graph.exports.len())?;
|
||||
|
||||
if let Some(unused) = source.uses.iter().find(|entry| !resolver.used.contains(&entry.local_name().to_string())) {
|
||||
return Err(Error::new(unused.local_name().span(), format!("`{}` is used but never called", unused.local_name())).into());
|
||||
}
|
||||
|
||||
resolver.build(graph, module_path, export_feeds)
|
||||
}
|
||||
|
||||
impl<'a> Resolver<'a> {
|
||||
fn import_index(&self, name: &Ident) -> Option<usize> {
|
||||
self.imports.iter().position(|import| import.name.as_ref() == Some(name))
|
||||
}
|
||||
|
||||
fn read(&mut self, expression: &'a Expression) -> Result<Feed, ResolveError> {
|
||||
match expression {
|
||||
Expression::Name(name) => {
|
||||
if let Some(feed) = self.bindings.get(&name.to_string()) {
|
||||
return Ok(feed.clone());
|
||||
}
|
||||
if let Some(index) = self.import_index(name) {
|
||||
return Ok(Feed::Import(index));
|
||||
}
|
||||
Err(Error::new(name.span(), format!("`{name}` isn't a binding or import. Call a node with parentheses, like `{name}()`")).into())
|
||||
}
|
||||
Expression::Value(value) => Ok(Feed::Value {
|
||||
value: match &value.kind {
|
||||
ValueKind::Integer(integer) => GraphValue::Integer(*integer),
|
||||
ValueKind::Number(number) => GraphValue::Number(*number),
|
||||
ValueKind::Bool(boolean) => GraphValue::Bool(*boolean),
|
||||
ValueKind::String(string) => GraphValue::String(string.clone()),
|
||||
ValueKind::Vec2(x, y) => GraphValue::vec2(*x, *y),
|
||||
},
|
||||
exposed: None,
|
||||
}),
|
||||
Expression::Call(call) => self.read_call(call),
|
||||
Expression::Feed { upstream, downstream, span } => {
|
||||
let upstream_feed = self.read(upstream)?;
|
||||
let Feed::Node { node, output } = self.read(downstream)? else {
|
||||
return Err(Error::new(downstream.span(), "The right side of `>>` is a node, like `fill()`, or a binding naming one").into());
|
||||
};
|
||||
|
||||
if let Feed::Node { node: upstream_node, .. } = upstream_feed
|
||||
&& self.is_fed_by(upstream_node, node)
|
||||
{
|
||||
return Err(Error::new(*span, "This wire makes a loop, since the node on the right already feeds the left side").into());
|
||||
}
|
||||
|
||||
let entry = &self.nodes[node];
|
||||
if entry.target.parameters().is_empty() {
|
||||
return Err(Error::new(entry.name.span(), format!("`{}` has no parameters, so `>>` has no input to feed", entry.name)).into());
|
||||
}
|
||||
if entry.inputs.iter().any(|(index, _)| *index == 0) {
|
||||
let primary = &entry.target.parameters()[0];
|
||||
let message = format!("The primary input of `{}`, `{}`, is already fed, so `>>` can't feed it too", entry.name, primary.identifier);
|
||||
return Err(Error::new(*span, message).into());
|
||||
}
|
||||
|
||||
self.connect(node, 0, upstream_feed);
|
||||
Ok(Feed::Node { node, output })
|
||||
}
|
||||
Expression::Output { node, output } => {
|
||||
let Feed::Node { node, output: None } = self.read(node)? else {
|
||||
return Err(Error::new(output.span(), "Only a node has outputs to choose from, and only one can be chosen").into());
|
||||
};
|
||||
let Target::Graph(graph) = self.nodes[node].target else {
|
||||
return Err(Error::new(output.span(), "Only a graph's outputs can be chosen by name").into());
|
||||
};
|
||||
let name = output.unraw().to_string();
|
||||
let Some(index) = graph.exports.iter().position(|export| export.identifier == name) else {
|
||||
return Err(Error::new(output.span(), format!("`{}` has no output named `{name}`", self.nodes[node].name)).into());
|
||||
};
|
||||
Ok(Feed::Node { node, output: Some(index) })
|
||||
}
|
||||
Expression::Tuple { span, .. } => Err(Error::new(*span, "A tuple only gives a graph's exports, as its final expression").into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_exports(&mut self, result: &'a Expression, export_count: usize) -> Result<Vec<Feed>, ResolveError> {
|
||||
let values: Vec<&Expression> = match result {
|
||||
Expression::Tuple { elements, .. } => elements.iter().collect(),
|
||||
single => vec![single],
|
||||
};
|
||||
if values.len() != export_count {
|
||||
return Err(Error::new(result.span(), format!("The graph names {export_count} exports, but ends with {} values", values.len())).into());
|
||||
}
|
||||
|
||||
values
|
||||
.into_iter()
|
||||
.map(|value| match self.read(value)? {
|
||||
Feed::Import(_) | Feed::Scope(_) => Err(Error::new(value.span(), "An export can't come straight from an import or scope yet, so pass it through a node first").into()),
|
||||
feed => Ok(feed),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `node` is `source` or feeds it through any chain of wires.
|
||||
fn is_fed_by(&self, node: usize, source: usize) -> bool {
|
||||
let mut visited = vec![false; self.nodes.len()];
|
||||
let mut stack = vec![node];
|
||||
|
||||
while let Some(current) = stack.pop() {
|
||||
if current == source {
|
||||
return true;
|
||||
}
|
||||
if std::mem::replace(&mut visited[current], true) {
|
||||
continue;
|
||||
}
|
||||
stack.extend(self.nodes[current].inputs.iter().filter_map(|(_, feed)| match feed {
|
||||
Feed::Node { node, .. } => Some(*node),
|
||||
_ => None,
|
||||
}));
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn connect(&mut self, node: usize, input: usize, feed: Feed) {
|
||||
if let Feed::Import(import) = feed {
|
||||
let parameter = self.nodes[node].target.parameters()[input].clone();
|
||||
self.import_consumers[import].push(parameter);
|
||||
}
|
||||
self.nodes[node].inputs.push((input, feed));
|
||||
}
|
||||
|
||||
fn read_call(&mut self, call: &'a crate::syntax::Call) -> Result<Feed, ResolveError> {
|
||||
let name = call.name.to_string();
|
||||
if let Some(feed) = self.read_value_helper(call)? {
|
||||
return Ok(feed);
|
||||
}
|
||||
|
||||
let target = self.target(&call.name)?;
|
||||
self.used.insert(name);
|
||||
|
||||
let mut inputs = Vec::new();
|
||||
for argument in &call.arguments {
|
||||
let parameter = match (&argument.parameter, &argument.value) {
|
||||
(Some(parameter), _) => parameter,
|
||||
(None, Expression::Name(shorthand)) => shorthand,
|
||||
(None, value) => return Err(Error::new(value.span(), "Name each argument, like `weight = 6`, or write a bare name for the shorthand").into()),
|
||||
};
|
||||
|
||||
let Some(index) = target.parameters().iter().position(|field| parameter == field.identifier) else {
|
||||
return Err(Error::new(parameter.span(), format!("`{}` has no parameter named `{parameter}`", call.name)).into());
|
||||
};
|
||||
if inputs.iter().any(|(existing, _)| *existing == index) {
|
||||
return Err(Error::new(parameter.span(), format!("`{parameter}` is already set in this call")).into());
|
||||
}
|
||||
|
||||
let mut feed = self.read(&argument.value)?;
|
||||
for attribute in &argument.attributes {
|
||||
if attribute.name != "exposed" {
|
||||
return Err(Error::new(attribute.name.span(), format!("Unknown argument attribute `#[{}]`", attribute.name)).into());
|
||||
}
|
||||
attribute.flag()?;
|
||||
let Feed::Value { exposed, .. } = &mut feed else {
|
||||
return Err(Error::new(attribute.name.span(), "Only a value can be exposed").into());
|
||||
};
|
||||
*exposed = Some(true);
|
||||
}
|
||||
|
||||
inputs.push((index, feed));
|
||||
}
|
||||
|
||||
self.nodes.push(Node {
|
||||
target,
|
||||
name: call.name.clone(),
|
||||
inputs: Vec::new(),
|
||||
states: call.states.iter().map(|state| state.kind.clone()).collect(),
|
||||
});
|
||||
let node = self.nodes.len() - 1;
|
||||
for (index, feed) in inputs {
|
||||
self.connect(node, index, feed);
|
||||
}
|
||||
|
||||
Ok(Feed::Node { node, output: None })
|
||||
}
|
||||
|
||||
/// Reads a call to `rgb`, `rgba`, `scope`, or `reflect`, which build values and input sources rather than nodes.
|
||||
fn read_value_helper(&self, call: &crate::syntax::Call) -> Result<Option<Feed>, ResolveError> {
|
||||
let name = call.name.to_string();
|
||||
if !matches!(name.as_str(), "rgb" | "rgba" | "scope" | "reflect") {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let [argument] = call.arguments.as_slice() else {
|
||||
return Err(Error::new(call.name.span(), format!("`{name}(...)` takes one argument")).into());
|
||||
};
|
||||
if let Some(state) = call.states.first() {
|
||||
return Err(Error::new(state.span, format!("`{name}(...)` is a value, so it has no node state")).into());
|
||||
}
|
||||
if argument.parameter.is_some() || !argument.attributes.is_empty() {
|
||||
return Err(Error::new(call.name.span(), format!("`{name}(...)` takes a plain argument")).into());
|
||||
}
|
||||
|
||||
let value = &argument.value;
|
||||
let feed = match (name.as_str(), value) {
|
||||
("rgb", Expression::Value(crate::syntax::Value { kind: ValueKind::Integer(hex), .. })) if (0..=0xFF_FFFF).contains(hex) => Feed::Value {
|
||||
value: GraphValue::rgb(*hex as u32),
|
||||
exposed: None,
|
||||
},
|
||||
("rgb", _) => return Err(Error::new(value.span(), "`rgb(...)` takes six hex digits, like `rgb(0xE85D75)`. Use `rgba(...)` to give an alpha too").into()),
|
||||
("rgba", Expression::Value(crate::syntax::Value { kind: ValueKind::Integer(hex), .. })) if (0..=0xFFFF_FFFF).contains(hex) => Feed::Value {
|
||||
value: GraphValue::rgba(*hex as u32),
|
||||
exposed: None,
|
||||
},
|
||||
("rgba", _) => return Err(Error::new(value.span(), "`rgba(...)` takes eight hex digits, like `rgba(0xE85D75FF)`").into()),
|
||||
("scope", Expression::Value(crate::syntax::Value { kind: ValueKind::String(key), .. })) => Feed::Scope(key.clone()),
|
||||
("scope", _) => return Err(Error::new(value.span(), "`scope(...)` takes the scope's key as a string").into()),
|
||||
(_, Expression::Name(reflected)) if reflected == "NodePath" => Feed::NodePath,
|
||||
(_, Expression::Name(reflected)) if reflected == "SourceId" => Feed::SourceId,
|
||||
_ => return Err(Error::new(value.span(), "Reflect `NodePath` or `SourceId`").into()),
|
||||
};
|
||||
Ok(Some(feed))
|
||||
}
|
||||
|
||||
/// The node or graph a called name refers to, through the `use` section.
|
||||
fn target(&self, name: &Ident) -> Result<Target<'a>, ResolveError> {
|
||||
let Some(entry) = self.uses.get(&name.to_string()) else {
|
||||
return Err(Error::new(name.span(), format!("`{name}` isn't used. Add it to the `use` section, like `use path::{name}@1;`")).into());
|
||||
};
|
||||
let module_path = entry.module_path();
|
||||
|
||||
let proto_identifier = ProtoNodeIdentifier::with_owned_string(format!("{module_path}::{}Node", entry.name.to_string().to_case(Case::Pascal)));
|
||||
if let Some((identifier, metadata)) = self.context.proto_nodes.get_key_value(&proto_identifier) {
|
||||
check_version(entry, metadata.version)?;
|
||||
return Ok(Target::ProtoNode(identifier, metadata));
|
||||
}
|
||||
|
||||
let graph_path = format!("{module_path}::{}", entry.name);
|
||||
if graph_path == self.graph_path {
|
||||
return Err(Error::new(name.span(), "A graph can't contain itself").into());
|
||||
}
|
||||
if let Some(graph) = self.context.graphs.iter().find(|graph| graph.path == graph_path) {
|
||||
check_version(entry, graph.version)?;
|
||||
return Ok(Target::Graph(graph));
|
||||
}
|
||||
|
||||
Err(ResolveError::Unresolved(Error::new(entry.name.span(), format!("No node or graph is named `{graph_path}`"))))
|
||||
}
|
||||
|
||||
fn build(self, graph: &GraphItem, module_path: &str, export_feeds: Vec<Feed>) -> Result<GraphMetadata, ResolveError> {
|
||||
let attributes = GraphAttributes::read(&graph.attributes)?;
|
||||
|
||||
let imports = graph
|
||||
.imports
|
||||
.iter()
|
||||
.zip(&self.import_consumers)
|
||||
.enumerate()
|
||||
.map(|(index, (import, consumers))| import_metadata(index, import, consumers))
|
||||
.collect::<syn::Result<Vec<_>>>()?;
|
||||
let import_types: Vec<Type> = imports.iter().map(import_wire_type).collect();
|
||||
|
||||
let source = |feed: &Feed| match feed {
|
||||
Feed::Node { node, output } => GraphInputSource::Node {
|
||||
node: *node,
|
||||
output: output.unwrap_or(0),
|
||||
},
|
||||
Feed::Import(index) => GraphInputSource::Import {
|
||||
index: *index,
|
||||
ty: import_types[*index].clone(),
|
||||
},
|
||||
Feed::Value { value, exposed } => GraphInputSource::Value {
|
||||
value: value.clone(),
|
||||
exposed: *exposed,
|
||||
},
|
||||
Feed::Scope(key) => GraphInputSource::Scope(leak(key.clone())),
|
||||
Feed::NodePath => GraphInputSource::NodePath,
|
||||
Feed::SourceId => GraphInputSource::SourceId,
|
||||
};
|
||||
|
||||
let layout_nodes: Vec<LayoutNode> = self
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|node| {
|
||||
let upstream = |input: &(usize, Feed)| match input.1 {
|
||||
Feed::Node { node, .. } => Some(node),
|
||||
_ => None,
|
||||
};
|
||||
LayoutNode {
|
||||
primary: node.inputs.iter().filter(|input| input.0 == 0).find_map(upstream),
|
||||
secondaries: node.inputs.iter().filter(|input| input.0 != 0).filter_map(upstream).collect(),
|
||||
at: node.states.iter().find_map(|state| match state {
|
||||
StateKind::At(x, y) => Some((*x, *y)),
|
||||
_ => None,
|
||||
}),
|
||||
offset: node
|
||||
.states
|
||||
.iter()
|
||||
.find_map(|state| match state {
|
||||
StateKind::Offset(x, y) => Some((*x, *y)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let roots: Vec<usize> = export_feeds
|
||||
.iter()
|
||||
.filter_map(|feed| match feed {
|
||||
Feed::Node { node, .. } => Some(*node),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let positions = layout(&layout_nodes, &roots);
|
||||
|
||||
let nodes = self
|
||||
.nodes
|
||||
.iter()
|
||||
.zip(positions)
|
||||
.map(|(node, position)| GraphNodeMetadata {
|
||||
implementation: node.target.implementation(),
|
||||
inputs: node.inputs.iter().map(|(index, feed)| (*index, source(feed))).collect(),
|
||||
position,
|
||||
layer: node.states.contains(&StateKind::Layer),
|
||||
display_name: node.states.iter().find_map(|state| match state {
|
||||
StateKind::Named(name) => Some(leak(name.clone())),
|
||||
_ => None,
|
||||
}),
|
||||
hidden: node.states.contains(&StateKind::Hidden),
|
||||
locked: node.states.contains(&StateKind::Locked),
|
||||
pinned: node.states.contains(&StateKind::Pinned),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let exports = graph
|
||||
.exports
|
||||
.iter()
|
||||
.zip(&export_feeds)
|
||||
.map(|(export, feed)| {
|
||||
let mut name = None;
|
||||
for attribute in &export.attributes {
|
||||
match attribute.name.to_string().as_str() {
|
||||
"doc" => {}
|
||||
"name" => set_once(&mut name, attribute, attribute.string()?)?,
|
||||
other => return Err(Error::new(attribute.name.span(), format!("Unknown export attribute `#[{other}]`"))),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(GraphExportMetadata {
|
||||
name: leak(name.unwrap_or_else(|| derived_display_name(&export.name))),
|
||||
identifier: leak(export.name.unraw().to_string()),
|
||||
description: leak(doc_comment(&export.attributes)),
|
||||
source: source(feed),
|
||||
})
|
||||
})
|
||||
.collect::<syn::Result<Vec<_>>>()?;
|
||||
|
||||
let identifier = attributes.display_name.unwrap_or_else(|| graph.name.unraw().to_string().to_case(Case::Pascal).to_case(Case::Title));
|
||||
|
||||
Ok(GraphMetadata {
|
||||
identifier: leak(identifier),
|
||||
path: leak(format!("{module_path}::{}", graph.name)),
|
||||
category: leak(attributes.category),
|
||||
icon: attributes.icon.map(leak),
|
||||
description: leak(doc_comment(&graph.attributes)),
|
||||
version: graph.version,
|
||||
layer: attributes.layer,
|
||||
imports,
|
||||
exports,
|
||||
nodes,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn check_version(entry: &Use, version: u32) -> syn::Result<()> {
|
||||
if entry.version == version {
|
||||
return Ok(());
|
||||
}
|
||||
Err(Error::new(entry.name.span(), format!("`{}` is at version {version}, not {}", entry.name, entry.version)))
|
||||
}
|
||||
|
||||
/// Strings in the registry's metadata live for the whole program, which holds for graphs resolved once at startup.
|
||||
fn leak(string: String) -> &'static str {
|
||||
Box::leak(string.into_boxed_str())
|
||||
}
|
||||
|
||||
/// The display name an identifier derives, in Title Case.
|
||||
fn derived_display_name(ident: &Ident) -> String {
|
||||
ident.unraw().to_string().to_case(Case::Title).trim().to_string()
|
||||
}
|
||||
|
||||
fn set_once<T>(slot: &mut Option<T>, attribute: &Attribute, value: T) -> syn::Result<()> {
|
||||
if slot.is_some() {
|
||||
return Err(Error::new(attribute.name.span(), format!("Multiple `{}` attributes are not allowed", attribute.name)));
|
||||
}
|
||||
*slot = Some(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct GraphAttributes {
|
||||
category: String,
|
||||
icon: Option<String>,
|
||||
display_name: Option<String>,
|
||||
layer: bool,
|
||||
}
|
||||
|
||||
impl GraphAttributes {
|
||||
fn read(attributes: &[Attribute]) -> syn::Result<Self> {
|
||||
let (mut category, mut icon, mut display_name, mut layer) = (None, None, None, None);
|
||||
|
||||
for attribute in attributes {
|
||||
match attribute.name.to_string().as_str() {
|
||||
"doc" => {}
|
||||
"category" => set_once(&mut category, attribute, attribute.string()?)?,
|
||||
"icon" => set_once(&mut icon, attribute, attribute.string()?)?,
|
||||
"name" => set_once(&mut display_name, attribute, attribute.string()?)?,
|
||||
"layer" => {
|
||||
attribute.flag()?;
|
||||
set_once(&mut layer, attribute, true)?;
|
||||
}
|
||||
other => {
|
||||
return Err(Error::new(
|
||||
attribute.name.span(),
|
||||
format!("Unknown graph attribute `#[{other}]`. Expected `category(\"…\")`, `icon(\"…\")`, `name(\"…\")`, or `layer`"),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(category) = category else {
|
||||
return Err(Error::new(Span::call_site(), "A graph needs a category, like `#[category(\"Vector: Deform\")]`"));
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
category,
|
||||
icon,
|
||||
display_name,
|
||||
layer: layer.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A parameter description with nothing set, which an import starts from when it feeds no input.
|
||||
pub(crate) fn blank_field() -> FieldMetadata {
|
||||
FieldMetadata {
|
||||
name: "",
|
||||
identifier: "",
|
||||
description: "",
|
||||
internal: false,
|
||||
exposed: false,
|
||||
widget_override: RegistryWidgetOverride::None,
|
||||
value_source: RegistryValueSource::None,
|
||||
default_colors: None,
|
||||
default_type: None,
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// An import's parameter description, inherited from an inner input it feeds and overridden by its own attributes.
|
||||
/// That input is the one whose parameter has the import's name, or else the first one fed.
|
||||
fn import_metadata(index: usize, import: &Import, consumers: &[FieldMetadata]) -> syn::Result<FieldMetadata> {
|
||||
let Some(name) = &import.name else {
|
||||
if let Some(attribute) = import.attributes.first() {
|
||||
return Err(Error::new(attribute.name.span(), "An unused primary import takes no attributes"));
|
||||
}
|
||||
return Ok(FieldMetadata {
|
||||
default_type: Some(concrete!(())),
|
||||
..blank_field()
|
||||
});
|
||||
};
|
||||
|
||||
let identifier = name.unraw().to_string();
|
||||
let inherited = consumers.iter().find(|consumer| consumer.identifier == identifier).or(consumers.first());
|
||||
let mut field = FieldMetadata {
|
||||
identifier: leak(identifier.clone()),
|
||||
exposed: false,
|
||||
internal: index > 0 && identifier.starts_with('_'),
|
||||
constant: false,
|
||||
..inherited.cloned().unwrap_or_else(blank_field)
|
||||
};
|
||||
|
||||
let mut display_name = None;
|
||||
let mut seen = HashSet::new();
|
||||
for attribute in &import.attributes {
|
||||
let attribute_name = attribute.name.to_string();
|
||||
if attribute_name != "doc" && !seen.insert(attribute_name.clone()) {
|
||||
return Err(Error::new(attribute.name.span(), format!("Multiple `{attribute_name}` attributes are not allowed")));
|
||||
}
|
||||
apply_import_attribute(&mut field, &mut display_name, attribute)?;
|
||||
}
|
||||
|
||||
field.name = leak(display_name.unwrap_or_else(|| derived_display_name(name)));
|
||||
let description = doc_comment(&import.attributes);
|
||||
if !description.is_empty() {
|
||||
field.description = leak(description);
|
||||
}
|
||||
|
||||
Ok(field)
|
||||
}
|
||||
|
||||
fn apply_import_attribute(field: &mut FieldMetadata, display_name: &mut Option<String>, attribute: &Attribute) -> syn::Result<()> {
|
||||
let arguments = || attribute.list();
|
||||
|
||||
match attribute.name.to_string().as_str() {
|
||||
"doc" => {}
|
||||
"name" => *display_name = Some(attribute.string()?),
|
||||
"expose" => {
|
||||
attribute.flag()?;
|
||||
field.exposed = true;
|
||||
}
|
||||
"default" => {
|
||||
let tokens = arguments()?;
|
||||
field.default_type = default_type(&tokens, field.default_type.take());
|
||||
field.value_source = RegistryValueSource::Default(leak(tokens.to_string()));
|
||||
field.default_colors = None;
|
||||
}
|
||||
"widget" => {
|
||||
field.widget_override = (|input: ParseStream| {
|
||||
let kind: Ident = input.parse()?;
|
||||
let text = || -> syn::Result<&'static str> {
|
||||
input.parse::<Token![=]>()?;
|
||||
Ok(leak(input.parse::<LitStr>()?.value()))
|
||||
};
|
||||
match kind.to_string().as_str() {
|
||||
"Hidden" => Ok(RegistryWidgetOverride::Hidden),
|
||||
"String" => Ok(RegistryWidgetOverride::String(text()?)),
|
||||
"Custom" => Ok(RegistryWidgetOverride::Custom(text()?)),
|
||||
_ => Err(Error::new(kind.span(), "A widget is `Hidden`, `String = \"…\"`, or `Custom = \"…\"`")),
|
||||
}
|
||||
})
|
||||
.parse2(arguments()?)?;
|
||||
}
|
||||
"unit" => field.unit = Some(leak(attribute.string()?)),
|
||||
"hard" => (field.number_hard_min, field.number_hard_max) = parse_bounds.parse2(arguments()?)?,
|
||||
"soft" => (field.number_soft_min, field.number_soft_max) = parse_bounds.parse2(arguments()?)?,
|
||||
"range" => {
|
||||
attribute.flag()?;
|
||||
field.number_mode_range = true;
|
||||
}
|
||||
"step" => field.number_step = Some(parse_number.parse2(arguments()?)?),
|
||||
"display_decimal_places" => field.number_display_decimal_places = Some(syn::parse2::<LitInt>(arguments()?)?.base10_parse()?),
|
||||
"multiline" => {
|
||||
attribute.flag()?;
|
||||
field.multiline = true;
|
||||
}
|
||||
"progression" => {
|
||||
attribute.flag()?;
|
||||
field.progression = true;
|
||||
}
|
||||
"integer" => {
|
||||
attribute.flag()?;
|
||||
field.integer = true;
|
||||
}
|
||||
"labels" => {
|
||||
field.labels = Some(
|
||||
(|input: ParseStream| {
|
||||
let x: LitStr = input.parse()?;
|
||||
input.parse::<Token![,]>()?;
|
||||
let y: LitStr = input.parse()?;
|
||||
Ok((leak(x.value()), leak(y.value())))
|
||||
})
|
||||
.parse2(arguments()?)?,
|
||||
);
|
||||
}
|
||||
"blank_assist" => field.blank_assist = syn::parse2::<LitBool>(arguments()?)?.value,
|
||||
other => return Err(Error::new(attribute.name.span(), format!("Unknown import attribute `#[{other}]`"))),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The type a `#[default(...)]` is parsed as: a literal's own type, or else the bare element of the inherited type.
|
||||
fn default_type(tokens: &proc_macro2::TokenStream, inherited: Option<Type>) -> Option<Type> {
|
||||
if let Ok(literal) = syn::parse2::<crate::syntax::Value>(tokens.clone()) {
|
||||
return Some(match literal.kind {
|
||||
ValueKind::Integer(_) => concrete!(i64),
|
||||
ValueKind::Number(_) => concrete!(f64),
|
||||
ValueKind::Bool(_) => concrete!(bool),
|
||||
ValueKind::String(_) => concrete!(String),
|
||||
ValueKind::Vec2(..) => concrete!(glam::DVec2),
|
||||
});
|
||||
}
|
||||
|
||||
match inherited {
|
||||
Some(Type::Item(element)) => Some(*element),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The type an import's wire records, ranked as an `Item` when its default is a bare element.
|
||||
fn import_wire_type(field: &FieldMetadata) -> Type {
|
||||
match &field.default_type {
|
||||
Some(ty @ (Type::Item(_) | Type::List(_) | Type::Fn(..) | Type::Generic(_))) => ty.clone(),
|
||||
Some(unit) if *unit == concrete!(()) => unit.clone(),
|
||||
Some(element) => Type::Item(Box::new(element.clone())),
|
||||
None => generic!(T),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_number(input: ParseStream) -> syn::Result<f64> {
|
||||
let negative = input.peek(Token![-]);
|
||||
if negative {
|
||||
input.parse::<Token![-]>()?;
|
||||
}
|
||||
let magnitude: f64 = match input.parse::<syn::Lit>()? {
|
||||
syn::Lit::Int(integer) => integer.base10_parse()?,
|
||||
syn::Lit::Float(float) => float.base10_parse()?,
|
||||
other => return Err(Error::new(other.span(), "Expected a number")),
|
||||
};
|
||||
Ok(if negative { -magnitude } else { magnitude })
|
||||
}
|
||||
|
||||
/// Reads `a..b`, where either end may be left out.
|
||||
fn parse_bounds(input: ParseStream) -> syn::Result<(Option<f64>, Option<f64>)> {
|
||||
let start = if input.peek(Token![..]) { None } else { Some(parse_number(input)?) };
|
||||
input.parse::<Token![..]>()?;
|
||||
let end = if input.is_empty() { None } else { Some(parse_number(input)?) };
|
||||
Ok((start, end))
|
||||
}
|
||||
@@ -0,0 +1,780 @@
|
||||
//! The grammar of graph text, parsed with syn from the tokens of a `graph!` invocation or a clipboard string.
|
||||
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use syn::ext::IdentExt;
|
||||
use syn::parse::{Parse, ParseStream};
|
||||
use syn::punctuated::Punctuated;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{Error, Ident, Lit, LitInt, LitStr, Token, braced, bracketed, parenthesized};
|
||||
|
||||
/// The syntax version this parser reads, from the `#![syntax(N)]` header.
|
||||
pub const SYNTAX_VERSION: u32 = 1;
|
||||
|
||||
/// A whole graph text: its header, its `use` section, and the graph it defines.
|
||||
pub struct Source {
|
||||
pub uses: Vec<Use>,
|
||||
pub graph: GraphItem,
|
||||
}
|
||||
|
||||
/// One node or graph named by the `use` section, like `math_nodes::add@1`.
|
||||
pub struct Use {
|
||||
pub module: Vec<Ident>,
|
||||
pub name: Ident,
|
||||
pub version: u32,
|
||||
pub alias: Option<Ident>,
|
||||
}
|
||||
|
||||
impl Use {
|
||||
/// The name the body calls it by.
|
||||
pub fn local_name(&self) -> &Ident {
|
||||
self.alias.as_ref().unwrap_or(&self.name)
|
||||
}
|
||||
|
||||
pub fn module_path(&self) -> String {
|
||||
self.module.iter().map(Ident::to_string).collect::<Vec<_>>().join("::")
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute item like `category("Graphic")`, `layer`, or `doc = "…"`. One `#[...]` can hold several, separated by commas.
|
||||
pub struct Attribute {
|
||||
pub name: Ident,
|
||||
pub arguments: AttributeArguments,
|
||||
}
|
||||
|
||||
pub enum AttributeArguments {
|
||||
None,
|
||||
List(TokenStream),
|
||||
Value(Lit),
|
||||
}
|
||||
|
||||
impl Attribute {
|
||||
/// The parenthesized arguments, or an error naming the attribute if it has none.
|
||||
pub fn list(&self) -> syn::Result<TokenStream> {
|
||||
match &self.arguments {
|
||||
AttributeArguments::List(tokens) => Ok(tokens.clone()),
|
||||
_ => Err(Error::new(self.name.span(), format!("`{}` takes arguments in parentheses", self.name))),
|
||||
}
|
||||
}
|
||||
|
||||
/// An error unless the attribute is written without arguments.
|
||||
pub fn flag(&self) -> syn::Result<()> {
|
||||
match &self.arguments {
|
||||
AttributeArguments::None => Ok(()),
|
||||
_ => Err(Error::new(self.name.span(), format!("`{}` takes no arguments", self.name))),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn string(&self) -> syn::Result<String> {
|
||||
syn::parse2::<LitStr>(self.list()?).map(|literal| literal.value())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GraphItem {
|
||||
pub attributes: Vec<Attribute>,
|
||||
pub name: Ident,
|
||||
pub version: u32,
|
||||
pub imports: Vec<Import>,
|
||||
pub exports: Vec<Export>,
|
||||
pub bindings: Vec<Binding>,
|
||||
/// The final expression, which gives one value per export.
|
||||
pub result: Expression,
|
||||
}
|
||||
|
||||
pub struct Import {
|
||||
pub attributes: Vec<Attribute>,
|
||||
/// The import's name, or `None` for an unused primary import written `_`.
|
||||
pub name: Option<Ident>,
|
||||
}
|
||||
|
||||
pub struct Export {
|
||||
pub attributes: Vec<Attribute>,
|
||||
pub name: Ident,
|
||||
}
|
||||
|
||||
pub struct Binding {
|
||||
pub name: Ident,
|
||||
pub value: Expression,
|
||||
}
|
||||
|
||||
pub enum Expression {
|
||||
Name(Ident),
|
||||
Value(Value),
|
||||
Call(Call),
|
||||
/// `upstream >> downstream`, which feeds the upstream into the downstream node's primary input.
|
||||
Feed {
|
||||
upstream: Box<Expression>,
|
||||
downstream: Box<Expression>,
|
||||
span: Span,
|
||||
},
|
||||
/// A node's output chosen by name, like `.captures`.
|
||||
Output {
|
||||
node: Box<Expression>,
|
||||
output: Ident,
|
||||
},
|
||||
Tuple {
|
||||
elements: Vec<Expression>,
|
||||
span: Span,
|
||||
},
|
||||
}
|
||||
|
||||
impl Expression {
|
||||
pub fn span(&self) -> Span {
|
||||
match self {
|
||||
Self::Name(name) => name.span(),
|
||||
Self::Value(value) => value.span,
|
||||
Self::Call(call) => call.name.span(),
|
||||
Self::Feed { span, .. } | Self::Tuple { span, .. } => *span,
|
||||
Self::Output { output, .. } => output.span(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Value {
|
||||
pub kind: ValueKind,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
pub enum ValueKind {
|
||||
Integer(i64),
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
Vec2(f64, f64),
|
||||
}
|
||||
|
||||
pub struct Call {
|
||||
pub name: Ident,
|
||||
pub arguments: Vec<Argument>,
|
||||
pub states: Vec<State>,
|
||||
}
|
||||
|
||||
pub struct Argument {
|
||||
pub attributes: Vec<Attribute>,
|
||||
/// The parameter set by `parameter = value`, or `None` for a positional argument, which for a node is the shorthand `name`.
|
||||
pub parameter: Option<Ident>,
|
||||
pub value: Expression,
|
||||
}
|
||||
|
||||
/// A node state method after a call, like `.offset(0, 2)`.
|
||||
pub struct State {
|
||||
pub kind: StateKind,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub enum StateKind {
|
||||
At(i32, i32),
|
||||
Offset(i32, i32),
|
||||
Named(String),
|
||||
Hidden,
|
||||
Locked,
|
||||
Pinned,
|
||||
Layer,
|
||||
}
|
||||
|
||||
impl Parse for Source {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
parse_header(input)?;
|
||||
|
||||
let mut uses = Vec::new();
|
||||
while input.peek(Token![use]) {
|
||||
uses.extend(parse_use(input)?);
|
||||
}
|
||||
|
||||
let graph = input.parse()?;
|
||||
if !input.is_empty() {
|
||||
return Err(input.error("Graph text defines one graph"));
|
||||
}
|
||||
|
||||
Ok(Self { uses, graph })
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `#![syntax(N)]`, which every graph text starts with.
|
||||
fn parse_header(input: ParseStream) -> syn::Result<()> {
|
||||
if !(input.peek(Token![#]) && input.peek2(Token![!])) {
|
||||
return Err(input.error(format!("Graph text starts with its syntax version, like `#![syntax({SYNTAX_VERSION})]`")));
|
||||
}
|
||||
input.parse::<Token![#]>()?;
|
||||
input.parse::<Token![!]>()?;
|
||||
|
||||
let content;
|
||||
bracketed!(content in input);
|
||||
let name: Ident = content.parse()?;
|
||||
if name != "syntax" {
|
||||
return Err(Error::new(name.span(), "The header is `#![syntax(N)]`"));
|
||||
}
|
||||
|
||||
let arguments;
|
||||
parenthesized!(arguments in content);
|
||||
let literal: LitInt = arguments.parse()?;
|
||||
let version: u32 = literal.base10_parse()?;
|
||||
if version != SYNTAX_VERSION {
|
||||
return Err(Error::new(literal.span(), format!("Syntax version {version} isn't supported, only {SYNTAX_VERSION} is")));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads `use path::name@N;` or `use path::{a@N, b@N as c};`.
|
||||
fn parse_use(input: ParseStream) -> syn::Result<Vec<Use>> {
|
||||
let use_token: Token![use] = input.parse()?;
|
||||
|
||||
let mut module = Vec::new();
|
||||
let entries = loop {
|
||||
if input.peek(syn::token::Brace) {
|
||||
let content;
|
||||
braced!(content in input);
|
||||
break Punctuated::<UseEntry, Token![,]>::parse_terminated(&content)?.into_iter().collect::<Vec<_>>();
|
||||
}
|
||||
|
||||
let segment: Ident = input.parse()?;
|
||||
if input.peek(Token![::]) {
|
||||
input.parse::<Token![::]>()?;
|
||||
module.push(segment);
|
||||
} else {
|
||||
break vec![UseEntry::parse_after_name(segment, input)?];
|
||||
}
|
||||
};
|
||||
input.parse::<Token![;]>()?;
|
||||
|
||||
if module.is_empty() {
|
||||
return Err(Error::new(use_token.span, "Name a node by its full path, like `use math_nodes::add@1;`"));
|
||||
}
|
||||
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.map(|entry| Use {
|
||||
module: module.clone(),
|
||||
name: entry.name,
|
||||
version: entry.version,
|
||||
alias: entry.alias,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
struct UseEntry {
|
||||
name: Ident,
|
||||
version: u32,
|
||||
alias: Option<Ident>,
|
||||
}
|
||||
|
||||
impl UseEntry {
|
||||
fn parse_after_name(name: Ident, input: ParseStream) -> syn::Result<Self> {
|
||||
let version = parse_version(input)?;
|
||||
let alias = if input.peek(Token![as]) {
|
||||
input.parse::<Token![as]>()?;
|
||||
Some(input.parse()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Self { name, version, alias })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for UseEntry {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let name = input.parse()?;
|
||||
Self::parse_after_name(name, input)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `@N`, the version a node or graph is declared or used at.
|
||||
fn parse_version(input: ParseStream) -> syn::Result<u32> {
|
||||
if !input.peek(Token![@]) {
|
||||
return Err(input.error("Give the version, like `@1`"));
|
||||
}
|
||||
input.parse::<Token![@]>()?;
|
||||
|
||||
let literal: LitInt = input.parse()?;
|
||||
if !literal.suffix().is_empty() {
|
||||
return Err(Error::new(literal.span(), "Write the version without a type suffix"));
|
||||
}
|
||||
let version: u32 = literal.base10_parse()?;
|
||||
if version == 0 {
|
||||
return Err(Error::new(literal.span(), "Versions start at 1"));
|
||||
}
|
||||
Ok(version)
|
||||
}
|
||||
|
||||
/// Reads any number of `#[...]` groups, each holding comma-separated attribute items.
|
||||
fn parse_attributes(input: ParseStream) -> syn::Result<Vec<Attribute>> {
|
||||
let mut attributes = Vec::new();
|
||||
|
||||
while input.peek(Token![#]) && !input.peek2(Token![!]) {
|
||||
input.parse::<Token![#]>()?;
|
||||
let content;
|
||||
bracketed!(content in input);
|
||||
|
||||
while !content.is_empty() {
|
||||
let name = content.call(Ident::parse_any)?;
|
||||
let arguments = if content.peek(syn::token::Paren) {
|
||||
let arguments;
|
||||
parenthesized!(arguments in content);
|
||||
AttributeArguments::List(arguments.parse()?)
|
||||
} else if content.peek(Token![=]) {
|
||||
content.parse::<Token![=]>()?;
|
||||
AttributeArguments::Value(content.parse()?)
|
||||
} else {
|
||||
AttributeArguments::None
|
||||
};
|
||||
attributes.push(Attribute { name, arguments });
|
||||
|
||||
if content.is_empty() {
|
||||
break;
|
||||
}
|
||||
content.parse::<Token![,]>()?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(attributes)
|
||||
}
|
||||
|
||||
/// The `///` lines among the attributes, each trimmed and joined by line breaks.
|
||||
pub fn doc_comment(attributes: &[Attribute]) -> String {
|
||||
attributes
|
||||
.iter()
|
||||
.filter(|attribute| attribute.name == "doc")
|
||||
.filter_map(|attribute| match &attribute.arguments {
|
||||
AttributeArguments::Value(Lit::Str(text)) => Some(text.value().trim().to_string()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
.trim()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
impl Parse for GraphItem {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let attributes = parse_attributes(input)?;
|
||||
input.parse::<Token![fn]>()?;
|
||||
let name: Ident = input.parse()?;
|
||||
let version = parse_version(input)?;
|
||||
|
||||
let parameters;
|
||||
parenthesized!(parameters in input);
|
||||
let imports = Punctuated::<Import, Token![,]>::parse_terminated(¶meters)?.into_iter().collect();
|
||||
|
||||
input.parse::<Token![->]>()?;
|
||||
let exports: Vec<Export> = if input.peek(syn::token::Paren) {
|
||||
let content;
|
||||
parenthesized!(content in input);
|
||||
Punctuated::<Export, Token![,]>::parse_terminated(&content)?.into_iter().collect()
|
||||
} else {
|
||||
vec![input.parse()?]
|
||||
};
|
||||
if exports.is_empty() {
|
||||
return Err(Error::new(name.span(), "Name at least one export, like `-> (out)`"));
|
||||
}
|
||||
|
||||
let body;
|
||||
braced!(body in input);
|
||||
let mut bindings = Vec::new();
|
||||
while body.peek(Token![let]) {
|
||||
bindings.push(body.parse()?);
|
||||
}
|
||||
|
||||
if body.is_empty() {
|
||||
return Err(Error::new(name.span(), "A graph ends its body with one value per export"));
|
||||
}
|
||||
let result = parse_expression(&body)?;
|
||||
if body.peek(Token![;]) {
|
||||
return Err(body.error("The graph ends with its exports, written without a semicolon"));
|
||||
}
|
||||
if !body.is_empty() {
|
||||
return Err(body.error("Each statement in a graph is a `let` binding, followed by the exports it ends with"));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
attributes,
|
||||
name,
|
||||
version,
|
||||
imports,
|
||||
exports,
|
||||
bindings,
|
||||
result,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Import {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let attributes = parse_attributes(input)?;
|
||||
let name = if input.peek(Token![_]) {
|
||||
input.parse::<Token![_]>()?;
|
||||
None
|
||||
} else {
|
||||
Some(input.parse()?)
|
||||
};
|
||||
if input.peek(Token![:]) {
|
||||
return Err(input.error("Imports take no type, since it's inferred from the inputs they feed"));
|
||||
}
|
||||
|
||||
Ok(Self { attributes, name })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Export {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let attributes = parse_attributes(input)?;
|
||||
let name = input.call(Ident::parse_any)?;
|
||||
Ok(Self { attributes, name })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Binding {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
input.parse::<Token![let]>()?;
|
||||
let name = input.parse()?;
|
||||
input.parse::<Token![=]>()?;
|
||||
let value = parse_expression(input)?;
|
||||
input.parse::<Token![;]>()?;
|
||||
Ok(Self { name, value })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Expression {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
parse_expression(input)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a chain of `>>`, which binds loosest and groups from the left.
|
||||
fn parse_expression(input: ParseStream) -> syn::Result<Expression> {
|
||||
let mut expression = parse_postfix(input)?;
|
||||
|
||||
while input.peek(Token![>>]) {
|
||||
let token: Token![>>] = input.parse()?;
|
||||
let downstream = parse_postfix(input)?;
|
||||
expression = Expression::Feed {
|
||||
upstream: Box::new(expression),
|
||||
downstream: Box::new(downstream),
|
||||
span: token.span(),
|
||||
};
|
||||
}
|
||||
|
||||
Ok(expression)
|
||||
}
|
||||
|
||||
/// Reads a primary expression followed by node state methods and output choices.
|
||||
fn parse_postfix(input: ParseStream) -> syn::Result<Expression> {
|
||||
let mut expression = parse_primary(input)?;
|
||||
|
||||
while input.peek(Token![.]) && !input.peek(Token![..]) {
|
||||
input.parse::<Token![.]>()?;
|
||||
let name = input.call(Ident::parse_any)?;
|
||||
|
||||
if !input.peek(syn::token::Paren) {
|
||||
if matches!(expression, Expression::Output { .. }) {
|
||||
return Err(Error::new(name.span(), "An output is already chosen here"));
|
||||
}
|
||||
expression = Expression::Output {
|
||||
node: Box::new(expression),
|
||||
output: name,
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
let arguments;
|
||||
parenthesized!(arguments in input);
|
||||
let call = match &mut expression {
|
||||
Expression::Call(call) => call,
|
||||
Expression::Output { .. } => {
|
||||
return Err(Error::new(name.span(), "Node state goes before the output it chooses, like `regex_find().at(0, 0).captures`"));
|
||||
}
|
||||
_ => return Err(Error::new(name.span(), "Node state goes directly after the call it modifies, not on a binding")),
|
||||
};
|
||||
|
||||
let state = parse_state(&name, &arguments)?;
|
||||
if call.states.iter().any(|existing| std::mem::discriminant(&existing.kind) == std::mem::discriminant(&state.kind)) {
|
||||
return Err(Error::new(name.span(), format!("`.{name}()` is already set on this node")));
|
||||
}
|
||||
call.states.push(state);
|
||||
}
|
||||
|
||||
Ok(expression)
|
||||
}
|
||||
|
||||
fn parse_state(name: &Ident, arguments: ParseStream) -> syn::Result<State> {
|
||||
let method = name.to_string();
|
||||
let no_arguments = || match arguments.is_empty() {
|
||||
true => Ok(()),
|
||||
false => Err(arguments.error(format!("`.{method}()` takes no arguments"))),
|
||||
};
|
||||
let coordinates = || -> syn::Result<(i32, i32)> {
|
||||
let x = parse_grid_coordinate(arguments)?;
|
||||
arguments.parse::<Token![,]>()?;
|
||||
let y = parse_grid_coordinate(arguments)?;
|
||||
if !arguments.is_empty() {
|
||||
return Err(arguments.error("Give two coordinates in grid units"));
|
||||
}
|
||||
Ok((x, y))
|
||||
};
|
||||
|
||||
let kind = match method.as_str() {
|
||||
"at" => {
|
||||
let (x, y) = coordinates()?;
|
||||
StateKind::At(x, y)
|
||||
}
|
||||
"offset" => {
|
||||
let (x, y) = coordinates()?;
|
||||
StateKind::Offset(x, y)
|
||||
}
|
||||
"named" => {
|
||||
let display_name: LitStr = arguments.parse()?;
|
||||
StateKind::Named(display_name.value())
|
||||
}
|
||||
"hidden" => no_arguments().map(|_| StateKind::Hidden)?,
|
||||
"locked" => no_arguments().map(|_| StateKind::Locked)?,
|
||||
"pinned" => no_arguments().map(|_| StateKind::Pinned)?,
|
||||
"layer" => no_arguments().map(|_| StateKind::Layer)?,
|
||||
_ => {
|
||||
return Err(Error::new(
|
||||
name.span(),
|
||||
format!("Unknown node state `.{method}()`. Parameters go inside the call's parentheses, like `node({method} = ...)`"),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
Ok(State { kind, span: name.span() })
|
||||
}
|
||||
|
||||
fn parse_grid_coordinate(input: ParseStream) -> syn::Result<i32> {
|
||||
let negative = input.peek(Token![-]);
|
||||
if negative {
|
||||
input.parse::<Token![-]>()?;
|
||||
}
|
||||
|
||||
let literal: LitInt = input.parse().map_err(|error| Error::new(error.span(), "Positions are integers in grid units"))?;
|
||||
if !literal.suffix().is_empty() {
|
||||
return Err(Error::new(literal.span(), "Write the position without a type suffix"));
|
||||
}
|
||||
let magnitude: i32 = literal.base10_parse()?;
|
||||
Ok(if negative { -magnitude } else { magnitude })
|
||||
}
|
||||
|
||||
fn parse_primary(input: ParseStream) -> syn::Result<Expression> {
|
||||
let span = input.span();
|
||||
|
||||
if input.peek(syn::token::Paren) {
|
||||
let content;
|
||||
parenthesized!(content in input);
|
||||
let elements = Punctuated::<Expression, Token![,]>::parse_terminated(&content)?;
|
||||
if elements.is_empty() {
|
||||
return Err(Error::new(span, "Empty parentheses aren't part of the graph syntax"));
|
||||
}
|
||||
if elements.len() == 1 && !elements.trailing_punct() {
|
||||
return Ok(elements.into_iter().next().expect("there is one element"));
|
||||
}
|
||||
return Ok(Expression::Tuple {
|
||||
elements: elements.into_iter().collect(),
|
||||
span,
|
||||
});
|
||||
}
|
||||
|
||||
if input.peek(syn::token::Bracket) {
|
||||
let content;
|
||||
bracketed!(content in input);
|
||||
let numbers = Punctuated::<Value, Token![,]>::parse_terminated(&content)?;
|
||||
let components: Vec<f64> = numbers
|
||||
.iter()
|
||||
.filter_map(|number| match number.kind {
|
||||
ValueKind::Number(number) => Some(number),
|
||||
ValueKind::Integer(integer) => Some(integer as f64),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let [x, y] = components.as_slice() else {
|
||||
return Err(Error::new(span, "A value array is a two-number Vec2, like `[1., 2.]`"));
|
||||
};
|
||||
return Ok(Expression::Value(Value { kind: ValueKind::Vec2(*x, *y), span }));
|
||||
}
|
||||
|
||||
if input.peek(Lit) || input.peek(Token![-]) {
|
||||
return input.parse().map(Expression::Value);
|
||||
}
|
||||
|
||||
if input.peek(Ident) {
|
||||
let name: Ident = input.parse()?;
|
||||
if !input.peek(syn::token::Paren) {
|
||||
return Ok(Expression::Name(name));
|
||||
}
|
||||
|
||||
let content;
|
||||
parenthesized!(content in input);
|
||||
let arguments = Punctuated::<Argument, Token![,]>::parse_terminated(&content)?.into_iter().collect();
|
||||
return Ok(Expression::Call(Call { name, arguments, states: Vec::new() }));
|
||||
}
|
||||
|
||||
Err(input.error("This isn't part of the graph syntax"))
|
||||
}
|
||||
|
||||
impl Parse for Value {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let span = input.span();
|
||||
let negative = input.peek(Token![-]);
|
||||
if negative {
|
||||
input.parse::<Token![-]>()?;
|
||||
}
|
||||
|
||||
let literal: Lit = input.parse()?;
|
||||
let kind = match &literal {
|
||||
Lit::Int(integer) => {
|
||||
if !integer.suffix().is_empty() {
|
||||
return Err(Error::new(integer.span(), "Write the integer without a type suffix. Its type is `i64`"));
|
||||
}
|
||||
let value: i64 = integer.base10_parse()?;
|
||||
ValueKind::Integer(if negative { -value } else { value })
|
||||
}
|
||||
Lit::Float(float) => {
|
||||
if !float.suffix().is_empty() {
|
||||
return Err(Error::new(float.span(), "Write the number without a type suffix. Its type is `f64`"));
|
||||
}
|
||||
let value: f64 = float.base10_parse()?;
|
||||
ValueKind::Number(if negative { -value } else { value })
|
||||
}
|
||||
Lit::Bool(boolean) if !negative => ValueKind::Bool(boolean.value),
|
||||
Lit::Str(string) if !negative => ValueKind::String(string.value()),
|
||||
_ if negative => return Err(Error::new(literal.span(), "Only a number can be negated")),
|
||||
_ => return Err(Error::new(literal.span(), "Unsupported literal")),
|
||||
};
|
||||
|
||||
Ok(Self { kind, span })
|
||||
}
|
||||
}
|
||||
|
||||
impl Parse for Argument {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
let attributes = parse_attributes(input)?;
|
||||
|
||||
let parameter = if input.peek(Ident) && input.peek2(Token![=]) && !input.peek2(Token![==]) {
|
||||
let parameter = input.parse()?;
|
||||
input.parse::<Token![=]>()?;
|
||||
Some(parameter)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let value = parse_expression(input)?;
|
||||
|
||||
Ok(Self { attributes, parameter, value })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse(text: &str) -> syn::Result<Source> {
|
||||
syn::parse_str(text)
|
||||
}
|
||||
|
||||
fn error_message(text: &str) -> String {
|
||||
match parse(text) {
|
||||
Ok(_) => panic!("the graph text should be rejected"),
|
||||
Err(error) => error.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_header_uses_and_graph() {
|
||||
let source = parse(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use graphic_nodes::graphic::{as_graphic@1, extend@2 as append};
|
||||
use graphic_nodes::graphic::into_group@1;
|
||||
|
||||
/// Merges content.
|
||||
#[category("Graphic"), layer]
|
||||
fn merge@3(base, #[expose] content) -> (out) {
|
||||
let grouped = content >> into_group();
|
||||
base >> as_graphic() >> append(new = grouped)
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.expect("the graph text should parse");
|
||||
|
||||
let uses: Vec<String> = source.uses.iter().map(|entry| format!("{}::{}@{}", entry.module_path(), entry.local_name(), entry.version)).collect();
|
||||
assert_eq!(
|
||||
uses,
|
||||
["graphic_nodes::graphic::as_graphic@1", "graphic_nodes::graphic::append@2", "graphic_nodes::graphic::into_group@1"]
|
||||
);
|
||||
|
||||
let graph = &source.graph;
|
||||
assert_eq!(graph.name, "merge");
|
||||
assert_eq!(graph.version, 3);
|
||||
assert_eq!(doc_comment(&graph.attributes), "Merges content.");
|
||||
assert_eq!(graph.imports.len(), 2);
|
||||
assert_eq!(graph.bindings.len(), 1);
|
||||
assert!(matches!(graph.result, Expression::Feed { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_state_values_and_outputs() {
|
||||
let source = parse(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use a::b::{f@1, g@1};
|
||||
fn state@1(_, x) -> (match, other) {
|
||||
let node = f(#[exposed] flag = false, offset = -2.5, size = [1, -2.], count = 3, label = "text", x).named("N").offset(0, -2).hidden();
|
||||
(node.match, node >> g())
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.expect("the graph text should parse");
|
||||
|
||||
let graph = &source.graph;
|
||||
assert!(graph.imports[0].name.is_none());
|
||||
assert_eq!(graph.exports[0].name, "match");
|
||||
|
||||
let Expression::Call(call) = &graph.bindings[0].value else {
|
||||
panic!("the binding should be a call")
|
||||
};
|
||||
let kinds: Vec<StateKind> = call.states.iter().map(|state| state.kind.clone()).collect();
|
||||
assert!(kinds == [StateKind::Named("N".into()), StateKind::Offset(0, -2), StateKind::Hidden]);
|
||||
assert!(matches!(call.arguments[1].value, Expression::Value(Value { kind: ValueKind::Number(-2.5), .. })));
|
||||
assert!(matches!(call.arguments[2].value, Expression::Value(Value { kind: ValueKind::Vec2(1., -2.), .. })));
|
||||
assert!(matches!(call.arguments[3].value, Expression::Value(Value { kind: ValueKind::Integer(3), .. })));
|
||||
assert!(call.arguments[5].parameter.is_none());
|
||||
|
||||
let Expression::Tuple { elements, .. } = &graph.result else {
|
||||
panic!("the result should be a tuple")
|
||||
};
|
||||
assert!(matches!(&elements[0], Expression::Output { output, .. } if output == "match"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_text_without_a_supported_header() {
|
||||
assert!(error_message("fn a@1() -> (out) { b() }").contains("starts with its syntax version"));
|
||||
assert!(error_message("#![syntax(2)] fn a@1() -> (out) { b() }").contains("isn't supported"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_unversioned_and_unqualified_names() {
|
||||
assert!(error_message("#![syntax(1)] use a::b; fn a@1() -> (out) { b() }").contains("Give the version"));
|
||||
assert!(error_message("#![syntax(1)] use b@1; fn a@1() -> (out) { b() }").contains("full path"));
|
||||
assert!(error_message("#![syntax(1)] fn a() -> (out) { b() }").contains("Give the version"));
|
||||
assert!(error_message("#![syntax(1)] fn a@0() -> (out) { b() }").contains("start at 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_typed_imports_and_suffixed_literals() {
|
||||
assert!(error_message("#![syntax(1)] fn a@1(x: Item<f64>) -> (out) { b(x) }").contains("take no type"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(c = 1_u32) }").contains("without a type suffix"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(c = 1.5_f32) }").contains("without a type suffix"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_misplaced_state() {
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { let n = b(); n.hidden() }").contains("not on a binding"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().out.hidden() }").contains("before the output"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().hidden().hidden() }").contains("already set"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().weight(2) }").contains("Unknown node state"));
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().at(1.5, 2) }").contains("integers in grid units"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_a_semicolon_after_the_exports() {
|
||||
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(); }").contains("without a semicolon"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
use super::*;
|
||||
use crate::resolve::blank_field;
|
||||
use core_types::registry::{FieldMetadata, GraphInputSource, GraphNodeImplementation, GraphValue, NodeFlags, RegistryValueSource};
|
||||
use core_types::{Type, concrete};
|
||||
|
||||
fn parameter(identifier: &'static str, default_type: Type) -> FieldMetadata {
|
||||
FieldMetadata {
|
||||
name: identifier,
|
||||
identifier,
|
||||
description: "From the node.",
|
||||
default_type: Some(default_type),
|
||||
..blank_field()
|
||||
}
|
||||
}
|
||||
|
||||
fn proto_node(fields: Vec<FieldMetadata>) -> NodeMetadata {
|
||||
NodeMetadata {
|
||||
display_name: "",
|
||||
category: "",
|
||||
icon: None,
|
||||
fields,
|
||||
description: "",
|
||||
inspector: None,
|
||||
context_features: Vec::new(),
|
||||
flags: NodeFlags::default(),
|
||||
version: 1,
|
||||
output_fields: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `test_nodes::Group(content)`, `test_nodes::Extend(base, new)`, and `test_nodes::Scale(value, factor, label)`.
|
||||
fn proto_nodes() -> HashMap<ProtoNodeIdentifier, NodeMetadata> {
|
||||
let list = || Type::List(Box::new(concrete!(f64)));
|
||||
let number = || Type::Item(Box::new(concrete!(f64)));
|
||||
|
||||
let mut factor = parameter("factor", number());
|
||||
factor.unit = Some(" px");
|
||||
factor.value_source = RegistryValueSource::Default("2.");
|
||||
|
||||
HashMap::from([
|
||||
(ProtoNodeIdentifier::new("test_nodes::GroupNode"), proto_node(vec![parameter("content", list())])),
|
||||
(
|
||||
ProtoNodeIdentifier::new("test_nodes::ExtendNode"),
|
||||
proto_node(vec![parameter("base", list()), parameter("new", list())]),
|
||||
),
|
||||
(
|
||||
ProtoNodeIdentifier::new("test_nodes::ScaleNode"),
|
||||
proto_node(vec![parameter("value", number()), factor, parameter("label", Type::Item(Box::new(concrete!(String))))]),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn source(text: &'static str) -> GraphSource {
|
||||
GraphSource {
|
||||
module_path: "test_graphs",
|
||||
file: "test_graphs.rs",
|
||||
line: 1,
|
||||
column: 1,
|
||||
text,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_texts(texts: &[&'static str]) -> (Vec<GraphMetadata>, Vec<GraphTextError>) {
|
||||
let sources: Vec<GraphSource> = texts.iter().map(|text| source(text)).collect();
|
||||
resolve_sources(&sources, &proto_nodes())
|
||||
}
|
||||
|
||||
fn resolve_one(text: &'static str) -> GraphMetadata {
|
||||
let (mut graphs, errors) = resolve_texts(&[text]);
|
||||
assert!(errors.is_empty(), "the graph should resolve: {}", errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n"));
|
||||
graphs.remove(0)
|
||||
}
|
||||
|
||||
fn error_message(text: &'static str) -> String {
|
||||
let (graphs, errors) = resolve_texts(&[text]);
|
||||
assert!(graphs.is_empty(), "the graph should be rejected");
|
||||
errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
const MERGE: &str = r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::{extend@1, group@1};
|
||||
|
||||
/// Merges content.
|
||||
#[category("Test"), layer]
|
||||
fn merge@1(
|
||||
/// The stack below.
|
||||
base,
|
||||
#[expose]
|
||||
content,
|
||||
) -> (out) {
|
||||
base >> extend(new = content >> group())
|
||||
}
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn resolves_nodes_wires_and_layout() {
|
||||
let graph = resolve_one(MERGE);
|
||||
|
||||
assert_eq!(graph.identifier, "Merge");
|
||||
assert_eq!(graph.path, "test_graphs::merge");
|
||||
assert_eq!(graph.description, "Merges content.");
|
||||
assert!(graph.layer);
|
||||
|
||||
let implementations: Vec<_> = graph.nodes.iter().map(|node| node.implementation.clone()).collect();
|
||||
assert_eq!(
|
||||
implementations,
|
||||
[
|
||||
GraphNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test_nodes::GroupNode")),
|
||||
GraphNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test_nodes::ExtendNode")),
|
||||
]
|
||||
);
|
||||
assert!(matches!(
|
||||
graph.nodes[1].inputs.as_slice(),
|
||||
[(1, GraphInputSource::Node { node: 0, output: 0 }), (0, GraphInputSource::Import { index: 0, .. })]
|
||||
));
|
||||
assert!(matches!(graph.exports[0].source, GraphInputSource::Node { node: 1, output: 0 }));
|
||||
|
||||
let positions: Vec<_> = graph.nodes.iter().map(|node| node.position).collect();
|
||||
assert_eq!(positions, [(-7, 1), (0, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_inherit_from_the_input_they_feed_unless_overridden() {
|
||||
let graph = resolve_one(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::scale@1;
|
||||
|
||||
#[category("Test")]
|
||||
fn scaled@1(value, factor, #[unit("%")] #[default(10)] other) -> (out) {
|
||||
let first = value >> scale(factor);
|
||||
first >> scale(factor = other)
|
||||
}
|
||||
"#,
|
||||
);
|
||||
|
||||
let [value, factor, other] = graph.imports.as_slice() else {
|
||||
panic!("the graph should have three imports")
|
||||
};
|
||||
assert_eq!(value.name, "Value");
|
||||
assert_eq!(factor.unit, Some(" px"));
|
||||
assert_eq!(factor.description, "From the node.");
|
||||
assert!(matches!(factor.value_source, RegistryValueSource::Default("2.")));
|
||||
|
||||
assert_eq!(other.unit, Some("%"));
|
||||
assert!(matches!(other.value_source, RegistryValueSource::Default("10")));
|
||||
assert_eq!(other.default_type, Some(concrete!(i64)));
|
||||
assert!(matches!(&graph.nodes[1].inputs[0].1, GraphInputSource::Import { index: 2, ty } if *ty == Type::Item(Box::new(concrete!(i64)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_inherits_from_the_parameter_of_its_own_name_first() {
|
||||
let graph = resolve_one(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::scale@1;
|
||||
|
||||
#[category("Test")]
|
||||
fn scaled@1(value, label) -> (out) {
|
||||
let first = value >> scale(factor = 1., label = value);
|
||||
first >> scale(label)
|
||||
}
|
||||
"#,
|
||||
);
|
||||
|
||||
assert_eq!(graph.imports[0].default_type, Some(Type::Item(Box::new(concrete!(f64)))));
|
||||
assert_eq!(graph.imports[1].default_type, Some(Type::Item(Box::new(concrete!(String)))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_keep_the_type_they_are_written_with() {
|
||||
let graph = resolve_one(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::scale@1;
|
||||
|
||||
#[category("Test")]
|
||||
fn values@1(value) -> (out) {
|
||||
value >> scale(factor = 2, #[exposed] label = "text")
|
||||
}
|
||||
"#,
|
||||
);
|
||||
|
||||
let inputs = &graph.nodes[0].inputs;
|
||||
assert!(matches!(
|
||||
&inputs[0].1,
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Integer(2),
|
||||
exposed: None
|
||||
}
|
||||
));
|
||||
assert!(matches!(&inputs[1].1, GraphInputSource::Value { value: GraphValue::String(text), exposed: Some(true) } if text == "text"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_resolves_after_a_graph_it_uses_and_chooses_its_outputs_by_name() {
|
||||
let outer = r#"
|
||||
#![syntax(1)]
|
||||
use test_graphs::pair@1;
|
||||
use test_nodes::group@1;
|
||||
|
||||
#[category("Test")]
|
||||
fn outer@1(content) -> (out) {
|
||||
content >> pair().second >> group()
|
||||
}
|
||||
"#;
|
||||
let pair = r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::group@1;
|
||||
|
||||
#[category("Test")]
|
||||
fn pair@1(content) -> (first, second) {
|
||||
let grouped = content >> group();
|
||||
(grouped, grouped >> group())
|
||||
}
|
||||
"#;
|
||||
|
||||
let (graphs, errors) = resolve_texts(&[outer, pair]);
|
||||
assert!(errors.is_empty(), "both graphs should resolve");
|
||||
|
||||
let outer = graphs.iter().find(|graph| graph.identifier == "Outer").expect("the outer graph should resolve");
|
||||
assert_eq!(outer.nodes[0].implementation, GraphNodeImplementation::Graph("Pair"));
|
||||
assert!(matches!(outer.nodes[1].inputs[0].1, GraphInputSource::Node { node: 0, output: 1 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_names_that_dont_resolve() {
|
||||
let unknown_parameter = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::group@1;
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> group(weight = 2) }
|
||||
"#,
|
||||
);
|
||||
assert!(unknown_parameter.contains("`group` has no parameter named `weight`"), "{unknown_parameter}");
|
||||
|
||||
let unknown_node = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::missing@1;
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> missing() }
|
||||
"#,
|
||||
);
|
||||
assert!(unknown_node.contains("No node or graph is named `test_nodes::missing`"), "{unknown_node}");
|
||||
|
||||
let not_used = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> group() }
|
||||
"#,
|
||||
);
|
||||
assert!(not_used.contains("`group` isn't used"), "{not_used}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_versions_and_unused_entries() {
|
||||
let wrong_version = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::group@2;
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> group() }
|
||||
"#,
|
||||
);
|
||||
assert!(wrong_version.contains("is at version 1, not 2"), "{wrong_version}");
|
||||
|
||||
let unused = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::{extend@1, group@1};
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> group() }
|
||||
"#,
|
||||
);
|
||||
assert!(unused.contains("`extend` is used but never called"), "{unused}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wiring_mistakes() {
|
||||
let primary_twice = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::group@1;
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content >> group(content) }
|
||||
"#,
|
||||
);
|
||||
assert!(primary_twice.contains("is already fed"), "{primary_twice}");
|
||||
|
||||
let looped = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
use test_nodes::group@1;
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) {
|
||||
let node = group();
|
||||
node >> node
|
||||
}
|
||||
"#,
|
||||
);
|
||||
assert!(looped.contains("makes a loop"), "{looped}");
|
||||
|
||||
let export_from_import = error_message(
|
||||
r#"
|
||||
#![syntax(1)]
|
||||
#[category("Test")]
|
||||
fn bad@1(content) -> (out) { content }
|
||||
"#,
|
||||
);
|
||||
assert!(export_from_import.contains("straight from an import"), "{export_from_import}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_name_where_the_graph_is_written() {
|
||||
let (_, errors) = resolve_texts(&["#![syntax(1)] #[category(\"Test\")] fn bad@1(content) -> (out) { content >> missing() }"]);
|
||||
let error = errors.first().expect("the graph should be rejected");
|
||||
|
||||
assert_eq!((error.file, error.line, error.column), ("test_graphs.rs", 1, 1));
|
||||
assert!(error.excerpt.starts_with("missing()"), "{}", error.excerpt);
|
||||
}
|
||||
@@ -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
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
pub mod adjustment;
|
||||
pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod effect_layers;
|
||||
pub mod effects;
|
||||
pub mod generator;
|
||||
pub mod graphic;
|
||||
pub mod masks;
|
||||
pub(crate) mod parameters;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
@@ -15,9 +17,13 @@ pub use vector_types;
|
||||
pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use effects::{Effect, EffectKind, EffectOperation, Effects, GlowTechnique, paint_with_envelope_effects, stamp_effect, stamped_transform};
|
||||
pub use effects::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, fitted_paint, linked_to_content, paint_with_envelope_effects, stamp_effect,
|
||||
stamped_transform,
|
||||
};
|
||||
pub use generator::Generator;
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
pub use masks::MaskMode;
|
||||
|
||||
pub mod migrations {
|
||||
use crate::Vector;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//! The definitions shared by every renderer for masking content by another graphic and feathering it toward its edges.
|
||||
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use dyn_any::DynAny;
|
||||
|
||||
/// Which part of a graphic masks the content.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum MaskMode {
|
||||
/// White shows the content and black hides it, with transparent areas also hiding it.
|
||||
#[default]
|
||||
Luminance,
|
||||
/// Opaque areas show the content and transparent areas hide it, whatever their colors.
|
||||
Alpha,
|
||||
}
|
||||
|
||||
/// The weights of the red, green, and blue channels in a mask's luminance, those of SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
|
||||
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
|
||||
|
||||
/// How much a pixel of the mask graphic, given as premultiplied gamma-encoded channels, shows the content, from 0 to 1.
|
||||
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in either mode.
|
||||
pub fn mask_coverage([red, green, blue, alpha]: [f32; 4], mode: MaskMode) -> f32 {
|
||||
let [red_weight, green_weight, blue_weight] = MASK_LUMINANCE_WEIGHTS;
|
||||
let coverage = match mode {
|
||||
MaskMode::Luminance => red * red_weight + green * green_weight + blue * blue_weight,
|
||||
MaskMode::Alpha => alpha,
|
||||
};
|
||||
coverage.clamp(0., 1.)
|
||||
}
|
||||
|
||||
/// The slope and intercept of the line mapping a mask's feathered coverage to how much it shows the content, flipped if `invert`.
|
||||
/// For PSD interop, the `density` percentage scales how much the mask hides, so at 50% the content shows at half strength where the mask hides it fully.
|
||||
pub fn mask_density_line(density: f64, invert: bool) -> (f32, f32) {
|
||||
let density = (density / 100.).clamp(0., 1.) as f32;
|
||||
match invert {
|
||||
false => (density, 1. - density),
|
||||
true => (-density, 1.),
|
||||
}
|
||||
}
|
||||
|
||||
/// The standard deviation, in document pixels, of the Gaussian blur a mask's `feather` softens it by.
|
||||
/// For PSD interop, this is the feather radius, within 4 levels on hard edges of PSD's own kernel, which approximates the same Gaussian.
|
||||
pub fn mask_feather_sigma(feather: f64) -> f64 {
|
||||
feather.max(0.)
|
||||
}
|
||||
|
||||
/// The alpha at or below which a feather counts content as absent, half an 8-bit level, so the faint tail of a blur doesn't count as content, though an 8-bit image's faintest alpha does.
|
||||
pub const FEATHER_FOOTPRINT_ALPHA: f32 = 0.5 / 255.;
|
||||
|
||||
/// How far a feather of `distance` erodes the content's footprint, and the standard deviation of the Gaussian softening the eroded footprint, in the same units.
|
||||
///
|
||||
/// A feather multiplies the content by a strength made this way. The footprint is where the content's alpha exceeds [`FEATHER_FOOTPRINT_ALPHA`].
|
||||
/// Its edge falls within the pixels bordering the absent area by their alpha relative to the largest beside them, so translucent content places it as opaque content does.
|
||||
/// It is eroded by half the distance, measured in straight lines, then blurred by a Gaussian reaching three standard deviations, which end at the footprint's edge.
|
||||
/// Across a straight edge, the strength rises along the normal distribution's cumulative curve from nothing at the edge, through half at half the distance, to full at the distance. Parts thinner than the distance fade away entirely.
|
||||
/// A gap between parts counts as an edge only once it swallows a whole pixel, so gaps one to two pixels wide feather or not depending on where they fall on the pixel grid.
|
||||
pub fn feather_parts(distance: f64) -> (f64, f64) {
|
||||
let distance = distance.max(0.);
|
||||
(distance / 2., distance / 6.)
|
||||
}
|
||||
@@ -13,10 +13,7 @@ pub(crate) struct ColorOverlay {
|
||||
|
||||
impl MapColor for ColorOverlay {
|
||||
fn map_cpu(&self, pixel: Color) -> Color {
|
||||
let overlay = apply_blend_mode(self.color, pixel, self.blend_mode);
|
||||
let mix = |image: f32, overlay: f32| image + (overlay - image) * self.opacity;
|
||||
|
||||
Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a())
|
||||
overlay_paint(pixel, self.color, self.blend_mode, self.opacity)
|
||||
}
|
||||
|
||||
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
||||
@@ -25,6 +22,37 @@ impl MapColor for ColorOverlay {
|
||||
}
|
||||
}
|
||||
|
||||
/// The color with `paint` mixed over it by the blend mode in gamma, as much as the paint's alpha times `opacity` (from 0 to 1), keeping the color's own alpha.
|
||||
pub fn overlay_paint(color: Color, paint: Color, blend_mode: BlendMode, opacity: f32) -> Color {
|
||||
let gamma = |color: Color| {
|
||||
let [red, green, blue, _] = color.to_gamma_srgb_channels();
|
||||
[red, green, blue]
|
||||
};
|
||||
let (under, over) = (gamma(color), gamma(paint));
|
||||
let blended = blend_gamma(under, over, blend_mode);
|
||||
|
||||
let amount = opacity * paint.a();
|
||||
let [red, green, blue] = std::array::from_fn(|channel| under[channel] + (blended[channel] - under[channel]) * amount);
|
||||
Color::from_gamma_srgb_channels(red, green, blue, color.a())
|
||||
}
|
||||
|
||||
/// The blend mode's mix of straight gamma-encoded `backdrop` and `paint` colors.
|
||||
pub fn blend_gamma(backdrop: [f32; 3], paint: [f32; 3], blend_mode: BlendMode) -> [f32; 3] {
|
||||
match blend_mode {
|
||||
// The component modes encode the colors they're given themselves
|
||||
BlendMode::Hue | BlendMode::Saturation | BlendMode::Color | BlendMode::Luminosity => {
|
||||
let color = |[red, green, blue]: [f32; 3]| Color::from_gamma_srgb_channels(red, green, blue, 1.);
|
||||
let [red, green, blue, _] = apply_blend_mode(color(paint), color(backdrop), blend_mode).to_gamma_srgb_channels();
|
||||
[red, green, blue]
|
||||
}
|
||||
_ => {
|
||||
let color = |[red, green, blue]: [f32; 3]| Color::from_rgbaf32_unchecked(red, green, blue, 1.);
|
||||
let blended = apply_blend_mode(color(paint), color(backdrop), blend_mode);
|
||||
[blended.r(), blended.g(), blended.b()]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every blend mode with the name the shader gives its code.
|
||||
const BLEND_MODES: [(BlendMode, &str); 29] = [
|
||||
(BlendMode::Normal, "BLEND_NORMAL"),
|
||||
|
||||
@@ -18,6 +18,32 @@ pub const MAX_KERNEL_REACH: usize = 24;
|
||||
/// The most times an image is halved for a blur, by which point it is one pixel across.
|
||||
const MAX_LEVELS: u32 = 16;
|
||||
|
||||
/// How many passes after jump flooding to `reach` look for nearer seeds through the neighbors one chamfer step away, which settles the near misses within about 20 pixels.
|
||||
/// Since a chamfer length is the shortest path of such steps, a pixel whose neighbor along that path found the nearest seed finds it too.
|
||||
pub fn chamfer_passes(reach: f64) -> usize {
|
||||
if reach > 16. { 4 } else { 2 }
|
||||
}
|
||||
|
||||
/// The steps of a chamfer path (one pixel straight or diagonally, or a knight's move) by rows from the top, the order the GPU visits them in too.
|
||||
const CHAMFER_STEPS: [[i32; 2]; 16] = [
|
||||
[-1, -2],
|
||||
[1, -2],
|
||||
[-2, -1],
|
||||
[-1, -1],
|
||||
[0, -1],
|
||||
[1, -1],
|
||||
[2, -1],
|
||||
[-1, 0],
|
||||
[1, 0],
|
||||
[-2, 1],
|
||||
[-1, 1],
|
||||
[0, 1],
|
||||
[1, 1],
|
||||
[2, 1],
|
||||
[-1, 2],
|
||||
[1, 2],
|
||||
];
|
||||
|
||||
/// A blur's kernel along one axis, sized in pixels.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum BlurKernel {
|
||||
@@ -226,46 +252,48 @@ impl Plane<f32> {
|
||||
}
|
||||
|
||||
/// Each pixel's least `distance` to a seed, given its offset from the seed and the seed's value, or infinity past `reach`.
|
||||
/// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, so farther pixels may find none. O(width × height × log(reach)).
|
||||
fn jump_flood(&self, reach: f64, is_seed: impl Fn(f32) -> bool, distance: impl Fn([i32; 2], f32) -> f32 + Sync) -> Self {
|
||||
/// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, so farther pixels may find none.
|
||||
/// Seeds of differing values leave near misses, mostly settled by two more halving passes and then those of [`chamfer_passes`] along the chamfer steps. O(width × height × log(reach)).
|
||||
pub(crate) fn jump_flood(&self, reach: f64, is_seed: impl Fn(f32) -> bool, distance: impl Fn([i32; 2], f32) -> f32 + Sync) -> Self {
|
||||
let mut nearest: Vec<Option<[i32; 2]>> = self.data.iter().map(|&value| is_seed(value).then_some([0, 0])).collect();
|
||||
|
||||
let (columns, rows) = (self.width as i32, self.height as i32);
|
||||
// The offset runs from the seed to the pixel
|
||||
let distance = |x: i32, y: i32, offset: [i32; 2]| distance(offset, self.data[((y - offset[1]) * columns + x - offset[0]) as usize]);
|
||||
|
||||
let mut step = (reach.clamp(0., (columns.max(rows)) as f64).ceil() as u32 + 1).next_power_of_two();
|
||||
while step >= 1 {
|
||||
let previous = nearest.clone();
|
||||
let step_length = step as i32;
|
||||
// The neighbors each pass looks at in the GPU's order: the eight a step away, then those one chamfer step away
|
||||
let first_step = (reach.clamp(0., (columns.max(rows)) as f64).ceil() as u32 + 1).next_power_of_two() as i32;
|
||||
let halvings = std::iter::successors(Some(first_step), |&step| (step > 1).then_some(step / 2)).chain([2, 1]);
|
||||
let adjacent = CHAMFER_STEPS.iter().filter(|[x, y]| x.abs().max(y.abs()) == 1);
|
||||
let around = |step: i32| adjacent.clone().map(|&[x, y]| [x * step, y * step]).collect::<Vec<_>>();
|
||||
let passes = halvings.map(around).chain(std::iter::repeat_n(CHAMFER_STEPS.to_vec(), chamfer_passes(reach)));
|
||||
|
||||
// Each pixel keeps the nearest of the seeds that it and its eight neighbors a step away have found so far
|
||||
for neighbors in passes {
|
||||
let previous = nearest.clone();
|
||||
|
||||
// Each pixel keeps the nearest of the seeds that it and its neighbors have found so far
|
||||
fill_rows(&mut nearest, self.width, |y, row| {
|
||||
let y = y as i32;
|
||||
for (x, best) in row.iter_mut().enumerate() {
|
||||
let x = x as i32;
|
||||
let mut best_distance = best.map_or(f32::INFINITY, |offset| distance(x, y, offset));
|
||||
|
||||
for neighbor_y in -1..=1 {
|
||||
for neighbor_x in -1..=1 {
|
||||
let (neighbor_x, neighbor_y) = (neighbor_x * step_length, neighbor_y * step_length);
|
||||
let (from_x, from_y) = (x + neighbor_x, y + neighbor_y);
|
||||
if from_x < 0 || from_y < 0 || from_x >= columns || from_y >= rows {
|
||||
continue;
|
||||
}
|
||||
let Some([offset_x, offset_y]) = previous[(from_y * columns + from_x) as usize] else { continue };
|
||||
for &[neighbor_x, neighbor_y] in &neighbors {
|
||||
let (from_x, from_y) = (x + neighbor_x, y + neighbor_y);
|
||||
if from_x < 0 || from_y < 0 || from_x >= columns || from_y >= rows {
|
||||
continue;
|
||||
}
|
||||
let Some([offset_x, offset_y]) = previous[(from_y * columns + from_x) as usize] else { continue };
|
||||
|
||||
let candidate = [offset_x - neighbor_x, offset_y - neighbor_y];
|
||||
let candidate_distance = distance(x, y, candidate);
|
||||
if candidate_distance < best_distance {
|
||||
*best = Some(candidate);
|
||||
best_distance = candidate_distance;
|
||||
}
|
||||
let candidate = [offset_x - neighbor_x, offset_y - neighbor_y];
|
||||
let candidate_distance = distance(x, y, candidate);
|
||||
if candidate_distance < best_distance {
|
||||
*best = Some(candidate);
|
||||
best_distance = candidate_distance;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
step /= 2;
|
||||
}
|
||||
|
||||
let data = nearest
|
||||
@@ -453,6 +481,77 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distances_from_seeds_of_differing_values_are_exact_within_their_reach() {
|
||||
// An antialiased disk whose edge pixels seed with head starts set by their coverage away from half, as a Soft Chisel bevel's do
|
||||
let side = 40;
|
||||
let disk = Plane {
|
||||
width: side,
|
||||
height: side,
|
||||
data: (0..side * side)
|
||||
.map(|index| {
|
||||
let (x, y) = ((index % side) as f64 + 0.5 - 20.3, (index / side) as f64 + 0.5 - 19.6);
|
||||
(12.5 - (x * x + y * y).sqrt()).clamp(0., 1.) as f32
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let head_starts = disk.map(|alpha| ((alpha - 0.5) * 22.).max(0.));
|
||||
let reach = 11.;
|
||||
|
||||
// O(n²) over the pixel pairs, small enough here
|
||||
let exactly = |values: &Plane<f32>, distance: &dyn Fn([i32; 2], f32) -> Option<f32>| {
|
||||
(0..side * side)
|
||||
.map(|index| {
|
||||
let (x, y) = ((index % side) as i32, (index / side) as i32);
|
||||
let candidates = (0..side * side).filter_map(|from| {
|
||||
let offset = [x - (from % side) as i32, y - (from / side) as i32];
|
||||
distance(offset, values.data[from])
|
||||
});
|
||||
candidates.fold(f32::INFINITY, f32::min)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
let found = head_starts.distances_through_seeds(reach);
|
||||
let exact = exactly(&head_starts, &|offset, value| Some(chamfer_length(offset) + value));
|
||||
let found_edges = disk.distances_to_silhouette(reach);
|
||||
let exact_edges = exactly(&disk, &|offset, coverage| (coverage > 0.).then(|| chamfer_length(offset) + 1. - coverage));
|
||||
|
||||
for index in 0..side * side {
|
||||
if exact[index] <= reach as f32 {
|
||||
assert!(
|
||||
(found.data[index] - exact[index]).abs() < 1e-4,
|
||||
"pixel {index} lies {} from the seeds, not {}",
|
||||
found.data[index],
|
||||
exact[index]
|
||||
);
|
||||
}
|
||||
if exact_edges[index] <= reach as f32 {
|
||||
assert!(
|
||||
(found_edges.data[index] - exact_edges[index]).abs() < 1e-4,
|
||||
"pixel {index} lies {} from the edge, not {}",
|
||||
found_edges.data[index],
|
||||
exact_edges[index]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn growing_the_outside_inward_covers_only_the_band_along_the_edges() {
|
||||
let mut square = Plane::<f32>::new(21, 21);
|
||||
for y in 2..19 {
|
||||
square.data[y * 21 + 2..y * 21 + 19].fill(1.);
|
||||
}
|
||||
let inward = square.map(|coverage| 1. - coverage).grown(3.);
|
||||
let at = |x: usize, y: usize| inward.data[y * 21 + x];
|
||||
|
||||
assert_eq!(at(2, 10), 1., "at the edge");
|
||||
assert_eq!(at(4, 10), 1., "the band's full width in");
|
||||
assert_eq!(at(5, 10), 0., "past the band's width");
|
||||
assert_eq!(at(10, 10), 0., "deep inside");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shifting_moves_by_fractions_of_a_pixel() {
|
||||
let mut plane = Plane::<f32>::new(4, 1);
|
||||
|
||||
@@ -16,25 +16,24 @@ pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32,
|
||||
let pixel_center = |x: usize, y: usize| area[0] + (DVec2::new(x as f64, y as f64) + 0.5) * pixel_size;
|
||||
|
||||
match pattern {
|
||||
GeneratorPattern::Noise(settings) => {
|
||||
let noise = NoiseSampler::new(settings);
|
||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = Color::from_luminance(noise.sample(pixel_center(x, y))));
|
||||
});
|
||||
}
|
||||
// Across a known area, a Mandelbrot pattern follows a reference orbit as the GPU does
|
||||
GeneratorPattern::Mandelbrot(settings) => {
|
||||
let setup = MandelbrotSetup::new(settings);
|
||||
let (plane_area, plane_texel) = (area.map(|point| setup.plane_point(point)), (pixel_size / setup.scale).min_element());
|
||||
let reference = setup.reference_orbit(plane_area, plane_texel);
|
||||
let interior_test = setup.has_interior_test() && resolves_in_32_bits(plane_area, plane_texel);
|
||||
// The brightness is gamma-encoded, so a Gradient Map takes it as the position along its gradient
|
||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| {
|
||||
let value = setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test).clamp(0., 1.);
|
||||
*pixel = Color::from_gamma_srgb_channels(value, value, value, 1.);
|
||||
*pixel = mandelbrot_gray(setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test));
|
||||
});
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
let sample = pattern_sampler(pattern);
|
||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = sample(pixel_center(x, y)));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(image)
|
||||
@@ -48,6 +47,30 @@ pub fn thumbnail_area(pattern: &GeneratorPattern) -> Option<[DVec2; 2]> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples the pattern's color at points in its own space, after the setup shared by every sample.
|
||||
/// A Mandelbrot pattern is iterated directly in 64 bits, since the points may lie anywhere.
|
||||
pub fn pattern_sampler(pattern: &GeneratorPattern) -> impl Fn(DVec2) -> Color + Sync + use<> {
|
||||
enum Sampler {
|
||||
Noise(NoiseSampler),
|
||||
Mandelbrot(MandelbrotSetup),
|
||||
}
|
||||
let sampler = match pattern {
|
||||
GeneratorPattern::Noise(settings) => Sampler::Noise(NoiseSampler::new(settings)),
|
||||
GeneratorPattern::Mandelbrot(settings) => Sampler::Mandelbrot(MandelbrotSetup::new(settings)),
|
||||
};
|
||||
|
||||
move |point| match &sampler {
|
||||
Sampler::Noise(noise) => Color::from_luminance(noise.sample(point)),
|
||||
Sampler::Mandelbrot(setup) => mandelbrot_gray(setup.sample(setup.plane_point(point), None, false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Mandelbrot brightness as a gray, gamma-encoded so a Gradient Map takes it as the position along its gradient.
|
||||
fn mandelbrot_gray(brightness: f32) -> Color {
|
||||
let value = brightness.clamp(0., 1.);
|
||||
Color::from_gamma_srgb_channels(value, value, value, 1.)
|
||||
}
|
||||
|
||||
/// Samples a noise pattern's luminance, from 0 to 1, at positions in its space.
|
||||
struct NoiseSampler {
|
||||
noise: fastnoise_lite::FastNoiseLite,
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Blends a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend.
|
||||
//! The modes CSS lacks blend normally, since layers only ever take the others.
|
||||
|
||||
use crate::effect_kernels::Plane;
|
||||
use core_types::blending::BlendMode;
|
||||
|
||||
/// The premultiplied gamma-encoded `layer` blended by the mode onto the layers `below` it. O(width × height).
|
||||
pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode: BlendMode) -> Plane<[f32; 4]> {
|
||||
layer.zip(below, |source, backdrop| blend_pixel(source, backdrop, blend_mode))
|
||||
}
|
||||
|
||||
/// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop.
|
||||
pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] {
|
||||
let (source_alpha, backdrop_alpha) = (source[3], backdrop[3]);
|
||||
if source_alpha <= 0. {
|
||||
return backdrop;
|
||||
}
|
||||
|
||||
let straight = |pixel: [f32; 4]| match pixel[3] > 0. {
|
||||
true => [0, 1, 2].map(|channel| (pixel[channel] / pixel[3]).clamp(0., 1.)),
|
||||
false => [0.; 3],
|
||||
};
|
||||
let (source_color, backdrop_color) = (straight(source), straight(backdrop));
|
||||
let blended = blend(backdrop_color, source_color, blend_mode);
|
||||
|
||||
let mut result = [0.; 4];
|
||||
for channel in 0..3 {
|
||||
let mixed = (1. - backdrop_alpha) * source_color[channel] + backdrop_alpha * blended[channel];
|
||||
result[channel] = source_alpha * mixed + (1. - source_alpha) * backdrop[channel];
|
||||
}
|
||||
result[3] = source_alpha + backdrop_alpha * (1. - source_alpha);
|
||||
result
|
||||
}
|
||||
|
||||
/// The mode's blend of straight `backdrop` and `source` colors.
|
||||
fn blend(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode) -> [f32; 3] {
|
||||
match blend_mode {
|
||||
BlendMode::Hue => set_luminosity(set_saturation(source, saturation(backdrop)), luminosity(backdrop)),
|
||||
BlendMode::Saturation => set_luminosity(set_saturation(backdrop, saturation(source)), luminosity(backdrop)),
|
||||
BlendMode::Color => set_luminosity(source, luminosity(backdrop)),
|
||||
BlendMode::Luminosity => set_luminosity(backdrop, luminosity(source)),
|
||||
_ => [0, 1, 2].map(|channel| blend_channel(backdrop[channel], source[channel], blend_mode)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode's blend of one channel of the backdrop and source, for the modes that blend each channel on its own.
|
||||
fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
|
||||
let hard_light = |backdrop: f32, source: f32| match source <= 0.5 {
|
||||
true => backdrop * 2. * source,
|
||||
false => screen(backdrop, 2. * source - 1.),
|
||||
};
|
||||
|
||||
match blend_mode {
|
||||
BlendMode::Multiply => backdrop * source,
|
||||
BlendMode::Screen => screen(backdrop, source),
|
||||
BlendMode::Overlay => hard_light(source, backdrop),
|
||||
BlendMode::Darken => backdrop.min(source),
|
||||
BlendMode::Lighten => backdrop.max(source),
|
||||
BlendMode::ColorDodge if backdrop <= 0. => 0.,
|
||||
BlendMode::ColorDodge if source >= 1. => 1.,
|
||||
BlendMode::ColorDodge => (backdrop / (1. - source)).min(1.),
|
||||
BlendMode::ColorBurn if backdrop >= 1. => 1.,
|
||||
BlendMode::ColorBurn if source <= 0. => 0.,
|
||||
BlendMode::ColorBurn => 1. - ((1. - backdrop) / source).min(1.),
|
||||
BlendMode::HardLight => hard_light(backdrop, source),
|
||||
BlendMode::SoftLight if source <= 0.5 => backdrop - (1. - 2. * source) * backdrop * (1. - backdrop),
|
||||
BlendMode::SoftLight => {
|
||||
let darkened = if backdrop <= 0.25 { ((16. * backdrop - 12.) * backdrop + 4.) * backdrop } else { backdrop.sqrt() };
|
||||
backdrop + (2. * source - 1.) * (darkened - backdrop)
|
||||
}
|
||||
BlendMode::Difference => (backdrop - source).abs(),
|
||||
BlendMode::Exclusion => backdrop + source - 2. * backdrop * source,
|
||||
_ => source,
|
||||
}
|
||||
}
|
||||
|
||||
fn screen(backdrop: f32, source: f32) -> f32 {
|
||||
backdrop + source - backdrop * source
|
||||
}
|
||||
|
||||
fn luminosity([red, green, blue]: [f32; 3]) -> f32 {
|
||||
0.3 * red + 0.59 * green + 0.11 * blue
|
||||
}
|
||||
|
||||
/// The color moved to the `target` luminosity, its channels pulled back toward it where they leave the range from 0 to 1.
|
||||
fn set_luminosity(color: [f32; 3], target: f32) -> [f32; 3] {
|
||||
let shift = target - luminosity(color);
|
||||
let color = color.map(|channel| channel + shift);
|
||||
|
||||
// Channels all equal to the luminosity have no spread to pull back, only rounding past the range, which clamping removes
|
||||
let luminosity = luminosity(color);
|
||||
let (minimum, maximum) = (color[0].min(color[1]).min(color[2]), color[0].max(color[1]).max(color[2]));
|
||||
color.map(|channel| {
|
||||
let channel = if minimum < 0. && luminosity > minimum {
|
||||
luminosity + (channel - luminosity) * luminosity / (luminosity - minimum)
|
||||
} else {
|
||||
channel
|
||||
};
|
||||
let channel = if maximum > 1. && maximum > luminosity {
|
||||
luminosity + (channel - luminosity) * (1. - luminosity) / (maximum - luminosity)
|
||||
} else {
|
||||
channel
|
||||
};
|
||||
channel.clamp(0., 1.)
|
||||
})
|
||||
}
|
||||
|
||||
fn saturation([red, green, blue]: [f32; 3]) -> f32 {
|
||||
red.max(green).max(blue) - red.min(green).min(blue)
|
||||
}
|
||||
|
||||
/// The color with its channels spread to the `target` saturation, keeping which is largest, middle, and smallest.
|
||||
fn set_saturation(color: [f32; 3], target: f32) -> [f32; 3] {
|
||||
let (minimum, maximum) = (color[0].min(color[1]).min(color[2]), color[0].max(color[1]).max(color[2]));
|
||||
if maximum <= minimum {
|
||||
return [0.; 3];
|
||||
}
|
||||
color.map(|channel| (channel - minimum) * target / (maximum - minimum))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn blending_over_nothing_leaves_the_source_as_it_is() {
|
||||
let source = [0.2, 0.3, 0.1, 0.5];
|
||||
for blend_mode in [BlendMode::Multiply, BlendMode::Screen, BlendMode::Hue, BlendMode::ColorBurn] {
|
||||
let blended = blend_pixel(source, [0.; 4], blend_mode);
|
||||
assert!(blended.iter().zip(source).all(|(blended, source)| (blended - source).abs() < 1e-6), "{blend_mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_opaque_backdrop_takes_the_blend_of_both_colors() {
|
||||
let multiplied = blend_pixel([0.5, 0.5, 0.5, 1.], [0.8, 0.4, 1., 1.], BlendMode::Multiply);
|
||||
assert!((multiplied[0] - 0.4).abs() < 1e-6 && (multiplied[1] - 0.2).abs() < 1e-6 && (multiplied[2] - 0.5).abs() < 1e-6);
|
||||
assert_eq!(multiplied[3], 1.);
|
||||
|
||||
// Half a source mixes halfway toward the blend
|
||||
let screened = blend_pixel([0.25, 0.25, 0.25, 0.5], [0.5, 0.5, 0.5, 1.], BlendMode::Screen);
|
||||
assert!((screened[0] - (0.5 * 0.75 + 0.5 * 0.5)).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_luminosity_of_black_over_any_gray_is_black() {
|
||||
for level in 0..=255 {
|
||||
let gray = level as f32 / 255.;
|
||||
let blended = blend_pixel([0., 0., 0., 1.], [gray, gray, gray, 1.], BlendMode::Luminosity);
|
||||
assert!(blended.iter().take(3).all(|&channel| channel.abs() < 1e-6), "gray {level} gives {blended:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,9 @@ pub mod color_lookup_table;
|
||||
pub mod effect_kernels;
|
||||
pub mod generators;
|
||||
mod kernel;
|
||||
pub mod layer_blending;
|
||||
pub mod mandelbrot;
|
||||
mod masks;
|
||||
pub mod raster_effects;
|
||||
pub mod value_effects;
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//! The CPU twins of the GPU passes that mask content by another graphic and feather it toward its edges.
|
||||
|
||||
use crate::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, Plane};
|
||||
use crate::raster_effects::premultiplied_gamma_channels;
|
||||
use core_types::Color;
|
||||
use glam::DVec2;
|
||||
use graphic_types::masks::{FEATHER_FOOTPRINT_ALPHA, MaskMode, feather_parts, mask_coverage, mask_density_line, mask_feather_sigma};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// How much the mask shows the content at each pixel, from 0 to 1, given the `colors` its graphic draws over a plane of `width` by `height` pixels.
|
||||
/// Its coverage is softened by the `feather` (in document pixels, `pixels_per_length` pixels each), then mapped through its `density` percentage, flipped if `invert`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn mask_strength(colors: &[Color], width: usize, height: usize, mode: MaskMode, density: f64, feather: f64, invert: bool, pixels_per_length: DVec2) -> Plane<f32> {
|
||||
let coverage = Plane {
|
||||
width,
|
||||
height,
|
||||
data: colors.iter().map(|&color| mask_coverage(premultiplied_gamma_channels(color), mode)).collect(),
|
||||
};
|
||||
|
||||
let sigma = mask_feather_sigma(feather) * pixels_per_length;
|
||||
let coverage = match sigma.max_element() >= NEGLIGIBLE_LENGTH {
|
||||
true => coverage.blurred(BlurKernel::Gaussian { sigma: sigma.x }, BlurKernel::Gaussian { sigma: sigma.y }),
|
||||
false => coverage,
|
||||
};
|
||||
|
||||
let (slope, intercept) = mask_density_line(density, invert);
|
||||
coverage.map(|coverage| (slope * coverage + intercept).clamp(0., 1.))
|
||||
}
|
||||
|
||||
/// The premultiplied image faded at each pixel by the mask's `strength` there.
|
||||
pub(crate) fn masked(image: &Plane<[f32; 4]>, strength: &Plane<f32>) -> Plane<[f32; 4]> {
|
||||
image.zip(strength, |pixel, strength| pixel.map(|channel| channel * strength))
|
||||
}
|
||||
|
||||
/// How much a footprint eroded by `erosion` pixels covers a pixel, given the pixel's distance to the area outside the footprint plus half a pixel and its share of that area, relative to its own coverage of the footprint.
|
||||
fn erode(to_outside: f32, outside_coverage: f32, erosion: f32) -> f32 {
|
||||
let coverage = 1. - outside_coverage;
|
||||
let eroded = (to_outside - erosion).clamp(0., 1.);
|
||||
if coverage > 0. { (eroded / coverage).min(1.) } else { eroded }
|
||||
}
|
||||
|
||||
/// How much a feather of `distance` pixels keeps of the `full`-strength content at each pixel, from 0 to 1, as [`feather_parts`] defines it, matching the GPU's `feather_strength`.
|
||||
/// O(width × height × log(distance)).
|
||||
pub(crate) fn feather_strength(full: &Plane<[f32; 4]>, distance: f64) -> Plane<f32> {
|
||||
let (width, height) = (full.width, full.height);
|
||||
let alpha_at = |x: usize, y: usize| full.data[y * width + x][3];
|
||||
|
||||
// The area outside the footprint, with its edge falling within the pixels bordering it by their alpha relative to the largest beside them
|
||||
let mut outside = Plane::<f32>::new(width, height);
|
||||
fill_rows(&mut outside.data, width, |y, row| {
|
||||
for (x, outside_coverage) in row.iter_mut().enumerate() {
|
||||
let alpha = alpha_at(x, y);
|
||||
let neighbors = (y.saturating_sub(1)..(y + 2).min(height)).flat_map(|neighbor_y| (x.saturating_sub(1)..(x + 2).min(width)).map(move |neighbor_x| (neighbor_x, neighbor_y)));
|
||||
let neighbor_alphas = neighbors.map(|(neighbor_x, neighbor_y)| alpha_at(neighbor_x, neighbor_y));
|
||||
let (borders_absence, largest) = neighbor_alphas.fold((false, alpha), |(borders, largest), neighbor| (borders || neighbor <= FEATHER_FOOTPRINT_ALPHA, largest.max(neighbor)));
|
||||
|
||||
*outside_coverage = match (alpha <= FEATHER_FOOTPRINT_ALPHA, borders_absence) {
|
||||
(true, _) => 1.,
|
||||
(false, true) => 1. - (alpha / largest).min(1.),
|
||||
(false, false) => 0.,
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// The footprint eroded in straight lines, from each pixel's distance to the edge plus half a pixel, relative to the pixel's own coverage of the footprint so a feather of nothing keeps the content as it is
|
||||
let (erosion, sigma) = feather_parts(distance);
|
||||
let to_outside = outside.jump_flood(erosion + 2., |coverage| coverage > 0., |[x, y], coverage| (x as f32).hypot(y as f32) + (0.5 - coverage) + 0.5);
|
||||
let eroded = to_outside.zip(&outside, |to_outside, outside_coverage| erode(to_outside, outside_coverage, erosion as f32));
|
||||
|
||||
match sigma >= NEGLIGIBLE_LENGTH {
|
||||
true => eroded.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma }),
|
||||
false => eroded,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The standard normal cumulative distribution, from the Abramowitz and Stegun approximation of the error function, accurate to 1e-7.
|
||||
fn normal_cdf(x: f64) -> f64 {
|
||||
let z = x.abs() / std::f64::consts::SQRT_2;
|
||||
let t = 1. / (1. + 0.327_591_1 * z);
|
||||
let polynomial = t * (0.254_829_592 + t * (-0.284_496_736 + t * (1.421_413_741 + t * (-1.453_152_027 + t * 1.061_405_429))));
|
||||
let erf = 1. - polynomial * (-z * z).exp();
|
||||
if x >= 0. { 0.5 * (1. + erf) } else { 0.5 * (1. - erf) }
|
||||
}
|
||||
|
||||
/// A plane of white content with the alpha `coverage` gives at each pixel's center.
|
||||
fn content(size: usize, coverage: impl Fn(f64, f64) -> f32) -> Plane<[f32; 4]> {
|
||||
let mut plane = Plane::<[f32; 4]>::new(size, size);
|
||||
for (index, pixel) in plane.data.iter_mut().enumerate() {
|
||||
let alpha = coverage((index % size) as f64 + 0.5, (index / size) as f64 + 0.5);
|
||||
*pixel = [alpha; 4];
|
||||
}
|
||||
plane
|
||||
}
|
||||
|
||||
/// The feather's strength across a straight edge, as the definition gives it for a pixel center at `depth` within the edge.
|
||||
fn expected(depth: f64, distance: f64) -> f64 {
|
||||
normal_cdf((depth - distance / 2.) / (distance / 6.))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feathers_follow_the_definition_across_straight_and_round_edges() {
|
||||
let distance = 16.;
|
||||
|
||||
// A square from 8 to 56, measured across its left edge on its middle row
|
||||
let square = content(64, |x, y| if (8. ..56.).contains(&x) && (8. ..56.).contains(&y) { 1. } else { 0. });
|
||||
let strength = feather_strength(&square, distance);
|
||||
for x in 8..30 {
|
||||
let depth = x as f64 + 0.5 - 8.;
|
||||
let actual = strength.data[32 * 64 + x] as f64;
|
||||
assert!((actual - expected(depth, distance)).abs() < 0.03, "at depth {depth} the square keeps {actual}");
|
||||
}
|
||||
|
||||
// A disk of radius 28 with an antialiased edge, measured along a diagonal, where distances by chamfer steps would stray from straight lines
|
||||
let disk = content(80, |x, y| (28.5 - (x - 40.).hypot(y - 40.)).clamp(0., 1.) as f32);
|
||||
let strength = feather_strength(&disk, distance);
|
||||
for step in 0..14 {
|
||||
let (x, y) = (40 + 19 - step, 40 + 19 - step);
|
||||
let depth = 28. - (x as f64 + 0.5 - 40.).hypot(y as f64 + 0.5 - 40.);
|
||||
let actual = strength.data[y * 80 + x] as f64;
|
||||
assert!((actual - expected(depth, distance)).abs() < 0.04, "at depth {depth} on the diagonal the disk keeps {actual}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feathers_fade_thin_parts_and_hole_edges_and_keep_translucent_edges_where_opaque_ones_are() {
|
||||
let distance = 12.;
|
||||
|
||||
// A strip thinner than the distance fades away entirely
|
||||
let strip = content(48, |x, _| if (20. ..26.).contains(&x) { 1. } else { 0. });
|
||||
let strength = feather_strength(&strip, distance);
|
||||
assert!(strength.data[24 * 48 + 23] < 0.01, "the strip's middle keeps {}", strength.data[24 * 48 + 23]);
|
||||
|
||||
// A hole's edge fades like the outline's
|
||||
let holed = content(64, |x, y| if (x - 32.).hypot(y - 32.) < 4. { 0. } else { 1. });
|
||||
let strength = feather_strength(&holed, distance);
|
||||
assert!(strength.data[32 * 64 + 36] < 0.05, "beside the hole the content keeps {}", strength.data[32 * 64 + 36]);
|
||||
|
||||
// Content at 40% places its edge as opaque content does
|
||||
let opaque = feather_strength(&content(48, |x, _| if x >= 16. { 1. } else { 0. }), distance);
|
||||
let translucent = feather_strength(&content(48, |x, _| if x >= 16. { 0.4 } else { 0. }), distance);
|
||||
for x in 16..32 {
|
||||
assert!(
|
||||
(opaque.data[24 * 48 + x] - translucent.data[24 * 48 + x]).abs() < 1e-4,
|
||||
"at {x} the translucent content is feathered differently"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_feather_of_almost_nothing_keeps_the_content_as_it_is() {
|
||||
let disk = content(32, |x, y| (10.5 - (x - 16.).hypot(y - 16.)).clamp(0., 1.) as f32);
|
||||
let strength = feather_strength(&disk, 0.01);
|
||||
for (pixel, strength) in disk.data.iter().zip(&strength.data) {
|
||||
if pixel[3] > 0. {
|
||||
assert!(*strength > 0.98, "a pixel of alpha {} keeps only {strength}", pixel[3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,176 @@
|
||||
//! The CPU steps of the layer styles' finer options: the outline's paints, and the bevel's contour and texture.
|
||||
|
||||
use crate::effect_kernels::{NEGLIGIBLE_LENGTH, Plane};
|
||||
use core_types::Color;
|
||||
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
||||
use glam::{DVec2, DVec3};
|
||||
use graphic_types::effects::{
|
||||
ANTIALIASED_CONTOUR_OFFSETS, BEVEL_FOOT_FADE, BevelStyle, GRADIENT_TABLE_SIZE, GlowFill, bevel_lighting, bevel_lit, contour_end_slopes, contour_gradient_position, extended_contour,
|
||||
slope_contour_input, slope_contour_reshapes, texture_gray,
|
||||
};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// An outline's coverage outside the content's edge and inside it, where it reaches, and each pixel's place across it for a contour gradient.
|
||||
pub(super) struct OutlineBands {
|
||||
pub outside: Option<Plane<f32>>,
|
||||
pub inside: Option<Plane<f32>>,
|
||||
pub positions: Option<Plane<f32>>,
|
||||
}
|
||||
|
||||
/// The bands of an outline reaching `outside` pixels past the edge of the `silhouette` and `inside` pixels within it.
|
||||
/// With a contour gradient's `start` and `span` in pixels (see `contour_gradient_span`), it also places each pixel across the outline.
|
||||
/// Both bands grow by chamfer distances, which also measure each pixel's center from the edge for its place. O(width × height × log(weight)).
|
||||
pub(super) fn outline_bands(silhouette: &Plane<f32>, outside: f64, inside: f64, contour_gradient: Option<(f64, f64)>) -> OutlineBands {
|
||||
let outward = (outside >= NEGLIGIBLE_LENGTH || contour_gradient.is_some()).then(|| silhouette.distances_to_silhouette(outside + 1.));
|
||||
let inward = (inside >= NEGLIGIBLE_LENGTH || contour_gradient.is_some()).then(|| silhouette.map(|alpha| 1. - alpha).distances_to_silhouette(inside + 1.));
|
||||
|
||||
// The silhouette grown by the band's width, as `Plane::grown` grows it
|
||||
let band = |distances: &Option<Plane<f32>>, width: f64| {
|
||||
let reach = width as f32 + 1.;
|
||||
distances
|
||||
.as_ref()
|
||||
.filter(|_| width >= NEGLIGIBLE_LENGTH)
|
||||
.map(|distances| distances.map(|nearest| (reach - nearest).clamp(0., 1.)))
|
||||
};
|
||||
|
||||
// Each pixel's center lies half a pixel short of its distance from the edge, inside or out
|
||||
let positions = match (&outward, &inward, contour_gradient) {
|
||||
(Some(outward), Some(inward), Some((start, span))) => Some(outward.zip(inward, |outward, inward| {
|
||||
let signed_distance = (outward - 0.5).max(0.) - (inward - 0.5).max(0.);
|
||||
contour_gradient_position(signed_distance, start as f32, span as f32)
|
||||
})),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
OutlineBands {
|
||||
outside: band(&outward, outside),
|
||||
inside: band(&inward, inside),
|
||||
positions,
|
||||
}
|
||||
}
|
||||
|
||||
/// The premultiplied gamma-encoded color of a contour `gradient` at each pixel's place across the outline, from the same table of samples the other renderers read.
|
||||
pub(super) fn contour_gradient_colors(gradient: &GlowFill, positions: &Plane<f32>) -> Plane<[f32; 4]> {
|
||||
let Some((samples, opacity)) = gradient.gradient_samples(GRADIENT_TABLE_SIZE) else {
|
||||
return positions.map(|_| [0.; 4]);
|
||||
};
|
||||
let last = GRADIENT_TABLE_SIZE - 1;
|
||||
|
||||
positions.map(|position| {
|
||||
let [red, green, blue, alpha] = samples[((position * last as f32).round() as usize).min(last)];
|
||||
let alpha = alpha * opacity;
|
||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||
})
|
||||
}
|
||||
|
||||
/// The gray of a bevel's texture at each pixel of a plane `width` by `height`, from its `colors` premultiplied in 8 bits as the GPU draws it.
|
||||
pub(super) fn texture_grays(colors: Vec<Color>, width: usize, height: usize) -> Plane<f32> {
|
||||
let data = colors
|
||||
.into_iter()
|
||||
.map(|color| {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
texture_gray([red * alpha, green * alpha, blue * alpha, alpha].map(|channel| (channel * 255.).round() / 255.))
|
||||
})
|
||||
.collect();
|
||||
Plane { width, height, data }
|
||||
}
|
||||
|
||||
/// What shapes a bevel's surface besides its height: a contour reshaping its slopes across a percentage of them, and a texture's gray sinking it by a percentage of its span.
|
||||
pub(super) struct BevelSurface<'a> {
|
||||
pub style: BevelStyle,
|
||||
pub slope_contour: &'a TransferCurve,
|
||||
pub slope_range: f64,
|
||||
/// Whether the slope contour is sampled at nine points across each pixel.
|
||||
pub slope_antialiased: bool,
|
||||
pub texture: Option<Plane<f32>>,
|
||||
pub texture_depth: f64,
|
||||
}
|
||||
|
||||
/// The offsets toward a pixel's right and lower neighbors at which an antialiased contour samples it, or just the pixel itself.
|
||||
fn sample_offsets(antialiased: bool) -> Vec<[f64; 2]> {
|
||||
match antialiased {
|
||||
true => ANTIALIASED_CONTOUR_OFFSETS.iter().flat_map(|&y| ANTIALIASED_CONTOUR_OFFSETS.map(|x| [x, y])).collect(),
|
||||
false => vec![[0., 0.]],
|
||||
}
|
||||
}
|
||||
|
||||
/// A plane's value at `offset` from the pixel at `x` and `y` toward its right and lower neighbors, interpolated between them and holding the edge pixels beyond the edges.
|
||||
fn sample_between(plane: &Plane<f32>, x: isize, y: isize, [offset_x, offset_y]: [f64; 2]) -> f64 {
|
||||
let (columns, rows) = (plane.width as isize, plane.height as isize);
|
||||
let at = |x: isize, y: isize| plane.data[(y.clamp(0, rows - 1) * columns + x.clamp(0, columns - 1)) as usize] as f64;
|
||||
|
||||
let top = at(x, y) * (1. - offset_x) + at(x + 1, y) * offset_x;
|
||||
let bottom = at(x, y + 1) * (1. - offset_x) + at(x + 1, y + 1) * offset_x;
|
||||
top * (1. - offset_y) + bottom * offset_y
|
||||
}
|
||||
|
||||
/// How much each pixel of a bevel's surface is lit by the `light` past a flat surface's brightness (its highlight), and how much it falls short (its shadow), each from 0 to 1.
|
||||
/// The surface's `height` runs from -0.5 at the slopes' foot to 0.5 at their top, which rise `rise` pixels as the `surface` options shape them, and it's lit through the `gloss` contour, antialiased if paired with true.
|
||||
/// For PSD interop, a slope is the difference across a pixel's neighbors averaged over the three rows or columns they span, and antialiasing averages nine samples offset toward the right and lower neighbors.
|
||||
/// O(width × height), nine times over when antialiased.
|
||||
pub(super) fn bevel_shading(height: &Plane<f32>, surface: &BevelSurface, rise: f64, light: DVec3, gloss: Option<&(TransferCurveEvaluator, bool)>) -> [Plane<f32>; 2] {
|
||||
let (columns, rows) = (height.width as isize, height.height as isize);
|
||||
let reshaped = slope_contour_reshapes(surface.slope_contour, surface.style, surface.slope_range);
|
||||
let contour = surface.slope_contour.evaluator();
|
||||
let slopes = contour_end_slopes(&contour);
|
||||
let texture_depth = surface.texture_depth / 100.;
|
||||
|
||||
// The surface's height in units of its span at an offset from a pixel, reshaped by the contour and sunk by the texture
|
||||
let surface_at = |x: isize, y: isize, offset: [f64; 2]| {
|
||||
let t = sample_between(height, x, y, offset) + 0.5;
|
||||
let shaped = match reshaped {
|
||||
true => extended_contour(&contour, slopes, slope_contour_input(t, surface.style, surface.slope_range)),
|
||||
false => t,
|
||||
};
|
||||
shaped - surface.texture.as_ref().map_or(0., |texture| texture_depth * sample_between(texture, x, y, offset))
|
||||
};
|
||||
|
||||
// How much brighter than flat ground each pixel is lit, averaged over the antialiased contour's samples, each lighting a whole grid of the surface offset alike
|
||||
let offsets = sample_offsets(surface.slope_antialiased && reshaped);
|
||||
let mut brighter = Plane::<f32>::new(height.width, height.height);
|
||||
for &offset in &offsets {
|
||||
let mut shifted = Plane::<f32>::new(height.width, height.height);
|
||||
fill_rows(&mut shifted.data, height.width, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, value)| *value = surface_at(x as isize, y as isize, offset) as f32)
|
||||
});
|
||||
|
||||
let at = |x: isize, y: isize| shifted.data[(y.clamp(0, rows - 1) * columns + x.clamp(0, columns - 1)) as usize] as f64;
|
||||
fill_rows(&mut brighter.data, height.width, |y, row| {
|
||||
let y = y as isize;
|
||||
for (x, brighter) in row.iter_mut().enumerate() {
|
||||
let x = x as isize;
|
||||
let across = at(x + 1, y - 1) + at(x + 1, y) + at(x + 1, y + 1) - at(x - 1, y - 1) - at(x - 1, y) - at(x - 1, y + 1);
|
||||
let down = at(x - 1, y + 1) + at(x, y + 1) + at(x + 1, y + 1) - at(x - 1, y - 1) - at(x, y - 1) - at(x + 1, y - 1);
|
||||
*brighter += ((bevel_lit(DVec2::new(across, down) * rise / 6., light) - light.z) / offsets.len() as f64) as f32;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// The gloss contour reshapes how lit each pixel is, averaged likewise over samples toward its neighbors when antialiased
|
||||
let brighter = match gloss {
|
||||
Some((gloss, antialiased)) => {
|
||||
let offsets = sample_offsets(*antialiased);
|
||||
let mut glossy = Plane::<f32>::new(height.width, height.height);
|
||||
fill_rows(&mut glossy.data, height.width, |y, row| {
|
||||
for (x, value) in row.iter_mut().enumerate() {
|
||||
let lit = |offset| gloss.evaluate(sample_between(&brighter, x as isize, y as isize, offset) + light.z).clamp(0., 1.);
|
||||
*value = (offsets.iter().map(|&offset| lit(offset)).sum::<f64>() / offsets.len() as f64 - light.z) as f32;
|
||||
}
|
||||
});
|
||||
glossy
|
||||
}
|
||||
None => brighter,
|
||||
};
|
||||
|
||||
let amounts = brighter.map(|brighter| {
|
||||
let (highlight, shadow) = bevel_lighting(brighter as f64, light.z);
|
||||
[highlight as f32, shadow as f32, 0., 0.]
|
||||
});
|
||||
[amounts.map(|[highlight, ..]| highlight), amounts.map(|[_, shadow, ..]| shadow)]
|
||||
}
|
||||
|
||||
/// A bevel's highlight and shadow `amounts` beneath the content, faded out across the slopes' foot by their `height` (from -0.5 at the foot), as a gloss contour or texture needs.
|
||||
/// For PSD interop, that keeps the flat ground they shade from reaching past the foot.
|
||||
pub(super) fn foot_faded(amounts: [Plane<f32>; 2], height: &Plane<f32>) -> [Plane<f32>; 2] {
|
||||
amounts.map(|amount| amount.zip(height, |amount, height| amount.min((height + 0.5) / BEVEL_FOOT_FADE as f32)))
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! A value read on its own has no pixels for the image operations among the effects (like blurs and shadows) to act on, so those are skipped.
|
||||
|
||||
use crate::adjustments::{PreparedAdjustment, adjust_color};
|
||||
use crate::blending::overlay_paint;
|
||||
use core_types::Color;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
|
||||
@@ -33,27 +34,66 @@ pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color {
|
||||
adjustments.iter().fold(color, |color, adjustment| adjust_color(adjustment, color))
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` in order on any number of colors, with each one's kernel prepared once.
|
||||
fn prepared(adjustments: &[Adjustment]) -> impl Fn(Color) -> Color {
|
||||
let adjustments: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
move |color| adjustments.iter().fold(color, |color, adjustment| adjustment.adjust(color))
|
||||
/// The color an endless paint of `color` shows with `adjustments` carried out over it and its `fill` fading it, though not the paint overlays painted over it.
|
||||
/// Without edges, each paint overlay blends with the paint itself, which is exact where the paint is opaque.
|
||||
pub fn filled_color(color: Color, adjustments: &[Adjustment], fill: f32) -> Color {
|
||||
if fill >= 1. {
|
||||
return adjusted_color(color, adjustments);
|
||||
}
|
||||
fill_through(color, adjustments, fill, |index, color| adjust_color(&adjustments[index], color))
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` over a paint faded by `fill` as [`filled_color`] does, with `adjust` carrying out each one besides a paint overlay, given its index.
|
||||
fn fill_through(color: Color, adjustments: &[Adjustment], fill: f32, adjust: impl Fn(usize, Color) -> Color) -> Color {
|
||||
// The color at full strength, which each paint overlay blends with, and the color the fill fades, which it paints over at full strength
|
||||
let (mut full, mut filled) = (color, color.with_alpha(color.a() * fill));
|
||||
for (index, adjustment) in adjustments.iter().enumerate() {
|
||||
let Adjustment::ColorOverlay { color: paint, blend_mode, opacity } = *adjustment else {
|
||||
(full, filled) = (adjust(index, full), adjust(index, filled));
|
||||
continue;
|
||||
};
|
||||
|
||||
let strength = paint.a() * (opacity / 100.) as f32;
|
||||
let [red, green, blue, _] = overlay_paint(full, paint.with_alpha(1.), blend_mode, 1.).to_gamma_srgb_channels();
|
||||
let [under_red, under_green, under_blue, under_alpha] = filled.to_gamma_srgb_channels();
|
||||
|
||||
// Premultiplied, the blended paint covers the full-strength content's alpha by its strength, over what it leaves of the faded color
|
||||
let (painted, kept) = (strength * full.a(), under_alpha * (1. - strength));
|
||||
let alpha = painted + kept;
|
||||
let mix = |over: f32, under: f32| if alpha > 0. { (over * painted + under * kept) / alpha } else { 0. };
|
||||
filled = Color::from_gamma_srgb_channels(mix(red, under_red), mix(green, under_green), mix(blue, under_blue), alpha);
|
||||
full = overlay_paint(full, paint, blend_mode, (opacity / 100.) as f32);
|
||||
}
|
||||
filled
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` in order on any number of colors with the `fill` fading them, with each one's kernel prepared once.
|
||||
fn prepared(adjustments: &[Adjustment], fill: f32) -> Box<dyn Fn(Color) -> Color> {
|
||||
let kernels: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
if fill >= 1. {
|
||||
return Box::new(move |color| kernels.iter().fold(color, |color, kernel| kernel.adjust(color)));
|
||||
}
|
||||
|
||||
let adjustments = adjustments.to_vec();
|
||||
Box::new(move |color| fill_through(color, &adjustments, fill, |index, color| kernels[index].adjust(color)))
|
||||
}
|
||||
|
||||
/// The gradient with `adjustments` carried out along its ramp, with the settings to read the result with, or `None` if there are no adjustments.
|
||||
/// A `fill` below 1 fades the ramp but not the paint overlays over it, as for an endless gradient drawn with its fill opacity.
|
||||
/// A stepped ramp holds each stop's color, so adjusting the stops is exact. Elsewhere an adjustment can bend the ramp between stops,
|
||||
/// so the adjusted ramp is resampled into stops that interpolate linearly in gamma.
|
||||
pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjustments: &[Adjustment]) -> Option<(Gradient, GradientSettings)> {
|
||||
pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjustments: &[Adjustment], fill: f32) -> Option<(Gradient, GradientSettings)> {
|
||||
if adjustments.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// A gradient without stops reads as black, so its adjusted ramp is one stop of the adjusted black
|
||||
if gradient.is_empty() {
|
||||
return Some((Gradient::from(vec![prepared(adjustments)(Color::BLACK)]), settings));
|
||||
return Some((Gradient::from(vec![prepared(adjustments, fill)(Color::BLACK)]), settings));
|
||||
}
|
||||
|
||||
if settings.interpolation == GradientInterpolation::Stepped {
|
||||
let adjust = prepared(adjustments);
|
||||
let adjust = prepared(adjustments, fill);
|
||||
return Some((gradient.map_colors(|color| adjust(*color)), settings));
|
||||
}
|
||||
|
||||
@@ -62,6 +102,7 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
|
||||
gradient.cache_hash(&mut hasher);
|
||||
settings.cache_hash(&mut hasher);
|
||||
adjustments.iter().for_each(|adjustment| adjustment.cache_hash(&mut hasher));
|
||||
hasher.write_u32(fill.to_bits());
|
||||
let key = hasher.finish();
|
||||
|
||||
// A lock poisoned by a panic elsewhere still guards a usable cache
|
||||
@@ -73,7 +114,7 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
|
||||
return Some(result);
|
||||
}
|
||||
|
||||
let resampled = gradient.map_ramp(settings, prepared(adjustments));
|
||||
let resampled = gradient.map_ramp(settings, prepared(adjustments, fill));
|
||||
let resampled_settings = GradientSettings {
|
||||
space: GradientSpace::RgbGamma,
|
||||
interpolation: GradientInterpolation::Linear,
|
||||
@@ -110,7 +151,7 @@ pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
||||
let settings = GradientSettings::from_item_attributes(&item);
|
||||
|
||||
let mut item = item;
|
||||
let settings = match adjusted_gradient(item.element(), settings, &adjustments) {
|
||||
let settings = match adjusted_gradient(item.element(), settings, &adjustments, 1.) {
|
||||
Some((gradient, adjusted_settings)) => {
|
||||
*item.element_mut() = gradient;
|
||||
adjusted_settings
|
||||
@@ -129,13 +170,40 @@ pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::blending::BlendMode;
|
||||
|
||||
fn gamma(color: Color) -> [f32; 4] {
|
||||
color.to_gamma_srgb_channels()
|
||||
}
|
||||
|
||||
fn close(actual: [f32; 4], expected: [f32; 4]) -> bool {
|
||||
actual.iter().zip(expected).all(|(actual, expected)| (actual - expected).abs() < 1e-4)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlays_mix_in_gamma_unfaded_by_the_fill() {
|
||||
let half_white = [Adjustment::ColorOverlay {
|
||||
color: Color::WHITE,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
}];
|
||||
|
||||
// Half of white over black is the middle gray of gamma-encoded channels
|
||||
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 1.)), [0.5, 0.5, 0.5, 1.]));
|
||||
|
||||
// With no fill, the black is gone, but the overlay still paints at half strength
|
||||
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.)), [1., 1., 1., 0.5]));
|
||||
|
||||
// At half fill, the overlay covers half and the faded black shows through a quarter
|
||||
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_without_stops_adjusts_the_black_it_reads_as() {
|
||||
let empty = Gradient::from(Vec::<Color>::new());
|
||||
for interpolation in [GradientInterpolation::default(), GradientInterpolation::Stepped] {
|
||||
let settings = GradientSettings { interpolation, ..Default::default() };
|
||||
let adjusted = adjusted_gradient(&empty, settings, &[Adjustment::Invert]).map(|(gradient, _)| gradient);
|
||||
let adjusted = adjusted_gradient(&empty, settings, &[Adjustment::Invert], 1.).map(|(gradient, _)| gradient);
|
||||
assert_eq!(adjusted, Some(Gradient::from(vec![Color::WHITE])), "{interpolation:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,6 +158,39 @@ impl<P: Pixel> Image<P> {
|
||||
}
|
||||
|
||||
impl Image<Color> {
|
||||
/// The color at a point in pixel coordinates, interpolating the four nearest pixel centers by their alpha.
|
||||
/// Like the renderer draws images, it's transparent outside the image and takes the edge pixels' colors out to its edges.
|
||||
pub fn sample_bilinear(&self, point: DVec2) -> Color {
|
||||
// Also rejects NaN and far-off points before they become pixel indices
|
||||
let size = DVec2::new(self.width as f64, self.height as f64);
|
||||
if !(point.cmpge(DVec2::ZERO).all() && point.cmplt(size).all()) {
|
||||
return Color::TRANSPARENT;
|
||||
}
|
||||
|
||||
let point = point.clamp(DVec2::splat(0.5), size - 0.5);
|
||||
let corner = (point - 0.5).floor();
|
||||
let fraction = (point - 0.5 - corner).as_vec2();
|
||||
|
||||
let premultiplied_at = |offset_x: i64, offset_y: i64| {
|
||||
let (x, y) = (corner.x as i64 + offset_x, corner.y as i64 + offset_y);
|
||||
if x < 0 || y < 0 || x >= self.width as i64 || y >= self.height as i64 {
|
||||
return [0.; 4];
|
||||
}
|
||||
let Some(&color) = self.data.get((y * self.width as i64 + x) as usize) else { return [0.; 4] };
|
||||
[color.r() * color.a(), color.g() * color.a(), color.b() * color.a(), color.a()]
|
||||
};
|
||||
let lerp = |a: [f32; 4], b: [f32; 4], t: f32| std::array::from_fn::<f32, 4, _>(|channel| a[channel] + (b[channel] - a[channel]) * t);
|
||||
|
||||
let top = lerp(premultiplied_at(0, 0), premultiplied_at(1, 0), fraction.x);
|
||||
let bottom = lerp(premultiplied_at(0, 1), premultiplied_at(1, 1), fraction.x);
|
||||
let [red, green, blue, alpha] = lerp(top, bottom, fraction.y);
|
||||
|
||||
match alpha > 0. {
|
||||
true => Color::from_rgbaf32_unchecked(red / alpha, green / alpha, blue / alpha, alpha),
|
||||
false => Color::TRANSPARENT,
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate Image from some frontend image data (the canvas pixels as u8s in a flat array)
|
||||
pub fn from_image_data(image_data: &[u8], width: u32, height: u32) -> Self {
|
||||
let data = image_data
|
||||
|
||||
@@ -26,7 +26,6 @@ brush-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
graphene-application-io = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
@@ -39,8 +38,6 @@ vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
glifo = { workspace = true }
|
||||
krilla = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
parley = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
|
||||
@@ -74,7 +74,7 @@ fn marked_span(svg: &str, opening: &str, closing: &str) -> Option<std::ops::Rang
|
||||
pub struct EffectMap {
|
||||
/// Names the markers around the placeholder in the SVG, which the map replaces.
|
||||
pub id: u64,
|
||||
/// The item with its effects, but without its opacity and blend mode, which don't touch its effects' coverages.
|
||||
/// The item with its effects, keeping its opacity and blend mode when its effects are layered, since they set how strongly the content knocks out the pieces.
|
||||
pub content: Graphic,
|
||||
pub render_params: RenderParams,
|
||||
pub capture: EffectCapture,
|
||||
@@ -112,10 +112,11 @@ fn map_markers(id: u64) -> (String, String) {
|
||||
(format!("<!--effect-map-{id}-->"), format!("<!--/effect-map-{id}-->"))
|
||||
}
|
||||
|
||||
/// The filter primitive standing for the map `id` names until it's resolved, which leaves nothing covered.
|
||||
pub(crate) fn map_placeholder(id: u64, result: &str) -> String {
|
||||
/// The filter primitive standing for the map `id` names until it's resolved, covering everything to the `coverage` from 0 to 1.
|
||||
/// Coverage that is added leaves the effect out at 0, and coverage the content is multiplied by leaves it out at 1.
|
||||
pub(crate) fn map_placeholder(id: u64, result: &str, coverage: f64) -> String {
|
||||
let (opening, closing) = map_markers(id);
|
||||
format!(r#"{opening}<feFlood flood-opacity="0" result="{result}" />{closing}"#)
|
||||
format!(r#"{opening}<feFlood flood-opacity="{coverage}" result="{result}" />{closing}"#)
|
||||
}
|
||||
|
||||
impl EffectMap {
|
||||
@@ -249,9 +250,12 @@ impl DeferredImage {
|
||||
}
|
||||
|
||||
/// Replaces the markup standing in for an item of deferred content in `svg` with the `image` the GPU rendered of it, adding the image to `image_data` if it's drawn to a canvas.
|
||||
/// Markup repeated in each layer of an ancestor's effects stands in for the content once in each.
|
||||
pub fn substitute_deferred_image(svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, placement: &DeferredImagePlacement, image: &Raster<CPU>) {
|
||||
let (opening, closing) = image_markers(placement.id);
|
||||
let Some(span) = marked_span(svg, &opening, &closing) else { return };
|
||||
if marked_span(svg, &opening, &closing).is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut render = SvgRender::new();
|
||||
render.transform = placement.user_to_document;
|
||||
@@ -262,6 +266,9 @@ pub fn substitute_deferred_image(svg: &mut String, image_data: &mut Vec<(u64, Ca
|
||||
};
|
||||
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
|
||||
|
||||
svg.replace_range(span, &render.svg.to_svg_string());
|
||||
let markup = render.svg.to_svg_string();
|
||||
while let Some(span) = marked_span(svg, &opening, &closing) {
|
||||
svg.replace_range(span, &markup);
|
||||
}
|
||||
image_data.extend(render.image_data);
|
||||
}
|
||||
@@ -21,7 +21,7 @@ pub enum PaintTarget {
|
||||
}
|
||||
|
||||
impl PaintTarget {
|
||||
pub(crate) fn paint_attr(self) -> &'static str {
|
||||
fn paint_attr(self) -> &'static str {
|
||||
match self {
|
||||
Self::Fill => "fill",
|
||||
Self::Stroke => "stroke",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,281 @@
|
||||
//! SVG masks of content by another graphic: SVG's own `<mask>` for the masks before and after the other effects, and filter primitives for those between them.
|
||||
//! Both forms run the same steps as the GPU's passes: the coverage, its feather, then its density.
|
||||
|
||||
use super::{ENDLESS_EXTENT, Render, RenderParams, RenderSvgSegmentList, SvgFilterPrimitives, SvgRender, drawn_bounding_box, nested_effects_reach, svg_drawn_paint, svg_effects_region};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::bounds::RenderBoundingBox;
|
||||
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effects::{EffectOperation, Effects, spans_along_axes};
|
||||
use graphic_types::masks::{MaskMode, mask_density_line, mask_feather_sigma};
|
||||
use graphic_types::{Appearance, Graphic};
|
||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||
use std::fmt::Write;
|
||||
use std::ops::Range;
|
||||
|
||||
/// One mask row for SVG's own mask: its settings, its graphic's markup, and the region of the user space its strength is worked out over.
|
||||
struct NativeMask<'a> {
|
||||
mode: MaskMode,
|
||||
density: f64,
|
||||
/// The feather's standard deviation along each axis of the user space.
|
||||
sigma: DVec2,
|
||||
invert: bool,
|
||||
markup: &'a str,
|
||||
region: [DVec2; 2],
|
||||
}
|
||||
|
||||
/// The ranges of the effects' masks that lead all their other effects and that trail them, which SVG's own masks carry out around the filter.
|
||||
pub(super) fn native_masks(effects: &Effects) -> (Range<usize>, Range<usize>) {
|
||||
let is_mask = |operation: &EffectOperation| matches!(operation, EffectOperation::Mask { .. });
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
|
||||
let leading = operations.iter().take_while(|operation| is_mask(operation)).count();
|
||||
let trailing = operations[leading..].iter().rev().take_while(|operation| is_mask(operation)).count();
|
||||
(0..leading, operations.len() - trailing..operations.len())
|
||||
}
|
||||
|
||||
/// The standard deviation along each axis of the user space of the Gaussian softening a mask by its `feather`, or zero for a feather too small to show, judged in the document as the GPU judges it in pixels.
|
||||
pub(super) fn svg_feather_sigma(feather: f64, length_scale: DVec2) -> DVec2 {
|
||||
let sigma = mask_feather_sigma(feather) * length_scale;
|
||||
if sigma.max_element() < NEGLIGIBLE_LENGTH { DVec2::ZERO } else { sigma }
|
||||
}
|
||||
|
||||
/// Whether the graphic, anything nested in it, or any paint its appearance fills or strokes them with, carries effects.
|
||||
pub(super) fn holds_effects(graphic: &Graphic) -> bool {
|
||||
fn row_holds_effects(effects: Option<&Effects>, appearance: Option<&Appearance>) -> bool {
|
||||
effects.is_some() || appearance.is_some_and(|appearance| appearance.covers_with_paints().any(|(_, paint)| paint.is_some_and(holds_effects)))
|
||||
}
|
||||
fn list_holds_effects<T>(list: &List<T>, nested: impl Fn(&T) -> bool) -> bool {
|
||||
(0..list.len()).any(|index| row_holds_effects(list.attribute(ATTR_EFFECTS, index), list.attribute(ATTR_APPEARANCE, index)) || list.element(index).is_some_and(&nested))
|
||||
}
|
||||
fn item_holds_effects<T>(item: &Item<T>) -> bool {
|
||||
row_holds_effects(item.attribute(ATTR_EFFECTS), item.attribute(ATTR_APPEARANCE))
|
||||
}
|
||||
|
||||
match graphic {
|
||||
Graphic::None(_) | Graphic::NoneList(_) | Graphic::StrokeList(_) => false,
|
||||
Graphic::Graphic(item) => item_holds_effects(item) || holds_effects(item.element()),
|
||||
Graphic::Vector(item) => item_holds_effects(item),
|
||||
Graphic::RasterCPU(item) => item_holds_effects(item),
|
||||
Graphic::RasterGPU(item) => item_holds_effects(item),
|
||||
Graphic::Color(item) => item_holds_effects(item),
|
||||
Graphic::Gradient(item) => item_holds_effects(item),
|
||||
Graphic::Generator(item) => item_holds_effects(item),
|
||||
Graphic::Text(item) => item_holds_effects(item),
|
||||
Graphic::GraphicList(list) => list_holds_effects(list, holds_effects),
|
||||
Graphic::VectorList(list) => list_holds_effects(list, |_| false),
|
||||
Graphic::RasterCPUList(list) => list_holds_effects(list, |_| false),
|
||||
Graphic::RasterGPUList(list) => list_holds_effects(list, |_| false),
|
||||
Graphic::ColorList(list) => list_holds_effects(list, |_| false),
|
||||
Graphic::GradientList(list) => list_holds_effects(list, |_| false),
|
||||
Graphic::GeneratorList(list) => list_holds_effects(list, |_| false),
|
||||
Graphic::TextList(list) => list_holds_effects(list, |_| false),
|
||||
}
|
||||
}
|
||||
|
||||
/// A mask's graphic placed by its content's `placement`, which it follows.
|
||||
pub(super) fn placed(mask: &Graphic, placement: DAffine2) -> Graphic {
|
||||
Graphic::Graphic(Box::new(Item::new_from_element(mask.clone()).with_attribute(ATTR_TRANSFORM, placement)))
|
||||
}
|
||||
|
||||
/// Writes into `svg_defs` the masks for the effects in each of the `ranges`, given the markup of the graphics the effects draw with in order, and the content's `bounds` in the user space, which is the effects' own.
|
||||
/// Returns the reference to each range's mask, which shows the content as much as all its masks together do.
|
||||
pub(super) fn write_native_masks(svg_defs: &mut String, effects: &Effects, ranges: [Range<usize>; 2], paints: &[String], bounds: [DVec2; 2]) -> [Option<String>; 2] {
|
||||
let length_scale = DVec2::ONE;
|
||||
let region = svg_effects_region(effects, bounds, length_scale);
|
||||
|
||||
// Each mask row by its place in the effects, with its graphic's markup
|
||||
let mut paints = paints.iter();
|
||||
let masks: Vec<(usize, NativeMask)> = effects
|
||||
.operations()
|
||||
.enumerate()
|
||||
.filter_map(|(index, operation)| {
|
||||
let paint = svg_drawn_paint(&operation).and_then(|_| paints.next());
|
||||
let EffectOperation::Mask { mode, density, feather, invert, .. } = operation else { return None };
|
||||
let sigma = svg_feather_sigma(feather, length_scale);
|
||||
Some((
|
||||
index,
|
||||
NativeMask {
|
||||
mode,
|
||||
density,
|
||||
sigma,
|
||||
invert,
|
||||
markup: paint?,
|
||||
region,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
|
||||
ranges.map(|range| {
|
||||
let in_range: Vec<&NativeMask> = masks.iter().filter(|(index, _)| range.contains(index)).map(|(_, mask)| mask).collect();
|
||||
write_combined_mask(svg_defs, &in_range, false)
|
||||
})
|
||||
}
|
||||
|
||||
/// The extent in the user space that the leading masks of content without edges (like a color or gradient filling everything) confine it to, with the reach of their feathers, given the content's `placement` there.
|
||||
/// `None` unless the first effect is such a mask: not inverted, at full density, with a graphic of bounded extent. Each such mask after it narrows the extent.
|
||||
pub(super) fn masked_extent(effects: &Effects, placement: DAffine2) -> Option<[DVec2; 2]> {
|
||||
// TODO: Masks that cut holes (like an inverted one) leave the content endless, so both renderers skip its other effects (blurs, shadows, feathers) at the holes' edges.
|
||||
// Carry those effects out over the area in view when masks give the content edges without confining it.
|
||||
let mut extent: Option<[DVec2; 2]> = None;
|
||||
for (operation, length_scale) in effects.operations().zip(effects.length_spans(placement)) {
|
||||
let EffectOperation::Mask { mask, density, feather, invert, .. } = operation else { break };
|
||||
let RenderBoundingBox::Rectangle([min, max]) = drawn_bounding_box(&mask, placement) else { break };
|
||||
if invert || density < 100. {
|
||||
break;
|
||||
}
|
||||
|
||||
let reach = 3. * svg_feather_sigma(feather, length_scale) + nested_effects_reach(&mask, placement, EffectOperation::painted_reach);
|
||||
let [min, max] = [min - reach, max + reach];
|
||||
extent = Some(match extent {
|
||||
// Masks that don't overlap leave an empty extent at the first one's corner
|
||||
Some([extent_min, extent_max]) => {
|
||||
let narrowed_min = extent_min.max(min);
|
||||
[narrowed_min, extent_max.min(max).max(narrowed_min)]
|
||||
}
|
||||
None => [min, max],
|
||||
});
|
||||
}
|
||||
extent
|
||||
}
|
||||
|
||||
/// Writes into the defs the mask carrying out the mask rows among the effects of content without edges, like a color or gradient filling everything, placed by `placement`, or `None` if there are none.
|
||||
/// This is for masks that leave the content without edges, so SVG leaves the other effects undone as it does for such content. Each mask's strength is worked out where its graphic reaches.
|
||||
pub(super) fn write_endless_content_mask(render: &mut SvgRender, effects: &Effects, placement: DAffine2, render_params: &RenderParams) -> Option<String> {
|
||||
// The mask graphics' markup lies in the document, where the maps and images of their own effects reach it
|
||||
let live_params = RenderParams {
|
||||
inherited_appearance: None,
|
||||
embeds_images: true,
|
||||
..render_params.clone()
|
||||
};
|
||||
let mut rows = Vec::new();
|
||||
for (operation, length_scale) in effects.operations().zip(effects.length_spans(placement)) {
|
||||
let EffectOperation::Mask {
|
||||
ref mask,
|
||||
mode,
|
||||
density,
|
||||
feather,
|
||||
invert,
|
||||
} = operation
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let feather_reach = operation.reach() * spans_along_axes(render.transform.matrix2).max_element() * length_scale.max_element();
|
||||
let mask = placed(mask, placement);
|
||||
|
||||
// The maps of the mask graphic's own effects cover past the view as far as its feather and the groups around the content read it
|
||||
let mut mask_render = SvgRender::new();
|
||||
mask_render.transform = render.transform;
|
||||
mask_render.ancestors_reach = render.ancestors_reach + feather_reach;
|
||||
mask.render_svg(&mut mask_render, &live_params);
|
||||
render.effect_maps.append(&mut mask_render.effect_maps);
|
||||
render.deferred_images.append(&mut mask_render.deferred_images);
|
||||
let markup = format!("<defs>{}</defs>{}", mask_render.svg_defs, mask_render.svg.to_svg_string());
|
||||
|
||||
let sigma = svg_feather_sigma(feather, length_scale);
|
||||
let region = match drawn_bounding_box(&mask, DAffine2::IDENTITY) {
|
||||
RenderBoundingBox::Rectangle([min, max]) => {
|
||||
let reach = 3. * sigma + nested_effects_reach(&mask, DAffine2::IDENTITY, EffectOperation::painted_reach);
|
||||
[min - reach, max + reach]
|
||||
}
|
||||
_ => [DVec2::splat(-ENDLESS_EXTENT), DVec2::splat(ENDLESS_EXTENT)],
|
||||
};
|
||||
rows.push((mode, density, sigma, invert, markup, region));
|
||||
}
|
||||
|
||||
let masks: Vec<NativeMask> = rows
|
||||
.iter()
|
||||
.map(|(mode, density, sigma, invert, markup, region)| NativeMask {
|
||||
mode: *mode,
|
||||
density: *density,
|
||||
sigma: *sigma,
|
||||
invert: *invert,
|
||||
markup,
|
||||
region: *region,
|
||||
})
|
||||
.collect();
|
||||
write_combined_mask(&mut render.svg_defs, &masks.iter().collect::<Vec<_>>(), true)
|
||||
}
|
||||
|
||||
/// Writes into `svg_defs` one SVG mask showing content as much as all the `masks` together do, returning its reference, or `None` for no masks.
|
||||
/// An `endless` mask spans all content without edges, and past each mask's region shows it as much as that mask does where its graphic is absent. Others end with their regions.
|
||||
fn write_combined_mask(svg_defs: &mut String, masks: &[&NativeMask], endless: bool) -> Option<String> {
|
||||
let placement = |[min, max]: [DVec2; 2]| format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y);
|
||||
let endless_square = format!("M{ENDLESS_EXTENT} {ENDLESS_EXTENT}H-{ENDLESS_EXTENT}V-{ENDLESS_EXTENT}H{ENDLESS_EXTENT}Z");
|
||||
|
||||
// Each mask's content is masked by the next one's, so the outermost shows the content by the product of them all
|
||||
let mut combined: Option<String> = None;
|
||||
for mask in masks.iter().rev() {
|
||||
// Past its region, an endless mask that isn't inverted shows the content by one less its density, drawn everywhere beneath its plain coverage so nothing overlaps along the region's edge.
|
||||
// An inverted one shows all of the content past its region, where its own strength is whole too.
|
||||
let beneath = endless && !mask.invert && mask.density < 100.;
|
||||
let density = if endless && !mask.invert { 100. } else { mask.density };
|
||||
let mut content = match beneath {
|
||||
true => format!(r#"<path d="{endless_square}" fill-opacity="{}" />"#, 1. - (mask.density / 100.).clamp(0., 1.)),
|
||||
false => String::new(),
|
||||
};
|
||||
|
||||
let mut primitives = SvgFilterPrimitives::default();
|
||||
primitives.mask_strength("SourceGraphic", mask.mode, density, mask.sigma, mask.invert);
|
||||
let strength_id = format!("mask-strength-{}", generate_uuid());
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<filter id="{strength_id}" filterUnits="userSpaceOnUse" {} color-interpolation-filters="sRGB">{}</filter>"#,
|
||||
placement(mask.region),
|
||||
primitives.markup
|
||||
);
|
||||
let _ = write!(content, r#"<g filter="url(#{strength_id})">{}</g>"#, mask.markup);
|
||||
|
||||
if endless && mask.invert {
|
||||
let [min, max] = mask.region;
|
||||
let _ = write!(content, r#"<path d="{endless_square}M{} {}H{}V{}H{}Z" fill-rule="evenodd" />"#, min.x, min.y, max.x, max.y, min.x);
|
||||
}
|
||||
|
||||
if let Some(inner) = &combined {
|
||||
content = format!(r#"<g mask="{inner}">{content}</g>"#);
|
||||
}
|
||||
let mask_region = if endless { [DVec2::splat(-ENDLESS_EXTENT), DVec2::splat(ENDLESS_EXTENT)] } else { mask.region };
|
||||
let mask_id = format!("mask-{}", generate_uuid());
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<mask id="{mask_id}" mask-type="alpha" maskUnits="userSpaceOnUse" {}>{content}</mask>"#,
|
||||
placement(mask_region)
|
||||
);
|
||||
combined = Some(format!("url(#{mask_id})"));
|
||||
}
|
||||
combined
|
||||
}
|
||||
|
||||
impl SvgFilterPrimitives {
|
||||
/// The `mode`'s coverage of a mask graphic's `image`, in the alpha of the result, matching the GPU's `mask_coverage`.
|
||||
pub(super) fn mask_coverage(&mut self, image: &str, mode: MaskMode) -> String {
|
||||
match mode {
|
||||
// Over black, the luminance of the opaque result is that of the premultiplied channels
|
||||
MaskMode::Luminance => {
|
||||
let black = self.push("feFlood", r#"flood-color="black""#, "");
|
||||
let opaque = self.push("feComposite", &format!(r#"in="{image}" in2="{black}" operator="over""#), "");
|
||||
self.push("feColorMatrix", &format!(r#"in="{opaque}" type="luminanceToAlpha""#), "")
|
||||
}
|
||||
MaskMode::Alpha => image.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How much the mask graphic's `image` shows the content, in the alpha of the result, matching the GPU's mask passes.
|
||||
/// Its coverage is softened by a Gaussian of standard deviation `sigma` along each axis of the user space (none at zero), then mapped through its `density` percentage, flipped if `invert`.
|
||||
pub(super) fn mask_strength(&mut self, image: &str, mode: MaskMode, density: f64, sigma: DVec2, invert: bool) -> String {
|
||||
let mut coverage = self.mask_coverage(image, mode);
|
||||
|
||||
if sigma != DVec2::ZERO {
|
||||
coverage = self.push("feGaussianBlur", &format!(r#"in="{coverage}" stdDeviation="{} {}""#, sigma.x, sigma.y), "");
|
||||
}
|
||||
|
||||
let (slope, intercept) = mask_density_line(density, invert);
|
||||
self.push(
|
||||
"feComponentTransfer",
|
||||
&format!(r#"in="{coverage}""#),
|
||||
&format!(r#"<feFuncA type="linear" slope="{slope}" intercept="{intercept}" />"#),
|
||||
)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,54 @@
|
||||
//! The SVG filter primitives of the layer styles' finer options: the outline's paints.
|
||||
|
||||
use super::SvgFilterPrimitives;
|
||||
use graphic_types::effects::{EffectCapture, GRADIENT_TABLE_SIZE, GlowFill};
|
||||
|
||||
/// Where an outline painted with something other than a solid color takes its bands' colors from, until they're first needed.
|
||||
pub(super) enum OutlineBandColors {
|
||||
/// The markup of a drawn paint.
|
||||
Drawn(String),
|
||||
ContourGradient(GlowFill),
|
||||
/// The primitive holding the colors, once made.
|
||||
Made(String),
|
||||
}
|
||||
|
||||
impl SvgFilterPrimitives {
|
||||
/// The primitive holding the colors that the outline effect at `index` paints its bands with, made the first time they're needed so a layer showing none of its bands makes none.
|
||||
pub(super) fn outline_band_colors(&mut self, colors: &mut OutlineBandColors, index: usize, region: [glam::DVec2; 2]) -> String {
|
||||
let made = match colors {
|
||||
OutlineBandColors::Made(made) => return made.clone(),
|
||||
OutlineBandColors::Drawn(markup) => self.paint_image(markup, region),
|
||||
OutlineBandColors::ContourGradient(gradient) => {
|
||||
let positions = self.map(EffectCapture { index, plane: 2 });
|
||||
self.contour_gradient_colors(&positions, gradient)
|
||||
}
|
||||
};
|
||||
*colors = OutlineBandColors::Made(made.clone());
|
||||
made
|
||||
}
|
||||
|
||||
/// The colors of a contour `gradient` at each pixel's place across the outline, which the `positions` map holds in its alpha, looked up as the GPU does.
|
||||
pub(super) fn contour_gradient_colors(&mut self, positions: &str, gradient: &GlowFill) -> String {
|
||||
let Some((samples, opacity)) = gradient.gradient_samples(GRADIENT_TABLE_SIZE) else {
|
||||
return positions.to_string();
|
||||
};
|
||||
let table = |value: &dyn Fn(&[f32; 4]) -> f32| samples.iter().map(|sample| format!("{:.4}", value(sample).clamp(0., 1.))).collect::<Vec<_>>().join(" ");
|
||||
|
||||
// The place moves into opaque color channels, which the tables look up the gradient's colors from in gamma
|
||||
let place = self.push("feColorMatrix", &format!(r#"in="{positions}" type="matrix" values="0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1""#), "");
|
||||
let functions = ["R", "G", "B"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(channel, name)| format!(r#"<feFunc{name} type="table" tableValues="{}" />"#, table(&|sample| sample[channel])))
|
||||
.collect::<String>();
|
||||
let colors = self.push("feComponentTransfer", &format!(r#"in="{place}" color-interpolation-filters="sRGB""#), &functions);
|
||||
|
||||
// A translucent gradient's alpha is looked up from the place where the map holds it, since premultiplied color channels lose precision at small places
|
||||
if opacity >= 1. && samples.iter().all(|sample| sample[3] >= 1.) {
|
||||
return colors;
|
||||
}
|
||||
let alpha_function = format!(r#"<feFuncA type="table" tableValues="{}" />"#, table(&|sample| sample[3] * opacity));
|
||||
let alpha = self.push("feComponentTransfer", &format!(r#"in="{positions}""#), &alpha_function);
|
||||
self.push("feComposite", &format!(r#"in="{colors}" in2="{alpha}" operator="in""#), "")
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,8 @@ impl BlendModeExt for BlendMode {
|
||||
BlendMode::Saturation => peniko::Mix::Saturation,
|
||||
BlendMode::Color => peniko::Mix::Color,
|
||||
BlendMode::Luminosity => peniko::Mix::Luminosity,
|
||||
_ => todo!(),
|
||||
// Like SVG, the modes that layers can't blend by fall back to normal
|
||||
_ => peniko::Mix::Normal,
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user