Compare commits

...
Author SHA1 Message Date
Keavon Chambers 1404b36081 Add curvature dials to gradients, rendered as a pencil of circles on Vello GPU 2026-10-30 20:22:06 -07:00
Keavon Chambers 06467de601 Replace Color Overlay with a Paint Overlay effect that paints with any graphic 2026-10-30 20:22:05 -07:00
Keavon Chambers 430b2030ed Add a Generator graphic type that renderers draw at the resolution they need with its kernels 2026-10-30 20:22:05 -07:00
Dennis Kobert 284ca6d509 Load images into CPU rasters by default again 2026-10-30 20:22:05 -07:00
Dennis Kobert 056bec13e5 Upload a CPU raster wire feeding a GPU-only input through its input adapter 2026-10-30 20:22:05 -07:00
Keavon Chambers 06d83843fa Speed up adjusted solid vector paints by folding the adjustments into the paint 2026-10-30 20:22:05 -07:00
Keavon Chambers 28e0112504 Speed up an image's leading adjustments by running them on a copy of its texture 2026-10-30 20:22:05 -07:00
Dennis Kobert 11d097f103 Give GPU rasters drawn smaller than their pixels mipmaps 2026-10-30 20:22:05 -07:00
Keavon Chambers 78e3166d22 Extend adjustments to images, colors, and gradients, stamped on images and carried out at once on colors and gradients 2026-10-30 20:22:05 -07:00
Keavon Chambers 661f37fa17 Allow adjustments on any graphic, carried out on the GPU by their kernels 2026-10-30 20:22:05 -07:00
Keavon Chambers aa7ebfc18c Add a Bevel & Emboss effect lighting the inner, outer, emboss, and pillow slopes 2026-10-30 20:22:05 -07:00
Keavon Chambers 2be0d1889b Add Inner Glow, Satin, and Outline effects to any graphic 2026-10-30 20:22:05 -07:00
Dennis Kobert 3b7d46836d Add an Eager node that uploads a raster and carries out its effects 2026-10-30 20:22:05 -07:00
Keavon Chambers 8f0ef2da8b Add Blur, Drop Shadow, Inner Shadow, and Outer Glow effects to any graphic 2026-10-30 20:22:05 -07:00
Keavon Chambers b88eee543a Move the noise and Mandelbrot kernels into a generator module rendering any area 2026-10-30 20:22:05 -07:00
Keavon Chambers e01f602b13 Upload images with mipmaps so they average their pixels when zoomed out 2026-10-30 20:22:05 -07:00
Keavon Chambers 8fd36852c1 Gather each adjustment's settings into plain data run by its kernel 2026-10-30 20:22:05 -07:00
Dennis Kobert 1bfbd8f4f8 Mark the Dehaze node as footprint invariant 2026-10-30 20:22:05 -07:00
Dennis Kobert c698fb157d Give content that nodes move or copy a footprint covering everywhere it lands 2026-10-30 20:22:05 -07:00
Dennis Kobert 48ee95a802 Keep a GPU raster's logical placement separate from the region its pixels cover 2026-10-30 20:22:05 -07:00
Dennis Kobert f3edba1603 Fall back to half-float rasters where the GPU can't render full floats 2026-10-30 20:22:05 -07:00
Dennis Kobert 7bb28460cc Merge no-std-types into core-types 2026-10-30 20:22:05 -07:00
Dennis Kobert f8c3984b6c Render the Rasterize node with Vello 2026-10-30 20:22:05 -07:00
Dennis Kobert 9ca321fdcf Remove CPU raster paths from raster nodes 2026-10-30 20:22:05 -07:00
Dennis Kobert d53c990f72 Run raster consumers on GPU rasters 2026-10-30 20:22:05 -07:00
Dennis Kobert ecaa5bb906 Load images into GPU rasters 2026-10-30 20:22:05 -07:00
Dennis Kobert fc488dd91f Embed GPU rasters in SVG output by downloading them first 2026-10-30 20:22:05 -07:00
Dennis Kobert a12cbea9fb Shade the Mandelbrot set by smooth escape time 2026-10-30 20:22:05 -07:00
Dennis Kobert 7b0298fe96 Run headless editor tests on a software GPU 2026-10-30 20:22:05 -07:00
Dennis Kobert ceb39a2c5b Give GPU rasters an empty default 2026-10-30 20:22:04 -07:00
Dennis Kobert b9e0df685f Run Dehaze and Image Color Palette on GPU rasters 2026-10-30 20:22:04 -07:00
Dennis Kobert 135b05bacf Run raster nodes on GPU rasters through hand-written WGSL kernels 2026-10-30 20:22:04 -07:00
Keavon Chambers 43316436c2 Port FastNoise Lite to WGSL 2026-10-30 20:22:04 -07:00
182 changed files with 17095 additions and 3471 deletions

No files matched your search

+6 -1
View File
@@ -47,12 +47,17 @@ let
# Plotting tools
pkgs.graphviz
];
libs = [
pkgs.vulkan-loader
];
env = {
VK_ADD_DRIVER_FILES = "${pkgs.mesa}/share/vulkan/icd.d/lvp_icd.${pkgs.stdenv.hostPlatform.uname.processor}.json";
};
}
(lib.optionalAttrs desktop (
{
libs = [
pkgs.wayland
pkgs.vulkan-loader
pkgs.libGL
pkgs.libxkbcommon
self.packages.${system}.graphite-cef
Generated
+29 -79
View File
@@ -893,13 +893,15 @@ dependencies = [
"futures",
"glam",
"graphene-hash",
"half",
"image",
"kurbo",
"log",
"lyon_geom",
"no-std-types",
"node-macro",
"num-derive",
"num-traits",
"num_enum",
"parley",
"petgraph",
"polycool",
@@ -1504,15 +1506,6 @@ dependencies = [
"regex-syntax 0.8.6",
]
[[package]]
name = "fastnoise-lite"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e5f3c3cc9081e5d0e18bcd50e80cd33cba47fc22f88a9da9c33ecd1c87ea5c0"
dependencies = [
"num-traits",
]
[[package]]
name = "fastrand"
version = "2.3.0"
@@ -2172,10 +2165,13 @@ dependencies = [
"dyn-any",
"glam",
"graphene-hash",
"graphene-resource",
"node-macro",
"num_enum",
"raster-types",
"serde",
"serde_json",
"tsify",
"vector-types",
"wasm-bindgen",
]
@@ -3527,16 +3523,6 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "matrixmultiply"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08"
dependencies = [
"autocfg",
"rawpointer",
]
[[package]]
name = "memchr"
version = "2.7.5"
@@ -3660,21 +3646,6 @@ dependencies = [
"thiserror 2.0.18",
]
[[package]]
name = "ndarray"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841"
dependencies = [
"matrixmultiply",
"num-complex",
"num-integer",
"num-traits",
"portable-atomic",
"portable-atomic-util",
"rawpointer",
]
[[package]]
name = "ndk"
version = "0.9.0"
@@ -3723,25 +3694,6 @@ dependencies = [
"libc",
]
[[package]]
name = "no-std-types"
version = "0.0.0"
dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam",
"graphene-hash",
"half",
"log",
"num-derive",
"num-traits",
"num_enum",
"serde",
"tsify",
"wasm-bindgen",
]
[[package]]
name = "node-docs"
version = "0.0.0"
@@ -3761,7 +3713,6 @@ dependencies = [
"convert_case 0.12.0",
"core-types",
"indoc",
"no-std-types",
"proc-macro-crate",
"proc-macro-error2",
"proc-macro2",
@@ -3844,15 +3795,6 @@ dependencies = [
"syn 2.0.106",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -4682,6 +4624,18 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d6831663a5098ea164f89cff59c6284e95f4e3c76ce9848d4529f5ccca9bde"
[[package]]
name = "raster-kernels"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"graphene-resource",
"graphic-types",
"thiserror 2.0.18",
"vector-types",
]
[[package]]
name = "raster-nodes"
version = "0.0.0"
@@ -4690,19 +4644,15 @@ dependencies = [
"color",
"core-types",
"dyn-any",
"fastnoise-lite",
"futures",
"glam",
"graphene-core",
"graphene-hash",
"graphene-resource",
"image",
"ndarray",
"no-std-types",
"graphic-types",
"node-macro",
"num_enum",
"rand",
"rand_chacha",
"raster-kernels",
"raster-types",
"serde",
"thiserror 2.0.18",
@@ -4710,6 +4660,7 @@ dependencies = [
"tsify",
"vector-types",
"wasm-bindgen",
"wgpu-executor",
]
[[package]]
@@ -4750,12 +4701,6 @@ dependencies = [
"objc2-quartz-core",
]
[[package]]
name = "rawpointer"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
[[package]]
name = "rayon"
version = "1.11.0"
@@ -4900,6 +4845,7 @@ dependencies = [
"log",
"num-traits",
"parley",
"raster-kernels",
"serde",
"skrifa",
"text-nodes",
@@ -6545,7 +6491,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -6560,7 +6506,7 @@ dependencies = [
[[package]]
name = "vello_gpu"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"bytemuck",
"hashbrown 0.17.1",
@@ -6574,7 +6520,7 @@ dependencies = [
[[package]]
name = "vello_gpu_shaders"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"naga",
"wesl",
@@ -7025,8 +6971,12 @@ dependencies = [
"futures",
"glam",
"graphene-application-io",
"graphene-resource",
"graphic-types",
"half",
"log",
"node-macro",
"raster-kernels",
"raster-types",
"rendering",
"thiserror 2.0.18",
+4 -5
View File
@@ -81,10 +81,10 @@ 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" }
no-std-types = { path = "node-graph/libraries/no-std-types" }
raster-types = { path = "node-graph/libraries/raster-types" }
vector-types = { path = "node-graph/libraries/vector-types" }
graphic-types = { path = "node-graph/libraries/graphic-types" }
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
brush-types = { path = "node-graph/libraries/brush-types" }
rendering = { path = "node-graph/libraries/rendering" }
brush-nodes = { path = "node-graph/nodes/brush" }
@@ -265,7 +265,6 @@ zip = { version = "8", default-features = false }
opt-level = 1
[profile.dev.package]
no-std-types = { opt-level = 1 }
core-types= { opt-level = 1 }
interpreted-executor = { opt-level = 1 } # This is a mitigation for https://github.com/rustwasm/wasm-pack/issues/981 which is needed because the node_registry function is too large
graphite-proc-macros = { opt-level = 1 }
@@ -282,6 +281,6 @@ debug = true
[patch.crates-io]
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
# TODO: Remove these once the fork's fixes are upstreamed and released
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3,4],[4,1]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplicLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3,4],[4,1]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[322234583139821148,{"inputs":[{"Node":{"node_id":6589978257209505606,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[-261.2435565297001,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"trLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"Integer":0},"exposed":false}},{"Value":{"tagged_value":{"Number":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"Integer":3},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"Number":0.5},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"Number":1.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::NoisePatternNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6565638614909771142,{"inputs":[{"Node":{"node_id":7624113397561636853,"output_index":0}},{"Node":{"node_id":80924370013313595,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"GeLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[4388711862172196665,{"inputs":[{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"Integer":0},"exposed":false}},{"Value":{"tagged_value":{"Number":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"Integer":3},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"Number":0.5},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"Number":1.0},"exposed":false}},{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::NoisePatternNode"}},"visible":true,"skip_deduplication":false}],[6565638614909771142,{"inputs":[{"Node":{"node_id":7624113397561636853,"output_index":0}},{"Node":{"node_id":80924370013313595,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}]Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":1,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"List":{"Concrete":{"nameLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":1,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[4,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}]},"import_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_dedLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Number":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"Number":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Number":4000.0},"exposed":false}},{"Value":{"tagged_value":{"Number":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":1415828794531Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Number":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"Number":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Number":4000.0},"exposed":false}},{"Value":{"tagged_value":{"Number":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false}],[7828034197076821310,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":3}}],"call_argument":{"Concrete":{"name":"core::option::Option<Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_dedupLine truncated
+2 -2
View File
@@ -21,7 +21,7 @@ pub(crate) struct RenderState {
ui_texture: Option<wgpu::Texture>,
bind_group: Option<wgpu::BindGroup>,
#[derivative(Debug = "ignore")]
overlays_scene: Option<VelloSceneBuilder>,
overlays_scene: Option<VelloSceneBuilder<'static>>,
#[derivative(Debug = "ignore")]
overlays_canvas: VelloCanvas,
surface_outdated: bool,
@@ -220,7 +220,7 @@ impl RenderState {
self.viewport_offset = offset;
}
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder<'static>) {
self.surface_outdated = true;
self.overlays_scene = Some(scene);
}
+1 -1
View File
@@ -40,7 +40,7 @@ pub enum DesktopFrontendMessage {
WindowUpdateDirectInput {
enabled: bool,
},
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder>),
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder<'static>>),
PersistenceUpdatePreferences {
preferences: Preferences,
},
@@ -11,6 +11,7 @@ use graphene_std::animation::RealTimeMode;
use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8;
use graphene_std::core_types::misc::format_f64;
use graphene_std::generator::Generator;
use graphene_std::gradient::Gradient;
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
use graphene_std::math::float_noise::round_away_float_noise;
@@ -18,7 +19,7 @@ use graphene_std::raster::{
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::raster_types::{CPU, GPU, Raster, Storage};
use graphene_std::text::TextAlign;
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -32,7 +33,7 @@ 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, Graphic};
use graphene_std::{Appearance, Artboard, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic};
use kurbo::BezPath;
use std::any::Any;
use std::sync::Arc;
@@ -377,6 +378,7 @@ macro_rules! inspectable_types {
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<String>,
List<f64>,
List<i64>,
@@ -433,6 +435,7 @@ macro_rules! inspectable_types {
Item<Raster<GPU>>,
Item<Color>,
Item<Gradient>,
Item<Generator>,
Item<String>,
Item<f64>,
Item<i64>,
@@ -776,6 +779,45 @@ impl TableItemLayout for Coverage {
}
}
impl TableItemLayout for Effects {
fn type_name() -> &'static str {
"Effects"
}
fn identifier(&self) -> String {
"Effects".to_string()
}
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
// Label the spreadsheet's element button with the inner list's identifier, like Appearance
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
self.0.value_widgets(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for Effect {
fn type_name() -> &'static str {
"Effect"
}
fn identifier(&self) -> String {
"Effect".to_string()
}
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
self.0.value_widgets(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for TransferCurve {
fn type_name() -> &'static str {
"TransferCurve"
@@ -841,6 +883,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPU(item) => item.identifier(),
Self::Color(item) => item.identifier(),
Self::Gradient(item) => item.identifier(),
Self::Generator(item) => item.identifier(),
Self::Text(item) => item.identifier(),
Self::NoneList(list) => list.identifier(),
Self::GraphicList(list) => list.identifier(),
@@ -849,6 +892,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPUList(list) => list.identifier(),
Self::ColorList(list) => list.identifier(),
Self::GradientList(list) => list.identifier(),
Self::GeneratorList(list) => list.identifier(),
Self::TextList(list) => list.identifier(),
Self::StrokeList(list) => list.identifier(),
}
@@ -866,6 +910,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
Self::Color(item) => item.layout_with_breadcrumb(data),
Self::Gradient(item) => item.layout_with_breadcrumb(data),
Self::Generator(item) => item.layout_with_breadcrumb(data),
Self::Text(item) => item.layout_with_breadcrumb(data),
Self::NoneList(list) => list.layout_with_breadcrumb(data),
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
@@ -874,6 +919,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data),
Self::ColorList(list) => list.layout_with_breadcrumb(data),
Self::GradientList(list) => list.layout_with_breadcrumb(data),
Self::GeneratorList(list) => list.layout_with_breadcrumb(data),
Self::TextList(list) => list.layout_with_breadcrumb(data),
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
}
@@ -944,9 +990,15 @@ impl TableItemLayout for Raster<GPU> {
"Raster"
}
fn identifier(&self) -> String {
format!("Raster ({} x {})", self.data().width(), self.data().height())
let size = self.size();
format!("Raster ({} x {})", size.x, size.y)
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
if self.is_empty() {
let widgets = vec![TextLabel::new("Image has no area").widget_instance()];
return vec![LayoutGroup::row(widgets)];
}
let widgets = vec![TextLabel::new("This raster data is a texture on the GPU. It currently cannot be displayed here.").widget_instance()];
vec![LayoutGroup::row(widgets)]
}
@@ -1197,6 +1249,11 @@ macro_rules! impl_table_item_layout_for_choice_enum {
impl_table_item_layout_for_choice_enum!(
BlendMode,
Cover,
BevelDirection,
BevelStyle,
EffectKind,
Generator,
GlowSource,
GradientForm,
GradientSpread,
GradientSpace,
@@ -1343,9 +1400,11 @@ macro_rules! known_item_types {
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<String>,
List<f64>,
Gradient,
Generator,
Color,
NodeId,
DAffine2,
@@ -1367,6 +1426,12 @@ macro_rules! known_item_types {
Appearance,
Coverage,
Cover,
Effects,
Effect,
EffectKind,
GlowSource,
BevelStyle,
BevelDirection,
DashPattern,
BoxCorners,
TransferCurve,
@@ -315,6 +315,9 @@ pub enum DocumentMessage {
UpdateAppearanceAttributes {
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
},
UpdateEffectsReach {
effects_reach: HashMap<NodeId, f64>,
},
Undo,
UngroupSelectedLayers,
UngroupLayer {
@@ -1877,6 +1877,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect();
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
}
DocumentMessage::UpdateEffectsReach { effects_reach } => {
let layer_effects_reach = effects_reach
.into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
.collect();
self.network_interface.update_effects_reach(layer_effects_reach);
}
DocumentMessage::Undo => {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
@@ -759,20 +759,26 @@ impl<'a> ModifyInputsContext<'a> {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
/// from the default (`Linear`).
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
let create_if_nonexistent = gradient_form != GradientForm::default();
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
return;
};
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
let [start, end] = match gradient_form {
GradientForm::Linear => LINEAR_DIALS,
GradientForm::Radial => RADIAL_DIALS,
};
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
}
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
@@ -834,6 +834,7 @@ fn static_node_inspector() -> NodeInspector {
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, Graphic, Vector};
use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::{MessagePart, ParseError};
use std::path::PathBuf;
@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
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
// ============
@@ -438,6 +439,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).inspector_row(),
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::<GlowSource>(x) => enum_choice::<GlowSource>().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::<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(),
@@ -1368,8 +1372,8 @@ fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
vec![
concrete!(Graphic),
concrete!(Vector),
concrete!(Raster<CPU>),
concrete!(Raster<GPU>),
concrete!(Raster<CPU>),
concrete!(Color),
concrete!(Gradient),
concrete!(String),
@@ -2997,6 +3001,79 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
}
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::math_nodes::gradient_curvature::*;
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
let curvatures = match get_document_node(node_id, context) {
Ok(document_node) => {
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
Some(&TaggedValue::Number(value)) => Some(value),
_ => None,
};
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
}
Err(err) => {
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
return Vec::new();
}
};
// Each form's button sets both curvatures to the form's own, and stands out while they're exactly those
let mut form = vec![
TextLabel::new("Form")
.tooltip_label("Form")
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
.widget_instance(),
];
add_blank_assist(&mut form);
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
for (label, [start, end], tooltip) in [
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
] {
form.push(
TextButton::new(label)
.tooltip_description(tooltip)
.emphasized(curvatures == Some([start, end]))
.disabled(curvatures.is_none())
.on_update(move |_: &TextButton| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: StartCurvatureInput::INDEX,
value: TaggedValue::Number(start).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: EndCurvatureInput::INDEX,
value: TaggedValue::Number(end).into(),
}
.into(),
]),
})
.on_commit(commit_value)
.widget_instance(),
);
}
// The same sliders the curvatures would get without this panel
let options = ParameterOptions {
soft_min: Some(-1.),
soft_max: Some(1.),
slider: true,
..Default::default()
};
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
let mut layout = vec![LayoutGroup::row(form)];
layout.extend(curvature(StartCurvatureInput::INDEX));
layout.extend(curvature(EndCurvatureInput::INDEX));
layout
}
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::vector::generator_nodes::rectangle::*;
@@ -34,6 +34,8 @@ impl FrontendGraphDataType {
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
// A generator draws pixels like an image, at whatever resolution is needed
"Generator" => Self::Raster,
raster if raster.starts_with("Raster") => Self::Raster,
_ => Self::General,
}
@@ -270,7 +270,7 @@ impl OverlayContext {
}
}
pub fn take_scene(self) -> VelloSceneBuilder {
pub fn take_scene(self) -> VelloSceneBuilder<'static> {
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
let empty_scene = overlay_scene(&internal.viewport);
std::mem::replace(&mut internal.scene, empty_scene)
@@ -486,13 +486,13 @@ pub enum DrawHandles {
}
pub(super) struct OverlayContextInternal {
scene: VelloSceneBuilder,
scene: VelloSceneBuilder<'static>,
viewport: ViewportMessageHandler,
visibility_settings: OverlaysVisibilitySettings,
}
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder {
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static> {
// The smallest texture size limit WebGL2 guarantees, which only matters for the overlays' tiny pattern images
const MAX_TEXTURE_SIZE: u32 = 2048;
@@ -51,6 +51,8 @@ pub struct DocumentMetadata {
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
/// Transform from document space to viewport space.
pub document_to_viewport: DAffine2,
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
@@ -347,9 +349,9 @@ impl DocumentMetadata {
}
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
/// stroke geometry when the layer is a vector with a stroke style. Only the first item of a layer's vector data
/// is recorded, so the others count through the click-target-based bounds, without their strokes.
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
let stroke = self
.layer_appearance_attributes
@@ -359,8 +361,10 @@ impl DocumentMetadata {
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
});
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
[stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
Some([min - reach, max + reach])
}
/// Get the bounding box of the click target of the specified layer in viewport space
@@ -732,7 +736,7 @@ mod tests {
let later_item = ClickTarget::new_with_path(line(100., 110.), 0.);
metadata.click_targets.insert(layer, vec![Arc::new(later_item)]);
let [min, max] = metadata.bounding_box_document_with_stroke(layer).unwrap();
let [min, max] = metadata.bounding_box_document_with_stroke_and_effects(layer).unwrap();
assert_eq!((min.x, max.x), (0., 110.));
}
@@ -970,11 +970,11 @@ impl NodeNetworkInterface {
Some(transformed.bounding_box())
}
/// Calculates the document bounds in document space, expanding vector layer bounds to include the rendered
/// stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
pub fn document_bounds_document_space_with_stroke(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
/// Calculates the document bounds in document space, expanding layer bounds to include the rendered stroke width and
/// effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
pub fn document_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
self.document_metadata.document_bounds(include_artboards, true, || {
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke(layer))
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke_and_effects(layer))
})
}
@@ -991,17 +991,17 @@ impl NodeNetworkInterface {
.reduce(Quad::combine_bounds)
}
/// Calculates the selected layer bounds in document space, expanding vector layer bounds to include the
/// rendered stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
pub fn selected_bounds_document_space_with_stroke(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
/// Calculates the selected layer bounds in document space, expanding layer bounds to include the rendered stroke width
/// and effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
pub fn selected_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke_and_effects");
return None;
};
selected_nodes
.selected_layers(&self.document_metadata)
.filter(|&layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke_and_effects(layer))
.reduce(Quad::combine_bounds)
}
@@ -737,6 +737,22 @@ mod tests {
assert!(!type_feeds_input(&item!(f64), &item!(Graphic), paint_conversions), "a number has no conversion into a graphic");
}
#[test]
fn a_cpu_raster_feeds_an_input_that_only_takes_gpu_rasters() {
use graphene_std::raster_nodes::dehaze::dehaze::ImageFrameInput;
use graphene_std::raster_types::{CPU, GPU, Raster};
let dehaze_image = input_conversions(&ImageFrameInput::NODE_IDENTIFIER).get(ImageFrameInput::INDEX).copied().flatten();
assert!(
type_feeds_input(&item!(Raster<CPU>), &item!(Raster<GPU>), dehaze_image),
"a CPU raster should upload through the input adapter"
);
assert!(type_feeds_input(&list!(Raster<CPU>), &list!(Raster<GPU>), dehaze_image), "a list of CPU rasters should too");
assert!(type_feeds_input(&item!(Raster<GPU>), &item!(Raster<GPU>), dehaze_image), "a GPU raster should pass through");
assert!(!type_feeds_input(&item!(Raster<GPU>), &item!(Raster<CPU>), None), "nothing downloads a GPU raster implicitly");
}
#[test]
fn items_promote_onto_list_inputs() {
let paint_conversions = input_conversions(&PaintInput::NODE_IDENTIFIER).get(PaintInput::INDEX).copied().flatten();
@@ -200,4 +200,9 @@ impl NodeNetworkInterface {
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
}
/// Update how far each layer's effects paint past its content.
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
}
}
@@ -20,7 +20,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::graphic_types;
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;
use std::ops::Range;
@@ -299,10 +299,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
aliases: &["math_nodes::GradientTypeNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
aliases: &["math_nodes::SpreadMethodNode"],
@@ -512,8 +508,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::raster_nodes::filter::blur::IDENTIFIER,
aliases: &["graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
node: graphene_std::raster_nodes::effects::blur::IDENTIFIER,
aliases: &["raster_nodes::filter::BlurNode", "graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
@@ -533,8 +529,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::raster_nodes::effects::paint_overlay::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ColorOverlayNode",
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
@@ -542,6 +539,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 {
@@ -1272,6 +1270,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), under.clone(), &network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), over.clone(), &network_path);
}
if *new == graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
}
}
}
}
@@ -1634,6 +1636,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take the presets of the form it set
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
})
.collect();
for (node_id, network_path) in &gradient_form_nodes {
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
continue;
};
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
reset_default_display_name(document, node_id, network_path, "Gradient Form");
if let Some(input) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
}
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
Some(TaggedValue::GradientForm(GradientForm::Radial)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
_ => {
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
graphene_std::renderer::dial_gradient::LINEAR_DIALS
}
};
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
}
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
@@ -1812,6 +1857,56 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// Noise Pattern and Mandelbrot once drew images cut off at a square, 100 units for a clipped Noise Pattern and 1 for Mandelbrot, where their
// patterns now fill the plane. An old Noise Pattern has a Clip toggle, after the primary input or first from before that input existed,
// and an old Mandelbrot lacks the primary input. Each takes the current inputs, with a square filled by its pattern where it was cut off.
const NOISE_SETTINGS: usize = 14;
let old_pattern_nodes = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let reference = document.network_interface.reference(node_id, &path)?;
let clipped = |clip_index: usize| !matches!(node.inputs.get(clip_index).and_then(|input| input.as_value()), Some(TaggedValue::Bool(false)));
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER);
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
let starts_with_clip = matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::Bool(_)));
let clip_index = match node.inputs.len() {
// Also with the pipeline input these nodes took when they rendered on the GPU themselves
17 if node.inputs.last() == Some(&pipeline) => 1,
16 => 1,
15 if starts_with_clip => 0,
_ => return None,
};
return Some((*node_id, path, reference, Some(clip_index), clipped(clip_index).then_some(100.)));
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) && (node.inputs.is_empty() || node.inputs == [pipeline]) {
return Some((*node_id, path, reference, None, Some(1.)));
}
None
})
.collect::<Vec<_>>();
for (node_id, network_path, reference, clip_index, clipped_size) in &old_pattern_nodes {
let Some(definition) = resolve_document_node_type(reference) else { continue };
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
if let Some(clip_index) = clip_index {
for (offset, input) in old_inputs.iter().skip(clip_index + 1).take(NOISE_SETTINGS).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
}
}
if let Some(size) = clipped_size {
fill_square_with_pattern(document, node_id, network_path, *size);
}
}
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
@@ -1865,6 +1960,76 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.require_whole_document_stage();
}
/// Splices a rectangle filled with the pattern node's output onto the wires leaving it, covering the square from the origin of the pattern's space out to `size`.
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_id: &NodeId, network_path: &[NodeId], size: f64) -> Option<()> {
let downstream_consumers: Vec<InputConnector> = document
.network_interface
.outward_wires(network_path)
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
.cloned()
.unwrap_or_default();
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
let rectangle_template = template(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)?;
let fill_template = template(graphene_std::vector_nodes::fill::IDENTIFIER)?;
let transform_template = template(graphene_std::transform_nodes::transform::IDENTIFIER)?;
let [rectangle_id, fill_id, paint_transform_id, placement_transform_id] = [(); 4].map(|_| NodeId::new());
document.network_interface.insert_node(rectangle_id, rectangle_template, network_path);
document.network_interface.insert_node(fill_id, fill_template, network_path);
document.network_interface.insert_node(paint_transform_id, transform_template.clone(), network_path);
document.network_interface.insert_node(placement_transform_id, transform_template, network_path);
let set_value = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, value: TaggedValue| {
document
.network_interface
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(value, false), network_path);
};
let wire = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, source: NodeId| {
document
.network_interface
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::node(source, 0), network_path);
};
// The rectangle's width and height, and the half-square translations of the paint and the filled rectangle
set_value(document, rectangle_id, 1, TaggedValue::Number(size));
set_value(document, rectangle_id, 2, TaggedValue::Number(size));
set_value(document, paint_transform_id, 1, TaggedValue::DVec2(DVec2::splat(-size / 2.)));
set_value(document, placement_transform_id, 1, TaggedValue::DVec2(DVec2::splat(size / 2.)));
wire(document, paint_transform_id, 0, *pattern_node_id);
wire(document, fill_id, 0, rectangle_id);
wire(document, fill_id, 1, paint_transform_id);
wire(document, placement_transform_id, 0, fill_id);
for consumer in &downstream_consumers {
document.network_interface.set_input(consumer, NodeInput::node(placement_transform_id, 0), network_path);
}
// A pattern in a layer chain gives way to the filled rectangle there, moving below to paint it, and otherwise the new nodes sit beside it
if was_in_chain {
document.network_interface.force_set_upstream_to_chain(&placement_transform_id, network_path);
if let Some(fill_position) = document.network_interface.position(&fill_id, network_path) {
document.network_interface.set_absolute_position(&paint_transform_id, fill_position + IVec2::new(-7, 3), network_path);
document.network_interface.set_absolute_position(pattern_node_id, fill_position + IVec2::new(-14, 3), network_path);
}
} else if let Some(position) = document.network_interface.position(pattern_node_id, network_path) {
let offsets = [
(paint_transform_id, IVec2::new(7, 0)),
(rectangle_id, IVec2::new(7, -3)),
(fill_id, IVec2::new(14, 0)),
(placement_transform_id, IVec2::new(21, 0)),
];
for (node_id, offset) in offsets {
document.network_interface.shift_absolute_node_position(&node_id, position + offset, network_path);
}
}
Some(())
}
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
@@ -2395,7 +2560,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()) {
@@ -2716,20 +2880,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
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)?;
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
for (i, input) in old_inputs.iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i + 1), input.clone(), network_path);
}
}
// The Threshold node's luminance calculation input was retired
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER) && inputs_count == 4 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -3511,6 +3661,52 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
let raster_kernel_pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
let raster_kernel_nodes = {
use graphene_std::raster_nodes::adjustments::*;
[
desaturate::IDENTIFIER,
gamma_correction::IDENTIFIER,
make_opaque::IDENTIFIER,
brightness_contrast::IDENTIFIER,
levels::IDENTIFIER,
curves::IDENTIFIER,
black_and_white::IDENTIFIER,
hue_saturation::IDENTIFIER,
invert::IDENTIFIER,
threshold::IDENTIFIER,
gradient_map::IDENTIFIER,
vibrance::IDENTIFIER,
channel_mixer::IDENTIFIER,
selective_color::IDENTIFIER,
posterize::IDENTIFIER,
exposure::IDENTIFIER,
color_balance::IDENTIFIER,
photo_filter::IDENTIFIER,
color_lookup::IDENTIFIER,
image_to_channels::IDENTIFIER,
graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
graphene_std::raster_nodes::filter::median_filter::IDENTIFIER,
graphene_std::raster_nodes::effects::blur::IDENTIFIER,
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
graphene_std::platform_application_io::image_to_bytes::IDENTIFIER,
graphene_std::platform_application_io::rasterize::IDENTIFIER,
]
};
if raster_kernel_nodes.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && !node.inputs.contains(&raster_kernel_pipeline) {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let value_inputs = node_template.inputs.iter().position(|input| *input == raster_kernel_pipeline)?;
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.into_iter().take(value_inputs).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
// A value input stored as a List-form TypeDefault adopts the definition's current default when the connector's declared default has since changed (e.g. the connector was ranked down to Item).
// The red-slash no-paint choice shares that stored form but is a deliberate value, not a stale disconnect default, so it is exempt.
if let Some(definition) = resolve_document_node_type(&reference) {
@@ -4114,7 +4310,8 @@ mod tests {
let desaturate_node = node(1);
assert_eq!(desaturate_node.implementation, DocumentNodeImplementation::ProtoNode(desaturate::IDENTIFIER));
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method]);
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method, pipeline]);
let brightness_contrast = node(2);
assert_eq!(
@@ -4626,6 +4823,54 @@ mod tests {
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
}
#[test]
fn gradient_form_nodes_become_gradient_curvature_presets() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
let (source_id, form_id) = (NodeId(1), NodeId(2));
for (identifier, form, dials) in [
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
] {
let mut document = DocumentMessageHandler::default();
let placeholder = || NodeInput::value(TaggedValue::None, false);
document.network_interface.insert_node(
source_id,
NodeTemplate {
inputs: vec![placeholder()],
..Default::default()
},
&[],
);
document.network_interface.insert_node(
form_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
inputs: vec![placeholder(); 2],
..Default::default()
},
&[],
);
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
document
.network_interface
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), false), &[]);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&form_id];
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(
[curvature(1), curvature(2)],
dials.map(|dial| Some(TaggedValue::Number(dial))),
"{form:?} should become its curvature presets"
);
}
}
#[test]
fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -5175,4 +5420,81 @@ mod tests {
assert_eq!(interface.display_name(&node_id, &[]), "Image", "node {node_id}");
}
}
// Noise Pattern and Mandelbrot once drew a square of their patterns, which now fill the plane, so the square becomes a rectangle filled with the pattern
#[tokio::test]
async fn clipped_patterns_become_rectangles_filled_with_them() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let noise = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER)).await;
let mandelbrot = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER)).await;
let noise_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
let mandelbrot_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
let document = editor.active_document_mut();
for (reader, pattern) in [(noise_reader, noise), (mandelbrot_reader, mandelbrot)] {
document.network_interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(pattern, 0), &[]);
}
// Save them as an older editor did, the Noise Pattern with its Clip toggle on and the Mandelbrot without a primary input
let mut noise_inputs = document.network_interface.document_node(&noise, &[]).unwrap().inputs.clone();
noise_inputs.insert(1, NodeInput::value(TaggedValue::Bool(true), false));
noise_inputs[2] = NodeInput::value(TaggedValue::Integer(7), false);
for (node_id, inputs) in [(noise, noise_inputs), (mandelbrot, Vec::new())] {
let mut legacy = NodeTemplate { inputs, ..Default::default() };
legacy.normalize_input_metadata();
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
}
let serialized = document.serialize_document();
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
let input = |node_id: NodeId, index: usize| interface.document_node(&node_id, &[]).and_then(|node| node.inputs.get(index)).cloned();
let upstream = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_node());
let value = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_value().cloned());
// Each reader now reads a rectangle of the square's size, moved onto the square, filled with the pattern moved back by the same amount
for (reader, pattern, size) in [(noise_reader, noise, 100.), (mandelbrot_reader, mandelbrot, 1.)] {
let placement = upstream(reader, 0).expect("the reader should read the placement transform");
assert_eq!(value(placement, 1), Some(TaggedValue::DVec2(DVec2::splat(size / 2.))));
let fill = upstream(placement, 0).expect("the placement should move the filled rectangle");
let rectangle = upstream(fill, 0).expect("the fill should paint a rectangle");
assert_eq!((value(rectangle, 1), value(rectangle, 2)), (Some(TaggedValue::Number(size)), Some(TaggedValue::Number(size))));
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
assert_eq!(upstream(paint, 0), Some(pattern));
}
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
}
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
#[tokio::test]
async fn marbled_mandelbrot_renders_after_migration() {
use crate::messages::portfolio::ingest::utility_types::IngestAction;
use crate::messages::prelude::IngestMessage;
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
let content = std::fs::read_to_string("../demo-artwork/marbled-mandelbrot.graphite").unwrap();
editor.editor.handle_message(IngestMessage::Ingest {
data: content.into_bytes(),
action: IngestAction::Open,
mime_type: String::new(),
path: Some("marbled-mandelbrot.graphite".into()),
});
if let Err(error) = editor.eval_graph_until_finished().await {
panic!("The migrated demo failed to render: {error}");
}
}
}
@@ -342,7 +342,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
// A generator discards its primary input, so the chain ends at whichever one is reached
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
let setters = [
graphene_std::math_nodes::gradient_form::IDENTIFIER,
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
@@ -413,7 +413,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
let mut gradient_form: Option<GradientForm> = None;
@@ -430,11 +430,14 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
if reference == transform_reference {
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
} else if reference == gradient_form_reference
&& gradient_form.is_none()
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
{
gradient_form = Some(*value);
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
// Curvatures other than the radial form's are drawn with the linear form's controls
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_value()) {
Some(&TaggedValue::Number(value)) => value,
_ => 0.,
};
let is_radial = [curvature(1), curvature(2)] == graphene_std::renderer::dial_gradient::RADIAL_DIALS;
gradient_form = Some(if is_radial { GradientForm::Radial } else { GradientForm::Linear });
}
}
@@ -3366,7 +3369,7 @@ mod test_gradient {
.await;
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor
@@ -3375,7 +3378,7 @@ mod test_gradient {
})
.await;
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let form_node_id = {
let network_interface = &editor.active_document().network_interface;
network_interface
@@ -3384,10 +3387,10 @@ mod test_gradient {
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
.expect("Gradient Form node should have been inserted")
.expect("Gradient Curvature node should have been inserted")
};
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
+85 -4
View File
@@ -383,11 +383,11 @@ impl NodeGraphExecutor {
};
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
// `AllArtwork` and `Selection` expand vector layer bounds by the rendered stroke width so strokes
// drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
// `AllArtwork` and `Selection` expand layer bounds by the rendered stroke width and effects reach so strokes
// and shadows drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
let bounds = match export_config.bounds {
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke(true),
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke(true, &[]),
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke_and_effects(true),
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke_and_effects(true, &[]),
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
}
.ok_or_else(|| "No bounding box".to_string())?;
@@ -959,6 +959,7 @@ impl NodeGraphExecutor {
clip_targets,
vector_data,
appearance_attributes,
effects_reach,
backgrounds: _,
} = render_output.metadata;
@@ -975,6 +976,7 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
responses.add(DocumentMessage::UpdateVectorData { vector_data });
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
responses.add(DocumentMessage::RenderScrollbars);
responses.add(DocumentMessage::RenderRulers);
responses.add(OverlaysMessage::Draw);
@@ -1236,3 +1238,82 @@ mod test {
}
}
}
#[cfg(test)]
mod raster_input_adapter_tests {
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::test_utils::test_prelude::*;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::{DocumentNodeImplementation, NodeId};
use graphene_std::Effects;
use graphene_std::list::{ATTR_EFFECTS, Item};
use graphene_std::ops::ConvertAsync;
use graphene_std::raster_nodes::adjustments::invert;
use graphene_std::raster_nodes::dehaze::dehaze;
use graphene_std::raster_nodes::filter::median_filter;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::transform::Footprint;
/// A document whose image feeds `nodes` in turn, ending in the export, with each node's ID.
async fn image_through(editor: &mut EditorTestUtils, color: Color, nodes: &[ProtoNodeIdentifier]) -> Vec<NodeId> {
editor.new_document().await;
editor.create_raster_image(Image::new(4, 4, color), None).await;
let image = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
.map(|(id, _)| *id)
.expect("the pasted image should be an Image node");
let mut ids = Vec::new();
let mut previous = OutputConnector::node(image, 0);
for (index, identifier) in nodes.iter().enumerate() {
let id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(identifier.clone()), (index as i32 + 1) * 10, 0).await;
let input = InputConnector::node_at_index(id, 0);
editor.active_document_mut().network_interface.create_wire(&previous, &input, &[]);
previous = OutputConnector::node(id, 0);
ids.push(id);
}
editor.active_document_mut().network_interface.create_wire(&previous, &InputConnector::Export(0), &[]);
ids
}
async fn read(editor: &EditorTestUtils, raster: Raster<GPU>) -> Raster<CPU> {
let executor = editor.gpu_executor();
raster.convert(Footprint::DEFAULT, executor).await
}
#[tokio::test]
async fn an_images_stamped_effects_are_carried_out_before_the_gpu_only_node_it_feeds() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::WHITE, &[invert::IDENTIFIER, median_filter::IDENTIFIER, invert::IDENTIFIER]).await;
let instrumented = editor.eval_graph_until_finished().await.expect("the CPU raster should reach Median through its input adapter");
let reached_median: Item<Raster<CPU>> = instrumented
.grab_all_input::<median_filter::ImageFrameInput, Item<Raster<CPU>>>(&editor.runtime)
.next()
.expect("the image should arrive at Median as a CPU raster");
assert!(reached_median.attribute::<Effects>(ATTR_EFFECTS).is_some(), "the first Invert should only stamp the image");
// Median at its default radius passes its input through, so its output shows what the adapter gave it
let output = instrumented
.grab_all_input::<invert::InputInput, Item<Raster<GPU>>>(&editor.runtime)
.next()
.expect("Median should output a GPU raster");
assert!(output.attribute::<Effects>(ATTR_EFFECTS).is_none(), "no stamp should be left to apply after Median");
let raster = read(&editor, output.into_element()).await;
assert!(raster.data[0].r() < 0.01, "the white image should be black by the time Median reads it, not {:?}", raster.data[0]);
}
#[tokio::test]
async fn an_image_feeding_dehaze_compiles_and_renders_without_a_migration() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::from_rgbaf32_unchecked(0.5, 0.6, 0.7, 1.), &[dehaze::IDENTIFIER]).await;
// A compile error or a failed render fails this
editor.eval_graph_uninstrumented().await.expect("the image should reach Dehaze through its input adapter");
}
}
@@ -767,6 +767,8 @@ mod tests {
async fn editor(clock: &Arc<FakeClock>) -> EditorTestUtils {
let mut editor = EditorTestUtils::create_with(Scheduling::default(), clock.clone());
editor.new_document().await;
// SVG Preview renders through the SVG pipeline, which sends each evaluation's artwork to the frontend where it can be seen
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.runtime.async_runtime().retain_sources(&[SOURCE]);
editor.runtime.begin_frame();
+45 -8
View File
@@ -14,13 +14,13 @@ use crate::task::{Scheduling, Spawn, Task};
use crate::test_utils::test_prelude::LayerNodeIdentifier;
use document_container::store::MemoryStore;
use glam::{DVec2, UVec2};
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::application_io::{ApplicationIo, PlatformApplicationIo};
use graphene_std::raster::color::Color;
use graphene_std::runtime::Clock;
use graphene_std::uuid::NodeId;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use std::time::Duration;
/// A set of utility functions to make the writing of editor test more declarative
@@ -48,12 +48,7 @@ impl EditorTestUtils {
.with_resource_storage(Arc::new(HashMapResourceStorage::new()))
.with_document_store(Arc::new(MemoryStore::default())),
)
.with_runtime(
RuntimeBuilder::new(clock)
.with_wake(|| {})
.with_application_io(PlatformApplicationIo::default())
.with_scheduling(scheduling),
)
.with_runtime(RuntimeBuilder::new(clock).with_wake(|| {}).with_application_io(gpu_application_io()).with_scheduling(scheduling))
.with_spawner(BlockingSpawner)
.with_random_seed(0)
.build();
@@ -68,6 +63,11 @@ impl EditorTestUtils {
editor
}
/// The GPU executor the graph runs on.
pub fn gpu_executor(&self) -> <PlatformApplicationIo as ApplicationIo>::Executor {
gpu_application_io().gpu_executor().cloned().expect("tests render on the GPU")
}
pub fn dispatch(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
let mut responses = self.editor.handle_message(message);
while self.woken.swap(false, Ordering::Relaxed) {
@@ -113,6 +113,33 @@ impl EditorTestUtils {
Ok(instrumented)
}
/// Compiles and runs the graph without the monitors of [`Instrumented`], which can't wrap the runtime handle that asynchronous nodes take.
pub async fn eval_graph_uninstrumented(&mut self) -> Result<(), String> {
let portfolio = &mut self.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
if let Err(e) = executor.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, Default::default()) {
return Err(format!("submit_node_graph_evaluation failed\n\n{e}"));
}
self.finish_evaluation().await
}
/// Waits for the submitted evaluation and processes its results, failing if the graph didn't render.
async fn finish_evaluation(&mut self) -> Result<(), String> {
self.runtime.run().await;
let frontend_messages = self.dispatch(Message::Wake);
if frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
return Err("Graph should render".to_string());
}
for message in frontend_messages {
message.check_node_graph_error();
}
Ok(())
}
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
const MAX_ITERATIONS: usize = 16;
@@ -493,6 +520,16 @@ fn init_test_logger() {
});
}
/// Creates application IO with the GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
/// Panics if no adapter is found, since tests render on the GPU like the app does.
fn gpu_application_io() -> PlatformApplicationIo {
static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned());
let executor = GPU_EXECUTOR.clone().expect(
"Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).",
);
PlatformApplicationIo::new_with_executor(executor)
}
/// Runs `operation`, returning its result along with the errors it logged.
pub fn capture_logged_errors<T>(operation: impl FnOnce() -> T) -> (T, Vec<String>) {
init_test_logger();
@@ -540,9 +540,10 @@
margin-left: 8px;
}
// A label alone in its row lines up with the parameter names that follow their expose buttons
> .text-label:only-child {
// A label with no expose button before it lines up with the parameter names that follow one
> .text-label:first-child {
margin-left: calc(20px + 8px + 8px);
--wire-indent: 20px;
}
> .separator.horizontal.unrelated {
+2
View File
@@ -374,6 +374,7 @@ import NodeThreshold from "/../branding/assets/16x16-nodes/node-threshold.svg";
import NodeTransform from "/../branding/assets/16x16-nodes/node-transform.svg";
import NodeTriangulate from "/../branding/assets/16x16-nodes/node-triangulate.svg";
import NodeUnweld from "/../branding/assets/16x16-nodes/node-unweld.svg";
import NodeUploadTexture from "/../branding/assets/16x16-nodes/node-upload-texture.svg";
import NodeVec2ToNumbers from "/../branding/assets/16x16-nodes/node-vec2-to-numbers.svg";
import NodeVec2Value from "/../branding/assets/16x16-nodes/node-vec2-value.svg";
import NodeVibrance from "/../branding/assets/16x16-nodes/node-vibrance.svg";
@@ -652,6 +653,7 @@ export const ICON_16X16_NODES = {
NodeTransform: { svg: NodeTransform, size: 16 },
NodeTriangulate: { svg: NodeTriangulate, size: 16 },
NodeUnweld: { svg: NodeUnweld, size: 16 },
NodeUploadTexture: { svg: NodeUploadTexture, size: 16 },
NodeVec2ToNumbers: { svg: NodeVec2ToNumbers, size: 16 },
NodeVec2Value: { svg: NodeVec2Value, size: 16 },
NodeVibrance: { svg: NodeVibrance, size: 16 },
+26 -1
View File
@@ -13,7 +13,7 @@ pub use glam::{DAffine2, DVec2, IVec2, UVec2};
use graphene_animation::AnimationCurve;
use graphene_application_io::resource::ResourceHash;
use graphene_application_io::resource::ResourceId;
use graphic_types::raster_types::{CPU, Image, Raster};
use graphic_types::raster_types::{CPU, GPU, Image, Raster};
use graphic_types::vector_types::vector::misc::BoxCorners;
use graphic_types::vector_types::vector::style::DashPattern;
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
@@ -36,6 +36,7 @@ macro_rules! for_each_item_type_default {
$action!(Vector);
$action!(f64);
$action!(Raster<CPU>);
$action!(Raster<GPU>);
$action!(Graphic);
$action!(Color);
$action!(Gradient);
@@ -52,6 +53,7 @@ macro_rules! for_each_list_type_default {
$action!(Graphic);
$action!(Artboard);
$action!(Raster<CPU>);
$action!(Raster<GPU>);
$action!(Vector);
$action!(String);
$action!(Color);
@@ -577,6 +579,9 @@ tagged_value! {
TonalRange(raster_nodes::adjustments::TonalRange),
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
GlowSource(graphic_types::GlowSource),
BevelStyle(graphic_types::BevelStyle),
BevelDirection(graphic_types::BevelDirection),
GridType(vector::misc::GridType),
GridTopology(vector::misc::GridTopology),
ArcType(vector::misc::ArcType),
@@ -706,6 +711,25 @@ impl TaggedValue {
None
}
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
}
match ty {
Type::Generic(_) => None,
Type::Concrete(concrete_type) => {
@@ -724,6 +748,7 @@ impl TaggedValue {
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
() 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::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
() 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,
@@ -8,6 +8,7 @@ use graphene_animation::AnimationCurve;
use graphene_std::animation::RealTimeMode;
use graphene_std::any::DynAnyNode;
use graphene_std::brush::Stroke;
use graphene_std::generator::Generator;
use graphene_std::gradient::Gradient;
use graphene_std::list::{AttributeValueDyn, Bundle, Item, List, ListDyn, NodeIdPath};
#[cfg(feature = "gpu")]
@@ -27,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, GlowSource};
use node_registry_macros::async_node;
use std::collections::HashMap;
use std::sync::Arc;
@@ -45,14 +47,18 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Gradient>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Generator>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Artboard>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Graphic>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Vector>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<CPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Gradient>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Generator>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
@@ -90,6 +96,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::RuntimeHandle>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::SourceId>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Option<wgpu_executor::WgpuExecutor>>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>, Context => Item<graphene_std::ContextModification>]),
// ==========
// MEMO NODES
@@ -100,6 +107,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Gradient>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Generator>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
@@ -120,6 +128,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Gradient>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Generator>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
@@ -142,6 +151,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::brush::Stroke>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<RenderIntermediate>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuExecutor>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Option<wgpu_executor::WgpuExecutor>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
];
// The per-connector input adapter, registered per element type: an `Item` or `List` wire passes through unchanged.
@@ -329,6 +339,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
TonalRange,
AdjustmentChannel,
HueSaturationRange,
GlowSource,
BevelStyle,
BevelDirection,
Stroke,
ScaleType,
ReferencePoint,
@@ -362,6 +375,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
Graphic,
Color,
Gradient,
Generator,
String,
f64,
DVec2,
@@ -375,8 +389,28 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// The nested-generic `Box<VectorModification>` registers directly rather than through the shared callback, since the
// extra macro layer mangles the `stringify!` whitespace in its adapter identifier; its cache chain is likewise direct below
node_types.extend(rank_adapter_nodes!(Box<VectorModification>));
// A GPU raster's input adapter also takes the pipeline to upload a CPU raster wire with, so its rows don't come from `rank_adapter_nodes`
#[cfg(feature = "gpu")]
node_types.extend(rank_adapter_nodes!(Raster<GPU>));
{
use graphene_std::raster_nodes::effects::{PassRasterNode, UploadItemNode, UploadListNode};
use wgpu_executor::WgpuPipelineCache;
macro_rules! gpu_raster_input_adapter {
($path:ty, $from:ty) => {
async_node!(
identifier: ProtoNodeIdentifier::new("input_adapter<Raster<GPU>>"),
$path,
input: Context,
fn_params: [Context => $from, Context => Item<WgpuPipelineCache>]
)
};
}
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, Item<Raster<GPU>>));
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, List<Raster<GPU>>));
node_types.push(gpu_raster_input_adapter!(UploadItemNode<_, _>, Item<Raster<CPU>>));
node_types.push(gpu_raster_input_adapter!(UploadListNode<_, _>, List<Raster<CPU>>));
node_types.push(item_to_list_node!(element: Raster<GPU>));
}
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
macro_rules! list_dyn_rows {
($($element:ty),* $(,)?) => {{
@@ -394,6 +428,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
Raster<CPU>,
Color,
Gradient,
Generator,
f64,
i64,
bool,
@@ -434,6 +469,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
String,
Color,
Gradient,
Generator,
Artboard,
));
#[cfg(feature = "gpu")]
@@ -487,6 +523,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// This is what lets a paint list zip element-wise against the content it paints.
node_types.extend(embed_adapter_row!(from_element: Color, element: Graphic));
node_types.extend(embed_adapter_row!(from_element: Gradient, element: Graphic));
node_types.extend(embed_adapter_row!(from_element: Generator, element: Graphic));
node_types.extend(embed_adapter_row!(from_element: String, element: Graphic));
node_types.extend(embed_adapter_row!(from_element: Vector, element: Graphic));
node_types.extend(embed_adapter_row!(from_element: Raster<CPU>, element: Graphic));
@@ -544,6 +581,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
attribute_value_node!(List<String>),
attribute_value_node!(List<Color>),
attribute_value_node!(List<Gradient>),
attribute_value_node!(List<Generator>),
attribute_value_node!(List<Vector>),
attribute_value_node!(List<Raster<CPU>>),
#[cfg(feature = "gpu")]
@@ -571,6 +609,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
transform_list_node!(element: Raster<GPU>),
transform_list_node!(element: Color),
transform_list_node!(element: Gradient),
transform_list_node!(element: Generator),
];
node_types.extend(transform_list_rows);
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
+23 -7
View File
@@ -1,6 +1,6 @@
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeInput, NodeNetwork};
use graph_craft::generic;
use graph_craft::{concrete, item};
use graphene_std::Context;
@@ -27,7 +27,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
let render_node = DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::Network(NodeNetwork {
exports: vec![NodeInput::node(NodeId(5), 0)],
exports: vec![NodeInput::node(NodeId(6), 0)],
nodes: [
DocumentNode {
call_argument: concrete!(Context),
@@ -42,7 +42,23 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
inputs: vec![
NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER),
NodeInput::node(NodeId(0), 0),
NodeInput::scope("runtime"),
NodeInput::Reflection(DocumentNodeMetadata::SourceId),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::download_gpu_rasters::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
..Default::default()
}),
..Default::default()
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -53,7 +69,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -64,7 +80,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(3), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -77,7 +93,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
call_argument: concrete!(Context),
inputs: vec![
NodeInput::scope(graphene_std::render_background::composite_background_pipeline::IDENTIFIER),
NodeInput::node(NodeId(3), 0),
NodeInput::node(NodeId(4), 0),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
@@ -89,7 +105,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::node(NodeId(4), 0)],
inputs: vec![NodeInput::node(NodeId(5), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
// INDEX is never read; it forces a nullification and cache pair onto the `data` parameter's wire so the render cache keys on a stable context
+5 -3
View File
@@ -16,15 +16,14 @@ workspace = true
[features]
default = ["serde"]
serde = ["dep:serde"]
serde = ["dep:serde", "glam/serde", "half/serde"]
nightly = []
type_id_logging = []
dealloc_nodes = []
wasm = ["tsify", "wasm-bindgen", "no-std-types/wasm"]
wasm = ["tsify", "wasm-bindgen"]
[dependencies]
# Local dependencies
no-std-types = { workspace = true }
graphene-hash = { workspace = true, features = ["derive"] }
# Workspace dependencies
@@ -33,6 +32,9 @@ bitflags = { workspace = true }
bytemuck = { workspace = true }
node-macro = { workspace = true }
num-traits = { workspace = true }
num-derive = { workspace = true }
num_enum = { workspace = true, features = ["std"] }
half = { workspace = true, features = ["std"] }
rand = { workspace = true }
glam = { workspace = true }
serde_json = { workspace = true }
@@ -4,7 +4,8 @@ use num_enum::{FromPrimitive, IntoPrimitive};
#[repr(i32)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, dyn_any::DynAny, serde::Serialize, serde::Deserialize, graphene_hash::CacheHash, FromPrimitive, IntoPrimitive)]
#[derive(dyn_any::DynAny, graphene_hash::CacheHash, Debug, Default, Clone, Copy, Eq, PartialEq, Hash, FromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BlendMode {
// Basic group
#[default]
@@ -7,7 +7,8 @@ use glam::Vec4;
use half::f16;
#[repr(C)]
#[derive(Default, Clone, Copy, PartialEq, Pod, Zeroable, Debug, dyn_any::DynAny, serde::Serialize, serde::Deserialize)]
#[derive(Default, Clone, Copy, PartialEq, Pod, Zeroable, Debug, dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RGBA16F {
red: f16,
green: f16,
@@ -81,7 +82,8 @@ impl Pixel for RGBA16F {}
/// the linear-light [`Color`] type. Convert via [`From<SRGBA8> for Color`] and [`From<Color> for SRGBA8`].
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Pod, Zeroable, dyn_any::DynAny, serde::Serialize, serde::Deserialize, graphene_hash::CacheHash)]
#[derive(dyn_any::DynAny, graphene_hash::CacheHash, Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Pod, Zeroable)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SRGBA8 {
pub red: u8,
pub green: u8,
@@ -202,7 +204,8 @@ impl From<SRGBA8> for Color {
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable, dyn_any::DynAny, serde::Serialize, serde::Deserialize)]
#[derive(dyn_any::DynAny, Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Luma(pub f32);
impl Luminance for Luma {
@@ -249,6 +252,7 @@ pub struct Color {
impl Eq for Color {}
// TODO: Eventually remove this document upgrade code
#[cfg(feature = "serde")]
impl serde::Serialize for Color {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
@@ -265,6 +269,7 @@ impl serde::Serialize for Color {
}
// TODO: Eventually remove this document upgrade code
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Color {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
// Documents from before the linear-storage migration lack the `linear` marker and stored gamma-encoded floats; convert them on load.
+24 -2
View File
@@ -1,7 +1,6 @@
use crate::runtime::{Generations, SourceId};
use crate::transform::Footprint;
use glam::DVec2;
pub use no_std_types::context::{ArcCtx, Ctx};
use glam::{DAffine2, DVec2};
use std::any::Any;
use std::borrow::Borrow;
use std::collections::BTreeSet;
@@ -9,6 +8,15 @@ use std::hash::{Hash, Hasher};
use std::panic::Location;
use std::sync::Arc;
pub trait Ctx: Clone + Send {}
impl<T: Ctx> Ctx for Option<T> {}
impl<T: Ctx + Sync> Ctx for &T {}
impl Ctx for () {}
pub trait ArcCtx: Send + Sync {}
impl<T: ArcCtx> Ctx for Arc<T> {}
// ==============
// EXTRACT TRAITS
// ==============
@@ -764,6 +772,20 @@ impl OwnedContextImpl {
self.footprint = Some(footprint);
self
}
/// Replaces any footprint with [`Footprint::for_instances`] for content placed once per transform in `instance_transforms`.
pub fn with_instances_footprint(mut self, instance_transforms: impl IntoIterator<Item = DAffine2>) -> Self {
if let Some(footprint) = &self.footprint {
self.footprint = Some(footprint.for_instances(instance_transforms));
}
self
}
/// Replaces any footprint with its [`Footprint::probe`].
pub fn with_probe_footprint(mut self) -> Self {
if let Some(footprint) = &self.footprint {
self.footprint = Some(footprint.probe());
}
self
}
pub fn with_real_time(mut self, real_time: f64) -> Self {
self.real_time = Some(real_time);
self
+16 -7
View File
@@ -1,6 +1,9 @@
extern crate log;
pub mod blending;
pub mod bounds;
pub mod choice_type;
pub mod color;
pub mod consts;
pub mod context;
pub mod generic;
@@ -29,15 +32,12 @@ pub use glam_ext::FallibleVec2Operations;
pub use graphene_hash;
pub use graphene_hash::CacheHash;
pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING,
ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
};
pub use memo::MemoHash;
pub use no_std_types::AsU32;
pub use no_std_types::blending;
pub use no_std_types::choice_type;
pub use no_std_types::color;
pub use num_traits;
pub use poll::{Finality, Interrupt, LazyInput, NodeError, Poll, PollInput, Status};
pub use runtime::{Generations, RuntimeHandle, SourceId};
@@ -165,3 +165,12 @@ impl<P: NodeParameter> From<P> for ParameterRef {
}
}
}
pub trait AsU32 {
fn as_u32(&self) -> u32;
}
impl AsU32 for u32 {
fn as_u32(&self) -> u32 {
*self
}
}
@@ -61,6 +61,11 @@ pub const ATTR_CLIP: &str = "clip";
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
/// Gradient's `GradientForm` (`Linear` or `Radial`).
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
/// Gradient's `f64` curvature dial for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, the form decides it.
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
/// Gradient's `f64` curvature dial for the contour through its end, like `gradient_start_curvature` with the ends swapped.
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
@@ -80,6 +85,9 @@ pub const ATTR_POSITION: &str = "position";
pub const ATTR_MIDPOINT: &str = "midpoint";
/// Item's ordered list of paint passes, of type `Appearance`. Earlier coverages paint first, compositing below later ones.
pub const ATTR_APPEARANCE: &str = "appearance";
/// Item's ordered list of effects, of type `Effects`, which the renderer applies in turn to the pixels the item renders to.
/// Unlike the appearance, it doesn't cascade to descendants.
pub const ATTR_EFFECTS: &str = "effects";
// TODO: Add a "fill_rule" attribute as a sibling of "paint" on the coverage list (uniform across covers) once a FillRule type ships
/// Coverage's `Graphic` paint (implicit default `Graphic::None`, painting nothing), on the
/// `List<Coverage>` inside an `Appearance`.
+2 -2
View File
@@ -90,8 +90,8 @@ struct LegacyTable<T> {
}
// TODO: Eventually remove this document upgrade code
pub fn migrate_to_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<no_std_types::color::Color, D::Error> {
use no_std_types::color::Color;
pub fn migrate_to_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<crate::color::Color, D::Error> {
use crate::color::Color;
use serde::Deserialize;
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
@@ -179,6 +179,8 @@ impl Footprint {
quality: RenderQuality::Full,
};
pub const MAX_UNION_RESOLUTION: u32 = 8192;
pub const BOUNDLESS: Self = Self {
transform: DAffine2 {
matrix2: DMat2::from_diagonal(DVec2::splat(f64::INFINITY)),
@@ -205,6 +207,61 @@ impl Footprint {
}
}
/// The same view squeezed into a single pixel, for evaluating content only to learn where it's placed. A boundless footprint stays boundless.
pub fn probe(&self) -> Footprint {
if !self.transform.is_finite() {
return *self;
}
Footprint {
transform: DAffine2::from_scale(1. / self.resolution.max(UVec2::ONE).as_dvec2()) * self.transform,
resolution: UVec2::ONE,
..*self
}
}
/// The footprint for content shown once per transform in `instance_transforms`, covering what every instance shows of it. A boundless footprint stays boundless.
pub fn for_instances(&self, instance_transforms: impl IntoIterator<Item = DAffine2>) -> Footprint {
if !self.transform.is_finite() {
return *self;
}
let views = instance_transforms.into_iter().map(|instance_transform| Footprint {
transform: self.transform * instance_transform,
..*self
});
Self::union(views).unwrap_or(*self)
}
/// The footprint covering everything each of `views` shows of the content, axis-aligned in the content's space at the finest pixel density any of them needs.
/// Its density is lowered to keep each side within [`Self::MAX_UNION_RESOLUTION`]. `None` when no view has an invertible transform.
pub fn union(views: impl IntoIterator<Item = Footprint>) -> Option<Footprint> {
let mut bounds: Option<AxisAlignedBbox> = None;
let mut density = 0_f64;
let mut quality = RenderQuality::Full;
for view in views {
if view.transform.matrix2.determinant() == 0. {
continue;
}
let view_bounds = view.viewport_bounds_in_local_space();
bounds = Some(bounds.map_or(view_bounds.clone(), |bounds| bounds.union(&view_bounds)));
density = density.max(view.scale().max_element());
quality = view.quality;
}
let bounds = bounds?;
let size = bounds.size();
let density = density.min(Self::MAX_UNION_RESOLUTION as f64 / size.max_element());
let resolution = (size * density).ceil().as_uvec2().max(UVec2::ONE);
Some(Footprint {
transform: DAffine2::from_scale(DVec2::splat(density)) * DAffine2::from_translation(-bounds.start),
resolution,
quality,
})
}
pub fn scale(&self) -> DVec2 {
self.transform.scale_magnitudes()
}
@@ -257,3 +314,59 @@ impl ApplyTransform for DVec2 {
*self = modification.transform_point2(*self);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn view(width: u32, height: u32) -> Footprint {
Footprint {
resolution: UVec2::new(width, height),
..Footprint::DEFAULT
}
}
#[test]
fn instances_footprint_covers_every_instance() {
let footprint = view(100, 100).for_instances([DAffine2::IDENTITY, DAffine2::from_translation(DVec2::new(200., 0.))]);
let bounds = footprint.viewport_bounds_in_local_space();
assert!(bounds.start.abs_diff_eq(DVec2::new(-200., 0.), 1e-9), "{bounds:?}");
assert!(bounds.end.abs_diff_eq(DVec2::new(100., 100.), 1e-9), "{bounds:?}");
assert_eq!(footprint.resolution, UVec2::new(300, 100));
}
#[test]
fn instances_footprint_takes_the_finest_density() {
let footprint = view(100, 100).for_instances([DAffine2::IDENTITY, DAffine2::from_scale(DVec2::splat(4.))]);
assert!((footprint.scale().x - 4.).abs() < 1e-9);
assert_eq!(footprint.resolution, UVec2::new(400, 400));
}
#[test]
fn instances_footprint_caps_its_resolution() {
let footprint = view(1000, 1000).for_instances([DAffine2::IDENTITY, DAffine2::from_translation(DVec2::new(1e6, 0.))]);
assert!(footprint.resolution.max_element() <= Footprint::MAX_UNION_RESOLUTION);
}
#[test]
fn boundless_footprint_stays_boundless() {
assert_eq!(Footprint::BOUNDLESS.for_instances([DAffine2::from_translation(DVec2::ONE)]), Footprint::BOUNDLESS);
assert_eq!(Footprint::BOUNDLESS.probe(), Footprint::BOUNDLESS);
}
#[test]
fn probe_covers_the_same_view_in_one_pixel() {
let footprint = Footprint {
transform: DAffine2::from_scale(DVec2::splat(2.)),
..view(100, 50)
};
let probe = footprint.probe();
assert_eq!(probe.resolution, UVec2::ONE);
let (bounds, probe_bounds) = (footprint.viewport_bounds_in_local_space(), probe.viewport_bounds_in_local_space());
assert!(bounds.start.abs_diff_eq(probe_bounds.start, 1e-9) && bounds.end.abs_diff_eq(probe_bounds.end, 1e-9));
}
}
@@ -21,6 +21,7 @@ wasm = [
"core-types/wasm",
"vector-types/wasm",
"raster-types/wasm",
"tsify",
"wasm-bindgen",
]
@@ -28,6 +29,7 @@ wasm = [
# Local dependencies
core-types = { workspace = true }
graphene-hash = { workspace = true }
graphene-resource = { workspace = true }
brush-types = { workspace = true }
raster-types = { workspace = true, features = ["wgpu"] }
vector-types = { workspace = true }
@@ -36,8 +38,10 @@ node-macro = { workspace = true }
# Workspace dependencies
dyn-any = { workspace = true }
glam = { workspace = true }
num_enum = { workspace = true }
serde_json = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
tsify = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
@@ -0,0 +1,558 @@
//! 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;
use core_types::blending::BlendMode;
use core_types::color::SRGBA8;
use core_types::graphene_hash::CacheHash;
use core_types::list::Item;
use core_types::transfer_curve::TransferCurve;
use graphene_resource::Resource;
use num_enum::{FromPrimitive, IntoPrimitive};
use vector_types::Gradient;
/// A color adjustment applied to each color on its own, with no regard for its neighbors.
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub enum Adjustment {
Desaturate {
method: DesaturateMethod,
},
GammaCorrection {
gamma: f64,
inverse: bool,
},
MakeOpaque,
BrightnessContrast {
/// Percent.
brightness: f64,
/// Percent.
contrast: f64,
use_classic: bool,
/// On a scale of 0 to 255.
classic_pivot: f64,
},
Levels(Box<LevelsSettings>),
Curves(Box<CurvesSettings>),
BlackAndWhite(BlackAndWhiteSettings),
HueSaturation(Box<HueSaturationSettings>),
Invert,
Threshold {
/// Percent.
min_luminance: f64,
/// Percent.
max_luminance: f64,
},
GradientMap {
/// The gradient, with its whole-ramp settings as its attributes.
gradient: Item<Gradient>,
reverse: bool,
},
Vibrance {
/// Percent.
vibrance: f64,
/// Percent.
saturation: f64,
},
ChannelMixer(Box<ChannelMixerSettings>),
SelectiveColor(Box<SelectiveColorSettings>),
Posterize {
levels: i64,
},
Exposure {
exposure: f64,
offset: f64,
gamma_correction: f64,
},
ColorBalance(ColorBalanceSettings),
PhotoFilter {
color: Color,
/// Percent.
density: f64,
preserve_luminosity: bool,
},
ColorLookup {
/// The file the lookup table is read from.
lut_file: Resource,
},
ColorOverlay {
color: Color,
blend_mode: BlendMode,
/// Percent.
opacity: f64,
},
}
impl Adjustment {
/// Whether each channel of the result depends only on the same channel of the color, making the adjustment four curves.
pub fn is_per_channel(&self) -> bool {
matches!(
self,
Self::GammaCorrection { .. }
| Self::MakeOpaque
| Self::BrightnessContrast { .. }
| Self::Levels(_)
| Self::Curves(_)
| Self::Invert
| Self::Posterize { .. }
| Self::Exposure { .. }
| Self::ColorBalance(_)
)
}
pub fn kind(&self) -> EffectKind {
match self {
Self::Desaturate { .. } => EffectKind::Desaturate,
Self::GammaCorrection { .. } => EffectKind::GammaCorrection,
Self::MakeOpaque => EffectKind::MakeOpaque,
Self::BrightnessContrast { .. } => EffectKind::BrightnessContrast,
Self::Levels(_) => EffectKind::Levels,
Self::Curves(_) => EffectKind::Curves,
Self::BlackAndWhite(_) => EffectKind::BlackAndWhite,
Self::HueSaturation(_) => EffectKind::HueSaturation,
Self::Invert => EffectKind::Invert,
Self::Threshold { .. } => EffectKind::Threshold,
Self::GradientMap { .. } => EffectKind::GradientMap,
Self::Vibrance { .. } => EffectKind::Vibrance,
Self::ChannelMixer(_) => EffectKind::ChannelMixer,
Self::SelectiveColor(_) => EffectKind::SelectiveColor,
Self::Posterize { .. } => EffectKind::Posterize,
Self::Exposure { .. } => EffectKind::Exposure,
Self::ColorBalance(_) => EffectKind::ColorBalance,
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
Self::ColorLookup { .. } => EffectKind::ColorLookup,
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
}
}
/// Visits each parameter with the attribute it rides, named after the node's parameter, and its implicit default, which is the node's.
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
match self {
Self::Desaturate { method } => visitor.parameter("method", method, DesaturateMethod::default()),
Self::GammaCorrection { gamma, inverse } => {
visitor.parameter("gamma", gamma, 2.2);
visitor.parameter("inverse", inverse, false);
}
Self::MakeOpaque | Self::Invert => {}
Self::BrightnessContrast {
brightness,
contrast,
use_classic,
classic_pivot,
} => {
visitor.parameter("brightness", brightness, 0.);
visitor.parameter("contrast", contrast, 0.);
visitor.parameter("use_classic", use_classic, false);
visitor.parameter("classic_pivot", classic_pivot, 127.);
}
Self::Levels(settings) => {
let LevelsSettings { composite, red, green, blue, alpha } = settings.as_mut();
composite.visit_parameters(visitor, "");
red.visit_parameters(visitor, "red");
green.visit_parameters(visitor, "green");
blue.visit_parameters(visitor, "blue");
alpha.visit_parameters(visitor, "alpha");
}
Self::Curves(settings) => {
let CurvesSettings { composite, red, green, blue, alpha } = settings.as_mut();
visitor.parameter("curve", composite, TransferCurve::default());
visitor.parameter("red_curve", red, TransferCurve::default());
visitor.parameter("green_curve", green, TransferCurve::default());
visitor.parameter("blue_curve", blue, TransferCurve::default());
visitor.parameter("alpha_curve", alpha, TransferCurve::default());
}
Self::BlackAndWhite(settings) => {
visitor.parameter("use_tint", &mut settings.use_tint, false);
visitor.parameter("tint", &mut settings.tint, Color::from(SRGBA8::new(0xe1, 0xd3, 0xb3, 0xff)));
visitor.parameter("reds", &mut settings.reds, 40.);
visitor.parameter("yellows", &mut settings.yellows, 60.);
visitor.parameter("greens", &mut settings.greens, 40.);
visitor.parameter("cyans", &mut settings.cyans, 60.);
visitor.parameter("blues", &mut settings.blues, 20.);
visitor.parameter("magentas", &mut settings.magentas, 80.);
}
Self::HueSaturation(settings) => {
let HueSaturationSettings {
master,
colorize,
colorize_sliders,
reds,
yellows,
greens,
cyans,
blues,
magentas,
} = settings.as_mut();
master.visit_parameters(visitor, "", [0., 0., 0.]);
visitor.parameter("colorize", colorize, false);
colorize_sliders.visit_parameters(visitor, "colorize", [24., 25., 0.]);
reds.visit_parameters(visitor, "reds", [315., 345., 15., 45.]);
yellows.visit_parameters(visitor, "yellows", [15., 45., 75., 105.]);
greens.visit_parameters(visitor, "greens", [75., 105., 135., 165.]);
cyans.visit_parameters(visitor, "cyans", [135., 165., 195., 225.]);
blues.visit_parameters(visitor, "blues", [195., 225., 255., 285.]);
magentas.visit_parameters(visitor, "magentas", [255., 285., 315., 345.]);
}
Self::Threshold { min_luminance, max_luminance } => {
visitor.parameter("min_luminance", min_luminance, 50.);
visitor.parameter("max_luminance", max_luminance, 100.);
}
Self::GradientMap { gradient, reverse } => {
visitor.parameter("gradient", gradient, Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])));
visitor.parameter("reverse", reverse, false);
}
Self::Vibrance { vibrance, saturation } => {
visitor.parameter("vibrance", vibrance, 0.);
visitor.parameter("saturation", saturation, 0.);
}
Self::ChannelMixer(settings) => {
let ChannelMixerSettings {
monochrome,
monochrome_mix,
red,
green,
blue,
} = settings.as_mut();
visitor.parameter("monochrome", monochrome, false);
monochrome_mix.visit_parameters(visitor, "monochrome", [40., 40., 20., 0.]);
red.visit_parameters(visitor, "red", [100., 0., 0., 0.]);
green.visit_parameters(visitor, "green", [0., 100., 0., 0.]);
blue.visit_parameters(visitor, "blue", [0., 0., 100., 0.]);
}
Self::SelectiveColor(settings) => {
let SelectiveColorSettings {
mode,
reds,
yellows,
greens,
cyans,
blues,
magentas,
whites,
neutrals,
blacks,
} = settings.as_mut();
visitor.parameter("mode", mode, RelativeAbsolute::default());
let groups = [
("reds", reds),
("yellows", yellows),
("greens", greens),
("cyans", cyans),
("blues", blues),
("magentas", magentas),
("whites", whites),
("neutrals", neutrals),
("blacks", blacks),
];
for (name, inks) in groups {
inks.visit_parameters(visitor, name);
}
}
Self::Posterize { levels } => visitor.parameter("levels", levels, 4),
Self::Exposure { exposure, offset, gamma_correction } => {
visitor.parameter("exposure", exposure, 0.);
visitor.parameter("offset", offset, 0.);
visitor.parameter("gamma_correction", gamma_correction, 1.);
}
Self::ColorBalance(settings) => {
settings.shadows.visit_parameters(visitor, "shadows");
settings.midtones.visit_parameters(visitor, "midtones");
settings.highlights.visit_parameters(visitor, "highlights");
visitor.parameter("preserve_luminosity", &mut settings.preserve_luminosity, true);
}
Self::PhotoFilter { color, density, preserve_luminosity } => {
visitor.parameter("color", color, Color::from(SRGBA8::new(0xec, 0x8a, 0x00, 0xff)));
visitor.parameter("density", density, 25.);
visitor.parameter("preserve_luminosity", preserve_luminosity, true);
}
Self::ColorLookup { lut_file } => visitor.parameter("lut_file", lut_file, Resource::default()),
Self::ColorOverlay { color, blend_mode, opacity } => {
// 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.);
}
}
}
}
/// Conversion from a color to grayscale.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
#[widget(Dropdown)]
#[repr(u32)]
pub enum DesaturateMethod {
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
///
/// Accessibility contrast ratios and SVG luminance masks use this.
#[default]
#[label("Luminance (Rec. 709)")]
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
LuminanceRec709,
/// Light level approximation for the color, the Y′ (luma) of Rec. 709, which weights the gamma-encoded RGB channels by `0.2126, 0.7152, 0.0722`.
///
/// CSS filter functions such as `grayscale()` use this.
#[label("Luma (Rec. 709)")]
LumaRec709,
/// Light level approximation for the color, the Y′ (luma) of Rec. 601, which weights the gamma-encoded RGB channels by `0.299, 0.587, 0.114`.
///
/// The Luminosity family of blend modes uses this, rounded to `0.3, 0.59, 0.11`.
#[label("Luma (Rec. 601)")]
LumaRec601,
/// Perceptually uniform scale from black to white, the L (lightness) of OkLab.
#[label("Lightness (OkLab)")]
#[cfg_attr(feature = "serde", serde(alias = "Perceptual"))]
LightnessOkLab,
/// Mean of the three linear-light RGB channels.
#[menu_separator]
#[cfg_attr(feature = "serde", serde(alias = "AverageChannels"))]
ChannelsAverage,
/// Smallest of the three linear-light RGB channels.
#[cfg_attr(feature = "serde", serde(alias = "MinimumChannels"))]
ChannelsMinimum,
/// Largest of the three linear-light RGB channels, the V (value) of HSV.
#[cfg_attr(feature = "serde", serde(alias = "MaximumChannels"))]
ChannelsMaximum,
/// Midpoint of the largest and smallest gamma-encoded RGB channels, the L (lightness) of HSL.
///
/// The classic "Desaturate" command of many image editors uses this.
#[label("Lightness (HSL)")]
LightnessHsl,
}
#[repr(u32)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
#[widget(Radio)]
pub enum RelativeAbsolute {
#[default]
Relative,
Absolute,
}
/// A group of colors whose inks the Selective Color adjustment offsets.
#[repr(u32)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
pub enum SelectiveColorChoice {
#[default]
Reds,
Yellows,
Greens,
Cyans,
Blues,
Magentas,
#[menu_separator]
Whites,
Neutrals,
Blacks,
}
/// One channel's Levels record: percentage input and output points and the midtones gamma.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct LevelsRecord {
pub shadows: f64,
pub midtones: f64,
pub highlights: f64,
pub output_minimums: f64,
pub output_maximums: f64,
}
/// The composite record that the three color channels pass through after their own, and the alpha record that stands apart.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct LevelsSettings {
pub composite: LevelsRecord,
pub red: LevelsRecord,
pub green: LevelsRecord,
pub blue: LevelsRecord,
pub alpha: LevelsRecord,
}
/// The composite curve that the three color channels pass through after their own, and the alpha curve that stands apart.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct CurvesSettings {
pub composite: TransferCurve,
pub red: TransferCurve,
pub green: TransferCurve,
pub blue: TransferCurve,
pub alpha: TransferCurve,
}
/// The percentage each hue contributes to the gray, and the color tinting it when `use_tint` is set.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct BlackAndWhiteSettings {
pub use_tint: bool,
pub tint: Color,
pub reds: f64,
pub yellows: f64,
pub greens: f64,
pub cyans: f64,
pub blues: f64,
pub magentas: f64,
}
/// One set of Hue/Saturation sliders: a hue in degrees and saturation and lightness percentages.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct HueSaturationSliders {
pub hue: f64,
pub saturation: f64,
pub lightness: f64,
}
/// The sliders for one range of hues, which apply fully from the range start to its end, fading out at the falloff ends. Edges are in degrees.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct HueRangeSettings {
pub sliders: HueSaturationSliders,
pub falloff_start: f64,
pub range_start: f64,
pub range_end: f64,
pub falloff_end: f64,
}
/// The master sliders shift every color, each hue range adds its own, and colorizing replaces them all with an absolute hue and saturation.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct HueSaturationSettings {
pub master: HueSaturationSliders,
pub colorize: bool,
pub colorize_sliders: HueSaturationSliders,
pub reds: HueRangeSettings,
pub yellows: HueRangeSettings,
pub greens: HueRangeSettings,
pub cyans: HueRangeSettings,
pub blues: HueRangeSettings,
pub magentas: HueRangeSettings,
}
/// The percentages of each source channel, plus a constant, that sum to one output channel.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct ChannelMixerRow {
pub red: f64,
pub green: f64,
pub blue: f64,
pub constant: f64,
}
/// A row for each output channel, or for the single gray channel when monochrome.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct ChannelMixerSettings {
pub monochrome: bool,
pub monochrome_mix: ChannelMixerRow,
pub red: ChannelMixerRow,
pub green: ChannelMixerRow,
pub blue: ChannelMixerRow,
}
/// Percentage offsets to the cyan, magenta, yellow, and black inks of one group of colors.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct SelectiveColorInks {
pub cyan: f64,
pub magenta: f64,
pub yellow: f64,
pub black: f64,
}
/// The ink offsets of each group of colors, and whether they are relative to the inks already present.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct SelectiveColorSettings {
pub mode: RelativeAbsolute,
pub reds: SelectiveColorInks,
pub yellows: SelectiveColorInks,
pub greens: SelectiveColorInks,
pub cyans: SelectiveColorInks,
pub blues: SelectiveColorInks,
pub magentas: SelectiveColorInks,
pub whites: SelectiveColorInks,
pub neutrals: SelectiveColorInks,
pub blacks: SelectiveColorInks,
}
/// Percentage shifts along the three opponent color axes for one tonal range.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct ColorBalanceShifts {
pub cyan_red: f64,
pub magenta_green: f64,
pub yellow_blue: f64,
}
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct ColorBalanceSettings {
pub shadows: ColorBalanceShifts,
pub midtones: ColorBalanceShifts,
pub highlights: ColorBalanceShifts,
pub preserve_luminosity: bool,
}
/// The attribute key of a parameter in one of a node's groups of parameters, which the node names with the group's prefix.
fn grouped_key(group: &str, parameter: &str) -> String {
if group.is_empty() { parameter.to_string() } else { format!("{group}_{parameter}") }
}
impl LevelsRecord {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
visitor.parameter(&grouped_key(group, "highlights"), &mut self.highlights, 100.);
visitor.parameter(&grouped_key(group, "output_minimums"), &mut self.output_minimums, 0.);
visitor.parameter(&grouped_key(group, "output_maximums"), &mut self.output_maximums, 100.);
}
}
impl HueSaturationSliders {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [hue, saturation, lightness]: [f64; 3]) {
visitor.parameter(&grouped_key(group, "hue"), &mut self.hue, hue);
visitor.parameter(&grouped_key(group, "saturation"), &mut self.saturation, saturation);
visitor.parameter(&grouped_key(group, "lightness"), &mut self.lightness, lightness);
}
}
impl HueRangeSettings {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [falloff_start, range_start, range_end, falloff_end]: [f64; 4]) {
self.sliders.visit_parameters(visitor, group, [0.; 3]);
visitor.parameter(&grouped_key(group, "falloff_start"), &mut self.falloff_start, falloff_start);
visitor.parameter(&grouped_key(group, "range_start"), &mut self.range_start, range_start);
visitor.parameter(&grouped_key(group, "range_end"), &mut self.range_end, range_end);
visitor.parameter(&grouped_key(group, "falloff_end"), &mut self.falloff_end, falloff_end);
}
}
impl ChannelMixerRow {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [red, green, blue, constant]: [f64; 4]) {
visitor.parameter(&grouped_key(group, "red"), &mut self.red, red);
visitor.parameter(&grouped_key(group, "green"), &mut self.green, green);
visitor.parameter(&grouped_key(group, "blue"), &mut self.blue, blue);
visitor.parameter(&grouped_key(group, "constant"), &mut self.constant, constant);
}
}
impl SelectiveColorInks {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
visitor.parameter(&grouped_key(group, "cyan"), &mut self.cyan, 0.);
visitor.parameter(&grouped_key(group, "magenta"), &mut self.magenta, 0.);
visitor.parameter(&grouped_key(group, "yellow"), &mut self.yellow, 0.);
visitor.parameter(&grouped_key(group, "black"), &mut self.black, 0.);
}
}
impl ColorBalanceShifts {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
visitor.parameter(&grouped_key(group, "cyan_red"), &mut self.cyan_red, 0.);
visitor.parameter(&grouped_key(group, "magenta_green"), &mut self.magenta_green, 0.);
visitor.parameter(&grouped_key(group, "yellow_blue"), &mut self.yellow_blue, 0.);
}
}
@@ -0,0 +1,684 @@
//! An item's effects: an ordered list of image operations on the pixels the item renders to, stored in the `ATTR_EFFECTS` attribute.
//! Each row is an [`EffectKind`] whose parameters ride its item as attributes, read as their defaults when absent.
//! Each renderer decodes the rows into [`EffectOperation`]s and carries them out its own way, at the resolution of each render.
use crate::Graphic;
use crate::adjustment::Adjustment;
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
use core_types::ATTR_TRANSFORM;
use core_types::Color;
use core_types::blending::BlendMode;
use core_types::color::SRGBA8;
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_EFFECTS, Item, List};
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2, DVec3};
use std::fmt::Debug;
use vector_types::vector::style::StrokeAlign;
/// The image operation an [`Effect`] carries out.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash)]
pub enum EffectKind {
/// Softens the content by blurring it.
#[default]
Blur,
/// Casts the content's silhouette as a soft shadow beneath it.
DropShadow,
/// Casts a soft shadow inward from the content's edges, as if it were cut out of the surface.
InnerShadow,
/// Surrounds the content with a soft glow of its silhouette.
OuterGlow,
/// Glows inward from the content's edges, or outward from its center.
InnerGlow,
/// Shades the content's interior with soft bands from its silhouette cast two ways.
Satin,
/// Draws a band of color along the content's silhouette.
Outline,
/// Lights the content as if raised from the surface or pressed into it, with highlights and shadows along its edges.
BevelAndEmboss,
/// Paints over the content within its silhouette, mixing with its colors by a blend mode. A solid color paint is the color overlay adjustment.
PaintOverlay,
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
Desaturate,
GammaCorrection,
MakeOpaque,
BrightnessContrast,
Levels,
Curves,
BlackAndWhite,
HueSaturation,
Invert,
Threshold,
GradientMap,
Vibrance,
ChannelMixer,
SelectiveColor,
Posterize,
Exposure,
ColorBalance,
PhotoFilter,
ColorLookup,
}
impl std::fmt::Display for EffectKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Blur => "Blur",
Self::DropShadow => "Drop Shadow",
Self::InnerShadow => "Inner Shadow",
Self::OuterGlow => "Outer Glow",
Self::InnerGlow => "Inner Glow",
Self::Satin => "Satin",
Self::Outline => "Outline",
Self::BevelAndEmboss => "Bevel & Emboss",
Self::PaintOverlay => "Paint Overlay",
Self::Desaturate => "Desaturate",
Self::GammaCorrection => "Gamma Correction",
Self::MakeOpaque => "Make Opaque",
Self::BrightnessContrast => "Brightness/Contrast",
Self::Levels => "Levels",
Self::Curves => "Curves",
Self::BlackAndWhite => "Black & White",
Self::HueSaturation => "Hue/Saturation",
Self::Invert => "Invert",
Self::Threshold => "Threshold",
Self::GradientMap => "Gradient Map",
Self::Vibrance => "Vibrance",
Self::ChannelMixer => "Channel Mixer",
Self::SelectiveColor => "Selective Color",
Self::Posterize => "Posterize",
Self::Exposure => "Exposure",
Self::ColorBalance => "Color Balance",
Self::PhotoFilter => "Photo Filter",
Self::ColorLookup => "Color Lookup",
})
}
}
/// Where an inner glow starts from.
#[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 GlowSource {
/// Glows inward from the edges.
#[default]
Edge,
/// Glows outward from the center.
Center,
}
/// Which slopes a bevel shapes from the content's edges.
#[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(Dropdown)]
pub enum BevelStyle {
/// Slopes up from the edges into the content.
#[default]
InnerBevel,
/// Slopes down from the edges away from the content.
OuterBevel,
/// Slopes across the edges, half inside the content and half outside.
Emboss,
/// Slopes away from the edges both ways, as if pressed into the surface along them.
PillowEmboss,
}
/// Whether a bevel rises from the surface or sinks into it.
#[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 BevelDirection {
/// Raised from the surface.
#[default]
Up,
/// Pressed into the surface.
Down,
}
/// The deviation of the blur that rounds a bevel's slopes of `size`, in the same units.
pub fn bevel_smoothing(size: f64) -> f64 {
size.max(0.) / 4.
}
/// The unit vector toward a bevel's light from its `angle` and `altitude` in degrees, with `lengths_to_target` mapping document directions into the y-down space it's lit in.
pub fn bevel_light(angle: f64, altitude: f64, lengths_to_target: DMat2) -> DVec3 {
let (angle, altitude) = (angle.to_radians(), altitude.clamp(0., 90.).to_radians());
let across = (lengths_to_target * DVec2::new(angle.cos(), -angle.sin())).try_normalize().unwrap_or(DVec2::X);
(across * altitude.cos()).extend(altitude.sin())
}
/// An overlay's paint with its unit square fitted to `content_bounds`, the content's extent in the space it's drawn in, if it's a gradient or image without its own placement.
pub fn fitted_paint(paint: &Graphic, content_bounds: [DVec2; 2]) -> Option<Graphic> {
let unplaced = match paint {
Graphic::Gradient(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
Graphic::RasterCPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
Graphic::RasterGPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
_ => false,
};
if !unplaced {
return None;
}
let fit = DAffine2::from_translation(content_bounds[0]) * DAffine2::from_scale(content_bounds[1] - content_bounds[0]);
let mut paint = paint.clone();
match &mut paint {
Graphic::Gradient(item) => item.set_attribute(ATTR_TRANSFORM, fit),
Graphic::RasterCPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
Graphic::RasterGPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
_ => {}
}
Some(paint)
}
/// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item.
/// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct Effect(pub Item<EffectKind>);
impl Effect {
/// Creates an effect row carrying out the given operation, stamping only the parameters that differ from their implicit defaults.
pub fn new(operation: &EffectOperation) -> Self {
let mut item = Item::new_from_element(operation.kind());
operation.clone().visit_parameters(&mut WriteParameters(&mut item));
Self(item)
}
/// This effect's kind.
pub fn kind(&self) -> EffectKind {
*self.0.element()
}
/// Decodes the parameters into an [`EffectOperation`], falling back to the default for any absent attribute.
pub fn operation(&self) -> EffectOperation {
let mut operation = EffectOperation::placeholder(self.kind());
operation.visit_parameters(&mut ReadParameters(&|key| self.0.attributes().get_any(key)));
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
match operation {
EffectOperation::PaintOverlay {
paint: Graphic::Color(color),
blend_mode,
opacity,
} => EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: *color.element(),
blend_mode,
opacity,
}),
operation => operation,
}
}
}
/// An item's ordered list of effects. A blur acts on the result of those before it, while shadows and glows are cast from the content and stack in order beneath it (or within it, for an inner shadow).
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct Effects(pub List<Effect>);
impl Effects {
/// Creates the list of rows carrying out the given operations in order.
pub fn from_operations(operations: impl IntoIterator<Item = EffectOperation>) -> Self {
let mut effects = Self::default();
for operation in operations {
effects.0.push(Item::new_from_element(Effect::new(&operation)));
}
effects
}
/// The effects in the order they're carried out.
pub fn effects(&self) -> impl Iterator<Item = &Effect> {
self.0.iter_element_values()
}
/// The effects after the first `count`.
pub fn after(&self, count: usize) -> Self {
let mut remaining = Self::default();
for effect in self.effects().skip(count) {
remaining.0.push(Item::new_from_element(effect.clone()));
}
remaining
}
/// The effects decoded into the operations renderers carry out, in order.
pub fn operations(&self) -> impl Iterator<Item = EffectOperation> + '_ {
self.effects().map(Effect::operation)
}
/// How far past the content the effects together can paint, in document pixels.
pub fn reach(&self) -> f64 {
self.operations().map(|operation| operation.reach()).sum()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
/// How far an outline of `weight` reaches outside the silhouette's edge and inside it, by where it's aligned.
pub fn outline_extents(weight: f64, align: StrokeAlign) -> (f64, f64) {
match align {
StrokeAlign::Outside => (weight, 0.),
StrokeAlign::Inside => (0., weight),
StrokeAlign::Center => (weight / 2., weight / 2.),
}
}
/// Appends an effect to the item's list, after those already applied to it.
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS).0.push(Item::new_from_element(effect));
}
/// An effect's parameters decoded from its row, the form that renderers carry it out from. Lengths are in document pixels.
#[derive(Clone, Debug, PartialEq)]
pub enum EffectOperation {
Blur {
/// The standard deviation of the Gaussian, or the half width of the box.
radius: f64,
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
box_blur: bool,
/// Whether to blend the colors with their gamma encoding rather than in linear light.
gamma: bool,
},
DropShadow {
color: Color,
offset: DVec2,
blur: f64,
spread: f64,
},
InnerShadow {
color: Color,
offset: DVec2,
blur: f64,
spread: f64,
},
OuterGlow {
color: Color,
blur: f64,
spread: f64,
},
InnerGlow {
color: Color,
blur: f64,
/// How far the glow grows into the content before it softens.
choke: f64,
source: GlowSource,
},
Satin {
color: Color,
/// How far each of the two casts of the silhouette is moved, in opposite directions.
offset: DVec2,
blur: f64,
invert: bool,
},
Outline {
color: Color,
weight: f64,
align: StrokeAlign,
},
BevelAndEmboss {
style: BevelStyle,
/// How steep the slopes are, as a percentage.
depth: f64,
direction: BevelDirection,
/// How wide the slopes are.
size: f64,
/// How much the highlights and shadows are blurred.
soften: f64,
/// The direction the light comes from, in degrees counterclockwise from the right.
angle: f64,
/// How high the light is above the surface, in degrees from flat to straight overhead.
altitude: f64,
highlight_color: Color,
shadow_color: Color,
},
/// Paints over the content with a paint other than a solid color, since a solid one decodes into the color overlay adjustment instead.
PaintOverlay {
/// Placed in the space the content's item is, or fitted to the content's bounds if it's a gradient or image without its own placement.
paint: Graphic,
blend_mode: BlendMode,
/// Percent.
opacity: f64,
},
Adjustment(Adjustment),
}
impl EffectOperation {
/// The operation an effect of this kind carries out when its row gives none of its parameters, matching the defaults of the node that stamps it.
pub fn default_for(kind: EffectKind) -> Self {
Effect(Item::new_from_element(kind)).operation()
}
pub fn kind(&self) -> EffectKind {
match self {
Self::Blur { .. } => EffectKind::Blur,
Self::DropShadow { .. } => EffectKind::DropShadow,
Self::InnerShadow { .. } => EffectKind::InnerShadow,
Self::OuterGlow { .. } => EffectKind::OuterGlow,
Self::InnerGlow { .. } => EffectKind::InnerGlow,
Self::Satin { .. } => EffectKind::Satin,
Self::Outline { .. } => EffectKind::Outline,
Self::BevelAndEmboss { .. } => EffectKind::BevelAndEmboss,
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
Self::Adjustment(adjustment) => adjustment.kind(),
}
}
/// How far past the content this operation can paint, or reads from, in document pixels.
pub fn reach(&self) -> f64 {
// A Gaussian is negligible past three standard deviations
match self {
Self::Blur { radius, .. } => 3. * radius.max(0.),
Self::DropShadow { offset, blur, spread, .. } => offset.length() + spread.max(0.) + 3. * blur.max(0.),
Self::InnerShadow { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
Self::OuterGlow { blur, spread, .. } => spread.max(0.) + 3. * blur.max(0.),
Self::InnerGlow { blur, choke, .. } => choke.max(0.) + 3. * blur.max(0.),
Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
Self::Outline { weight, .. } => weight.max(0.),
Self::BevelAndEmboss { size, soften, .. } => size.max(0.) + 3. * (soften.max(0.) + bevel_smoothing(*size)),
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
}
}
/// An operation of this kind with arbitrary parameters, for a visitor to fill in.
fn placeholder(kind: EffectKind) -> Self {
match kind {
EffectKind::Blur => Self::Blur {
radius: 0.,
box_blur: false,
gamma: false,
},
EffectKind::DropShadow => Self::DropShadow {
color: Color::TRANSPARENT,
offset: DVec2::ZERO,
blur: 0.,
spread: 0.,
},
EffectKind::InnerShadow => Self::InnerShadow {
color: Color::TRANSPARENT,
offset: DVec2::ZERO,
blur: 0.,
spread: 0.,
},
EffectKind::OuterGlow => Self::OuterGlow {
color: Color::TRANSPARENT,
blur: 0.,
spread: 0.,
},
EffectKind::InnerGlow => Self::InnerGlow {
color: Color::TRANSPARENT,
blur: 0.,
choke: 0.,
source: GlowSource::default(),
},
EffectKind::Satin => Self::Satin {
color: Color::TRANSPARENT,
offset: DVec2::ZERO,
blur: 0.,
invert: false,
},
EffectKind::Outline => Self::Outline {
color: Color::TRANSPARENT,
weight: 0.,
align: StrokeAlign::default(),
},
EffectKind::BevelAndEmboss => Self::BevelAndEmboss {
style: BevelStyle::default(),
depth: 0.,
direction: BevelDirection::default(),
size: 0.,
soften: 0.,
angle: 0.,
altitude: 0.,
highlight_color: Color::TRANSPARENT,
shadow_color: Color::TRANSPARENT,
},
EffectKind::PaintOverlay => Self::PaintOverlay {
paint: Graphic::default(),
blend_mode: BlendMode::default(),
opacity: 0.,
},
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque),
EffectKind::BrightnessContrast => Self::Adjustment(Adjustment::BrightnessContrast {
brightness: 0.,
contrast: 0.,
use_classic: false,
classic_pivot: 0.,
}),
EffectKind::Levels => Self::Adjustment(Adjustment::Levels(Default::default())),
EffectKind::Curves => Self::Adjustment(Adjustment::Curves(Default::default())),
EffectKind::BlackAndWhite => Self::Adjustment(Adjustment::BlackAndWhite(Default::default())),
EffectKind::HueSaturation => Self::Adjustment(Adjustment::HueSaturation(Default::default())),
EffectKind::Invert => Self::Adjustment(Adjustment::Invert),
EffectKind::Threshold => Self::Adjustment(Adjustment::Threshold { min_luminance: 0., max_luminance: 0. }),
EffectKind::GradientMap => Self::Adjustment(Adjustment::GradientMap {
gradient: Default::default(),
reverse: false,
}),
EffectKind::Vibrance => Self::Adjustment(Adjustment::Vibrance { vibrance: 0., saturation: 0. }),
EffectKind::ChannelMixer => Self::Adjustment(Adjustment::ChannelMixer(Default::default())),
EffectKind::SelectiveColor => Self::Adjustment(Adjustment::SelectiveColor(Default::default())),
EffectKind::Posterize => Self::Adjustment(Adjustment::Posterize { levels: 0 }),
EffectKind::Exposure => Self::Adjustment(Adjustment::Exposure {
exposure: 0.,
offset: 0.,
gamma_correction: 0.,
}),
EffectKind::ColorBalance => Self::Adjustment(Adjustment::ColorBalance(Default::default())),
EffectKind::PhotoFilter => Self::Adjustment(Adjustment::PhotoFilter {
color: Color::TRANSPARENT,
density: 0.,
preserve_luminosity: false,
}),
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
}
}
/// Visits each parameter with the attribute it rides and its implicit default, the one listing that writing and reading rows share.
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
match self {
Self::Blur { radius, box_blur, gamma } => {
visitor.parameter("radius", radius, 0.);
visitor.parameter("box_blur", box_blur, false);
visitor.parameter("gamma", gamma, false);
}
Self::DropShadow { color, offset, blur, spread } | Self::InnerShadow { color, offset, blur, spread } => {
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
visitor.parameter("offset", offset, DVec2::splat(4.));
visitor.parameter("blur", blur, 4.);
visitor.parameter("spread", spread, 0.);
}
Self::OuterGlow { color, blur, spread } => {
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
visitor.parameter("blur", blur, 8.);
visitor.parameter("spread", spread, 0.);
}
Self::InnerGlow { color, blur, choke, source } => {
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
visitor.parameter("blur", blur, 8.);
visitor.parameter("choke", choke, 0.);
visitor.parameter("source", source, GlowSource::default());
}
Self::Satin { color, offset, blur, invert } => {
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
visitor.parameter("offset", offset, DVec2::new(10., 4.));
visitor.parameter("blur", blur, 14.);
visitor.parameter("invert", invert, true);
}
Self::Outline { color, weight, align } => {
visitor.parameter("color", color, Color::BLACK);
visitor.parameter("weight", weight, 3.);
visitor.parameter("align", align, StrokeAlign::Outside);
}
Self::BevelAndEmboss {
style,
depth,
direction,
size,
soften,
angle,
altitude,
highlight_color,
shadow_color,
} => {
visitor.parameter("style", style, BevelStyle::default());
visitor.parameter("depth", depth, 100.);
visitor.parameter("direction", direction, BevelDirection::default());
visitor.parameter("size", size, 5.);
visitor.parameter("soften", soften, 0.);
visitor.parameter("angle", angle, 120.);
visitor.parameter("altitude", altitude, 30.);
visitor.parameter("highlight_color", highlight_color, Color::from(SRGBA8::new(0xff, 0xff, 0xff, 0xbf)));
visitor.parameter("shadow_color", shadow_color, Color::from(SRGBA8::new(0, 0, 0, 0xbf)));
}
Self::PaintOverlay { paint, blend_mode, opacity } => {
visitor.parameter("paint", paint, Graphic::from(Color::BLACK));
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
visitor.parameter("opacity", opacity, 100.);
}
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use vector_types::{Gradient, GradientStop};
#[test]
fn rows_round_trip_their_operations_eliding_defaults() {
let operations = [
EffectOperation::Blur {
radius: 6.,
box_blur: true,
gamma: false,
},
EffectOperation::default_for(EffectKind::DropShadow),
EffectOperation::InnerShadow {
color: Color::RED,
offset: DVec2::new(-2., 3.),
blur: 1.,
spread: 5.,
},
EffectOperation::OuterGlow {
color: Color::BLUE,
blur: 8.,
spread: 2.,
},
EffectOperation::InnerGlow {
color: Color::GREEN,
blur: 3.,
choke: 1.,
source: GlowSource::Center,
},
EffectOperation::Satin {
color: Color::BLACK,
offset: DVec2::new(5., -6.),
blur: 2.,
invert: false,
},
EffectOperation::Outline {
color: Color::RED,
weight: 7.,
align: StrokeAlign::Center,
},
EffectOperation::BevelAndEmboss {
style: BevelStyle::PillowEmboss,
depth: 250.,
direction: BevelDirection::Down,
size: 12.,
soften: 2.,
angle: -45.,
altitude: 60.,
highlight_color: Color::YELLOW,
shadow_color: Color::BLUE,
},
EffectOperation::PaintOverlay {
paint: Graphic::from(Gradient::new([0., 1.].map(|position| GradientStop {
position,
midpoint: 0.5,
color: Color::from_rgbaf32_unchecked(position as f32, 0., 1., 1.),
}))),
blend_mode: BlendMode::Multiply,
opacity: 60.,
},
EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::GREEN,
blend_mode: BlendMode::Screen,
opacity: 100.,
}),
];
for operation in operations {
assert_eq!(Effect::new(&operation).operation(), operation);
}
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
let solid = EffectOperation::PaintOverlay {
paint: Graphic::from(Color::RED),
blend_mode: BlendMode::Normal,
opacity: 50.,
};
let solid_row = Effect::new(&solid);
assert_eq!(solid_row.kind(), EffectKind::PaintOverlay);
assert_eq!(
solid_row.operation(),
EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::RED,
blend_mode: BlendMode::Normal,
opacity: 50.,
})
);
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
}
#[test]
fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() {
use EffectKind::*;
let kinds = [
Desaturate,
GammaCorrection,
MakeOpaque,
BrightnessContrast,
Levels,
Curves,
BlackAndWhite,
HueSaturation,
Invert,
Threshold,
GradientMap,
Vibrance,
ChannelMixer,
SelectiveColor,
Posterize,
Exposure,
ColorBalance,
PhotoFilter,
ColorLookup,
PaintOverlay,
];
for kind in kinds {
let operation = EffectOperation::default_for(kind);
assert_eq!(operation.kind(), kind);
assert_eq!(Effect::new(&operation).0.attributes().iter_any().count(), 0, "{kind} stamps no defaults");
}
// A parameter in one of the node's groups rides the attribute named with the group's prefix
let mut levels = EffectOperation::default_for(Levels);
if let EffectOperation::Adjustment(Adjustment::Levels(settings)) = &mut levels {
settings.blue.midtones = 1.5;
}
let row = Effect::new(&levels);
assert_eq!(row.0.attribute::<f64>("blue_midtones"), Some(&1.5));
assert_eq!(row.operation(), levels);
}
}
@@ -0,0 +1,202 @@
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
use core_types::list::Item;
use dyn_any::DynAny;
use glam::DAffine2;
use std::any::Any;
/// Style of noise pattern.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
#[widget(Dropdown)]
pub enum NoiseType {
#[default]
Perlin,
#[label("OpenSimplex2")]
OpenSimplex2,
#[label("OpenSimplex2S")]
OpenSimplex2S,
Cellular,
ValueCubic,
Value,
WhiteNoise,
}
/// Style of layered levels of the noise pattern.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
pub enum FractalType {
#[default]
None,
#[label("Fractional Brownian Motion")]
FBm,
Ridged,
PingPong,
#[label("Progressive (Domain Warp Only)")]
DomainWarpProgressive,
#[label("Independent (Domain Warp Only)")]
DomainWarpIndependent,
}
/// Distance function used by the cellular noise.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
pub enum CellularDistanceFunction {
#[default]
Euclidean,
#[label("Euclidean Squared (Faster)")]
EuclideanSq,
Manhattan,
Hybrid,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
pub enum CellularReturnType {
CellValue,
#[default]
#[label("Nearest (F1)")]
Nearest,
#[label("Next Nearest (F2)")]
NextNearest,
#[label("Average (F1 / 2 + F2 / 2)")]
Average,
#[label("Difference (F2 - F1)")]
Difference,
#[label("Product (F2 * F1 / 2)")]
Product,
#[label("Division (F1 / F2)")]
Division,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
#[widget(Dropdown)]
pub enum DomainWarpType {
#[default]
None,
#[label("OpenSimplex2")]
OpenSimplex2,
#[label("OpenSimplex2 Reduced")]
OpenSimplex2Reduced,
BasicGrid,
}
/// The settings of a noise pattern, whose lengths are measured in the document units of the space it's sampled in.
#[derive(Debug, Clone, Default, PartialEq, CacheHash)]
pub struct NoiseSettings {
pub seed: i64,
pub scale: f64,
pub noise_type: NoiseType,
pub domain_warp_type: DomainWarpType,
pub domain_warp_amplitude: f64,
pub fractal_type: FractalType,
pub fractal_octaves: i64,
pub fractal_lacunarity: f64,
pub fractal_gain: f64,
pub fractal_weighted_strength: f64,
pub fractal_ping_pong_strength: f64,
pub cellular_distance_function: CellularDistanceFunction,
pub cellular_return_type: CellularReturnType,
pub cellular_jitter: f64,
}
/// A procedural pattern, a function of position in its own space that renders across any area at any resolution.
#[derive(Debug, Clone, PartialEq, CacheHash)]
pub enum GeneratorPattern {
Noise(NoiseSettings),
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
Mandelbrot,
}
/// A procedural pattern filling the whole plane, which renderers draw at whatever resolution they need across whatever part they see.
/// The item's transform places the pattern's own space, and a noise pattern's settings ride the item as attributes named after the Noise Pattern node's parameters.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny)]
pub enum Generator {
#[default]
Noise,
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
Mandelbrot,
}
impl std::fmt::Display for Generator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Noise => "Noise",
Self::Mandelbrot => "Mandelbrot",
})
}
}
impl BoundingBox for Generator {
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
match transform.matrix2.determinant() == 0. {
true => RenderBoundingBox::None,
false => RenderBoundingBox::Infinite,
}
}
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
self.bounding_box(transform, include_stroke)
}
}
impl NoiseSettings {
/// Stamps every setting onto the generator's item, whatever its value, so which attributes the item carries doesn't depend on them.
pub fn stamp(&self, item: &mut Item<Generator>) {
self.clone().visit_parameters(&mut StampParameters(item));
}
/// Visits each setting with the attribute it rides, named after the Noise Pattern node's parameter, and its default, which is the node's.
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
visitor.parameter("seed", &mut self.seed, 0);
visitor.parameter("scale", &mut self.scale, 10.);
visitor.parameter("noise_type", &mut self.noise_type, NoiseType::default());
visitor.parameter("domain_warp_type", &mut self.domain_warp_type, DomainWarpType::default());
visitor.parameter("domain_warp_amplitude", &mut self.domain_warp_amplitude, 100.);
visitor.parameter("fractal_type", &mut self.fractal_type, FractalType::default());
visitor.parameter("fractal_octaves", &mut self.fractal_octaves, 3);
visitor.parameter("fractal_lacunarity", &mut self.fractal_lacunarity, 2.);
visitor.parameter("fractal_gain", &mut self.fractal_gain, 0.5);
visitor.parameter("fractal_weighted_strength", &mut self.fractal_weighted_strength, 0.);
visitor.parameter("fractal_ping_pong_strength", &mut self.fractal_ping_pong_strength, 2.);
visitor.parameter("cellular_distance_function", &mut self.cellular_distance_function, CellularDistanceFunction::default());
visitor.parameter("cellular_return_type", &mut self.cellular_return_type, CellularReturnType::default());
visitor.parameter("cellular_jitter", &mut self.cellular_jitter, 1.);
}
}
impl GeneratorPattern {
/// The pattern a generator draws, reading a noise pattern's settings with `attribute`, which looks one of the item's attributes up by key.
/// Each setting the item lacks takes its default.
pub fn decode<'a>(generator: Generator, attribute: &'a dyn Fn(&str) -> Option<&'a dyn Any>) -> Self {
match generator {
Generator::Noise => {
let mut settings = NoiseSettings::default();
settings.visit_parameters(&mut ReadParameters(attribute));
Self::Noise(settings)
}
Generator::Mandelbrot => Self::Mandelbrot,
}
}
/// The pattern a generator item draws.
pub fn of_item(item: &Item<Generator>) -> Self {
Self::decode(*item.element(), &|key| item.attributes().get_any(key))
}
}
@@ -1,4 +1,5 @@
use crate::appearance::{Appearance, Cover, Coverage};
use crate::generator::Generator;
use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
@@ -26,6 +27,7 @@ pub enum Graphic {
RasterGPU(Item<Raster<GPU>>),
Color(Item<Color>),
Gradient(Item<Gradient>),
Generator(Item<Generator>),
Text(Item<String>),
NoneList(List<none::None>),
GraphicList(List<Graphic>),
@@ -34,6 +36,7 @@ pub enum Graphic {
RasterGPUList(List<Raster<GPU>>),
ColorList(List<Color>),
GradientList(List<Gradient>),
GeneratorList(List<Generator>),
TextList(List<String>),
StrokeList(List<Stroke>),
}
@@ -137,6 +140,23 @@ impl From<List<Gradient>> for Graphic {
}
}
// Generator
impl From<Generator> for Graphic {
fn from(generator: Generator) -> Self {
Graphic::Generator(Item::new_from_element(generator))
}
}
impl From<Item<Generator>> for Graphic {
fn from(generator: Item<Generator>) -> Self {
Graphic::Generator(generator)
}
}
impl From<List<Generator>> for Graphic {
fn from(generator: List<Generator>) -> Self {
Graphic::GeneratorList(generator)
}
}
// Stroke
impl From<Stroke> for Graphic {
fn from(stroke: Stroke) -> Self {
@@ -312,12 +332,14 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
Graphic::RasterCPU(item) => bake_item_transform(item, transform),
Graphic::RasterGPU(item) => bake_item_transform(item, transform),
Graphic::Gradient(item) => bake_item_transform(item, transform),
Graphic::Generator(item) => bake_item_transform(item, transform),
Graphic::Text(item) => bake_item_transform(item, transform),
Graphic::GraphicList(list) => bake_list_transform(list, transform),
Graphic::VectorList(list) => bake_list_transform(list, transform),
Graphic::RasterCPUList(list) => bake_list_transform(list, transform),
Graphic::RasterGPUList(list) => bake_list_transform(list, transform),
Graphic::GradientList(list) => bake_list_transform(list, transform),
Graphic::GeneratorList(list) => bake_list_transform(list, transform),
Graphic::TextList(list) => bake_list_transform(list, transform),
Graphic::StrokeList(list) => bake_list_transform(list, transform),
// A color has no spatial extent, so there is no placement for a transform to move
@@ -360,6 +382,16 @@ impl TryFromGraphic for Raster<CPU> {
}
}
impl TryFromGraphic for Raster<GPU> {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
match graphic {
Graphic::RasterGPU(item) => Some(List::new_from_item(item)),
Graphic::RasterGPUList(list) => Some(list),
_ => None,
}
}
}
impl TryFromGraphic for Color {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
match graphic {
@@ -380,6 +412,16 @@ impl TryFromGraphic for Gradient {
}
}
impl TryFromGraphic for Generator {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
match graphic {
Graphic::Generator(item) => Some(List::new_from_item(item)),
Graphic::GeneratorList(list) => Some(list),
_ => None,
}
}
}
impl TryFromGraphic for String {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
match graphic {
@@ -447,6 +489,12 @@ impl IntoGraphicList for List<Gradient> {
}
}
impl IntoGraphicList for List<Generator> {
fn into_graphic_list(self) -> List<Graphic> {
List::new_from_element(Graphic::GeneratorList(self))
}
}
impl IntoGraphicList for List<Stroke> {
fn into_graphic_list(self) -> List<Graphic> {
let layer_path: NodeIdPath = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
@@ -560,6 +608,7 @@ impl Graphic {
Graphic::RasterGPU(item) => item_clipped(item),
Graphic::Color(item) => item_clipped(item),
Graphic::Gradient(item) => item_clipped(item),
Graphic::Generator(item) => item_clipped(item),
Graphic::Text(item) => item_clipped(item),
Graphic::NoneList(list) => all_clipped(list),
Graphic::VectorList(list) => all_clipped(list),
@@ -568,6 +617,7 @@ impl Graphic {
Graphic::RasterGPUList(list) => all_clipped(list),
Graphic::ColorList(list) => all_clipped(list),
Graphic::GradientList(list) => all_clipped(list),
Graphic::GeneratorList(list) => all_clipped(list),
Graphic::TextList(list) => all_clipped(list),
Graphic::StrokeList(list) => all_clipped(list),
}
@@ -606,6 +656,7 @@ impl Graphic {
}
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
@@ -652,9 +703,11 @@ impl Graphic {
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
Graphic::Generator(item) => item_opacity_is_zero(item),
Graphic::Text(item) => item_opacity_is_zero(item),
Graphic::RasterCPUList(list) => every_item_has_zero_opacity(list),
Graphic::RasterGPUList(list) => every_item_has_zero_opacity(list),
Graphic::GeneratorList(list) => every_item_has_zero_opacity(list),
Graphic::TextList(list) => every_item_has_zero_opacity(list),
Graphic::StrokeList(list) => every_item_has_zero_opacity(list),
}
@@ -670,11 +723,12 @@ impl Graphic {
match self {
// A leaf always holds exactly one element, so only the none-typed content is truly empty
Graphic::None(_) | Graphic::NoneList(_) => true,
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Text(_) => false,
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) | Graphic::Text(_) => false,
Graphic::GraphicList(list) => list.is_empty(),
Graphic::VectorList(list) => list.is_empty(),
Graphic::ColorList(list) => list.is_empty(),
Graphic::GradientList(list) => list.is_empty(),
Graphic::GeneratorList(list) => list.is_empty(),
Graphic::RasterCPUList(list) => list.is_empty(),
Graphic::RasterGPUList(list) => list.is_empty(),
Graphic::TextList(list) => list.is_empty(),
@@ -831,6 +885,7 @@ impl BoundingBox for Graphic {
Graphic::RasterGPU(item) => item.bounding_box(transform, include_stroke),
Graphic::Color(item) => item.bounding_box(transform, include_stroke),
Graphic::Gradient(item) => item.bounding_box(transform, include_stroke),
Graphic::Generator(item) => item.bounding_box(transform, include_stroke),
Graphic::Text(item) => item.bounding_box(transform, include_stroke),
Graphic::VectorList(list) => vector_list_bounding_box(list, transform, include_stroke),
Graphic::RasterCPUList(list) => list.bounding_box(transform, include_stroke),
@@ -838,6 +893,7 @@ impl BoundingBox for Graphic {
Graphic::GraphicList(list) => list.bounding_box(transform, include_stroke),
Graphic::ColorList(list) => list.bounding_box(transform, include_stroke),
Graphic::GradientList(list) => list.bounding_box(transform, include_stroke),
Graphic::GeneratorList(list) => list.bounding_box(transform, include_stroke),
Graphic::TextList(list) => list.bounding_box(transform, include_stroke),
Graphic::StrokeList(list) => list.bounding_box(transform, include_stroke),
}
@@ -852,6 +908,7 @@ impl BoundingBox for Graphic {
Graphic::RasterGPU(item) => item.thumbnail_bounding_box(transform, include_stroke),
Graphic::Color(item) => item.thumbnail_bounding_box(transform, include_stroke),
Graphic::Gradient(item) => item.thumbnail_bounding_box(transform, include_stroke),
Graphic::Generator(item) => item.thumbnail_bounding_box(transform, include_stroke),
Graphic::Text(item) => item.thumbnail_bounding_box(transform, include_stroke),
Graphic::VectorList(vector) => vector_list_bounding_box(vector, transform, include_stroke),
Graphic::RasterCPUList(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
@@ -859,6 +916,7 @@ impl BoundingBox for Graphic {
Graphic::GraphicList(list) => list.thumbnail_bounding_box(transform, include_stroke),
Graphic::ColorList(color) => color.thumbnail_bounding_box(transform, include_stroke),
Graphic::GradientList(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
Graphic::GeneratorList(generator) => generator.thumbnail_bounding_box(transform, include_stroke),
Graphic::TextList(list) => list.thumbnail_bounding_box(transform, include_stroke),
Graphic::StrokeList(list) => list.thumbnail_bounding_box(transform, include_stroke),
}
@@ -1,6 +1,10 @@
pub mod adjustment;
pub mod appearance;
pub mod artboard;
pub mod effects;
pub mod generator;
pub mod graphic;
pub(crate) mod parameters;
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
pub use core_types;
@@ -8,8 +12,11 @@ pub use raster_types;
pub use vector_types;
// Re-export commonly used types at the crate root
pub use adjustment::Adjustment;
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
pub use artboard::Artboard;
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
pub use generator::Generator;
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
pub mod migrations {
@@ -0,0 +1,44 @@
//! Parameters riding an item as attributes, each read as its default when absent, which one listing per operation both writes and reads.
use core_types::graphene_hash::CacheHash;
use core_types::list::Item;
use std::any::Any;
use std::fmt::Debug;
/// What a value needs to ride an attribute.
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
/// Handles each parameter of an operation, given the attribute key it rides and its default.
pub(crate) trait ParameterVisitor {
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
}
/// Stamps each parameter that differs from its default onto an item, for rows whose attributes are part of their value.
pub(crate) struct WriteParameters<'a, T>(pub &'a mut Item<T>);
impl<T> ParameterVisitor for WriteParameters<'_, T> {
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, default: U) {
if *value != default {
self.0.set_attribute(key, value.clone());
}
}
}
/// Stamps every parameter onto an item, for an item on a wire, whose attributes mustn't come and go with their values.
pub(crate) struct StampParameters<'a, T>(pub &'a mut Item<T>);
impl<T> ParameterVisitor for StampParameters<'_, T> {
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, _default: U) {
self.0.set_attribute(key, value.clone());
}
}
/// Reads each parameter from the attribute that the lookup finds by key, or its default where there's none.
pub(crate) struct ReadParameters<'a>(pub &'a dyn Fn(&str) -> Option<&'a dyn Any>);
impl ParameterVisitor for ReadParameters<'_> {
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
*value = (self.0)(key).and_then(|value| value.downcast_ref::<T>()).cloned().unwrap_or(default);
}
}
@@ -1,40 +0,0 @@
[package]
name = "no-std-types"
description = "Color, blending, and context types for Graphene"
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
[features]
wasm = ["tsify", "wasm-bindgen"]
[dependencies]
# Local dependencies
dyn-any = { workspace = true }
graphene-hash = { workspace = true }
# Workspace dependencies
bytemuck = { workspace = true }
glam = { workspace = true, features = ["debug-glam-assert", "std", "serde"] }
half = { workspace = true, features = ["std", "serde"] }
num-derive = { workspace = true }
num-traits = { workspace = true, features = ["std"] }
num_enum = { workspace = true, features = ["std"] }
serde = { workspace = true }
log = { workspace = true }
# Workspace wasm dependencies
tsify = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
[dev-dependencies]
core-types = { workspace = true }
[package.metadata.cargo-shear]
ignored = ["core-types"]
@@ -1,8 +0,0 @@
pub trait Ctx: Clone + Send {}
impl<T: Ctx> Ctx for Option<T> {}
impl<T: Ctx + Sync> Ctx for &T {}
impl Ctx for () {}
pub trait ArcCtx: Send + Sync {}
impl<T: ArcCtx> Ctx for std::sync::Arc<T> {}
@@ -1,16 +0,0 @@
pub mod blending;
pub mod choice_type;
pub mod color;
pub mod context;
pub use context::Ctx;
pub use glam;
pub trait AsU32 {
fn as_u32(&self) -> u32;
}
impl AsU32 for u32 {
fn as_u32(&self) -> u32 {
*self
}
}
@@ -0,0 +1,26 @@
[package]
name = "raster-kernels"
description = "The GPU kernels of Graphene's raster operations, with the per-color CPU mapping of those that have one"
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 }
graphene-resource = { workspace = true }
graphic-types = { workspace = true }
vector-types = { workspace = true }
# Workspace dependencies
glam = { workspace = true }
thiserror = { workspace = true }
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,29 @@
//! The kernels blending one color with another.
use crate::{MapColor, Wgsl, gpu_param_enum, gpu_params};
use core_types::blending::{BlendMode, apply_blend_mode};
use core_types::color::Color;
gpu_param_enum!(i32: BlendMode);
gpu_params! {
#[derive(Clone)]
pub(crate) struct ColorOverlay {
pub(crate) color: Color,
pub(crate) blend_mode: BlendMode,
pub(crate) opacity: f32,
}
}
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())
}
fn wgsl() -> Wgsl {
Wgsl::function(format!("{}\n{}", include_str!("wgsl/blending.wgsl"), include_str!("wgsl/color_overlay.wgsl")))
}
}
@@ -0,0 +1,121 @@
//! The passes of a Gaussian or box blur, which halve an image until its kernel fits one pass, blur it along each axis, and double it back.
use crate::{RasterKernel, ToGpuParams, Wgsl, gpu_param_enum, gpu_params};
/// The farthest texel from the center a blur pass weighs, beyond which the image is first halved until the kernel fits.
pub const MAX_BLUR_REACH: i32 = 64;
/// The radius of a blur over texels `scale` image pixels wide, and the farthest texel from the center it weighs.
///
/// A box covers its whole texels and a fraction of the texel at each end, which keeps the window as wide as the whole pixel window of the unhalved image once halved,
/// and a Gaussian leaves out the blur that halving and doubling the image add.
pub fn blur_extent(radius: f64, box_blur: bool, scale: u32) -> (f32, i32) {
let scale = scale as f64;
if box_blur {
let radius = ((radius as i32) as f64 + 0.5) / scale - 0.5;
(radius as f32, radius.ceil() as i32)
} else {
let radius = (radius * radius - (scale * scale - 1.) / 3.).max(0.).sqrt() / scale;
(radius as f32, (3. * radius).ceil() as i32)
}
}
/// The colors a blur pass reads from its input or writes to its output, around the premultiplied colors it sums.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum BlurSpace {
/// Values summed as they are, such as premultiplied colors or coverage.
Premultiplied,
/// Straight-alpha linear-light colors, premultiplied for summing.
Linear,
/// Straight-alpha linear-light colors, gamma-encoded and premultiplied for summing.
Gamma,
}
impl From<BlurSpace> for u32 {
fn from(space: BlurSpace) -> Self {
space as u32
}
}
gpu_param_enum!(u32: BlurSpace);
gpu_params! {
/// Averages each 2x2 block of texels `scale` image pixels wide, weighed by how much of the `full_size` image each covers.
#[derive(Clone)]
pub struct BlurHalve {
pub space: BlurSpace,
pub scale: i32,
pub full_size: [i32; 2],
}
}
impl RasterKernel for BlurHalve {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_halve.wgsl")))
}
}
gpu_params! {
/// One axis of a blur over texels `scale` image pixels wide, each weighed by how much of the `full_size` image it covers.
#[derive(Clone)]
pub struct BlurPass {
pub radius: f32,
pub reach: i32,
pub box_blur: bool,
pub space: BlurSpace,
pub scale: i32,
pub full_size: [i32; 2],
}
}
pub struct BlurHorizontal(pub BlurPass);
impl ToGpuParams for BlurHorizontal {
type Params = BlurPass;
fn to_params(&self) -> BlurPass {
self.0.clone()
}
}
impl RasterKernel for BlurHorizontal {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_horizontal.wgsl")))
}
}
/// Reads its input in pairs of texels sampled bilinearly between them, so the input must be in a filterable format.
pub struct BlurVertical(pub BlurPass);
impl ToGpuParams for BlurVertical {
type Params = BlurPass;
fn to_params(&self) -> BlurPass {
self.0.clone()
}
}
impl RasterKernel for BlurVertical {
const INPUTS: usize = 1;
const FILTERED: bool = true;
fn wgsl() -> Wgsl {
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_vertical.wgsl")))
}
}
gpu_params! {
#[derive(Clone)]
pub struct BlurUpsample {
pub scale: f32,
pub space: BlurSpace,
}
}
impl RasterKernel for BlurUpsample {
const INPUTS: usize = 1;
const FILTERED: bool = true;
fn wgsl() -> Wgsl {
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_upsample.wgsl")))
}
}
@@ -7,36 +7,39 @@ mod format_icc;
mod format_look;
use crate::adjustments::{SRGB_TO_XYZ_D50, WHITE_XYZ_D50, XYZ_D50_TO_SRGB, multiply_matrix};
use core_types::color::{linear_to_srgb, srgb_to_linear};
use graphene_resource::{Resource, ResourceHash};
use no_std_types::color::{linear_to_srgb, srgb_to_linear};
use std::sync::{Arc, Mutex, PoisonError};
pub const LUT_FILE_EXTENSIONS: &[&str] = &["cube", "3dl", "look", "csp", "icc", "icm"];
/// How many files keep their parse results after the adjustments that read them move on to other files.
const MAX_PARSED_FILES: usize = 8;
/// A file's parse result, in the form the cache shares out.
type ParsedLut = Result<Arc<Lut>, LutParseError>;
/// The last file a node parsed, kept as the node's own data so the file is not parsed anew each time the node runs again.
#[derive(Debug, Clone, Default)]
pub struct LutCache(Arc<Mutex<Option<(ResourceHash, ParsedLut)>>>);
/// The files parsed most recently, least recent first, shared by every adjustment that reads a lookup table.
static PARSED_FILES: Mutex<Vec<(ResourceHash, ParsedLut)>> = Mutex::new(Vec::new());
impl LutCache {
/// [`Lut::parse`] for a resource, reusing the last result while the file's content hash stays the same.
pub fn parse(&self, resource: &Resource) -> ParsedLut {
// A lock poisoned by a panic elsewhere still guards a usable cache
let mut cached = self.0.lock().unwrap_or_else(PoisonError::into_inner);
/// [`Lut::parse`] for a resource, reusing the result while recent adjustments keep reading a file with the same content hash.
pub fn parse_cached(resource: &Resource) -> ParsedLut {
// A lock poisoned by a panic elsewhere still guards a usable cache
let mut parsed_files = PARSED_FILES.lock().unwrap_or_else(PoisonError::into_inner);
let hash = resource.hash();
if let Some((cached_hash, result)) = cached.as_ref()
&& *cached_hash == hash
{
return result.clone();
}
let result = Lut::parse(resource).map(Arc::new);
*cached = Some((hash, result.clone()));
result
let hash = resource.hash();
if let Some(index) = parsed_files.iter().position(|(parsed_hash, _)| *parsed_hash == hash) {
let entry = parsed_files.remove(index);
let result = entry.1.clone();
parsed_files.push(entry);
return result;
}
let result = Lut::parse(resource).map(Arc::new);
parsed_files.push((hash, result.clone()));
let excess = parsed_files.len().saturating_sub(MAX_PARSED_FILES);
parsed_files.drain(..excess);
result
}
/// Why a file could not be read as a lookup table.
@@ -348,6 +351,55 @@ impl Lut {
None => result,
}
}
/// The mapping as one grid, which [`Lut::apply`] matches by tetrahedral interpolation of the input normalized over the grid's domain:
/// the 3D table itself when the mapping is nothing more, otherwise the whole mapping sampled at `GRID_SIZE` points per axis across 0 to 1.
pub fn grid(&self) -> LutGrid {
if self.lab_encoding.is_none()
&& self.input_curves.is_none()
&& self.output_stages.is_empty()
&& let Some(LutTable::ThreeDimensional { size, red_fastest, entries }) = &self.table
&& size[0] == size[1]
&& size[1] == size[2]
{
let size = size[0];
let entries = if *red_fastest {
entries.clone()
} else {
(0..size.pow(3))
.map(|index| entries[((index % size) * size + index / size % size) * size + index / (size * size)])
.collect()
};
return LutGrid {
domain_min: self.domain_min,
domain_max: self.domain_max,
size,
entries,
};
}
let last = (GRID_SIZE - 1) as f32;
let entries = (0..GRID_SIZE.pow(3))
.map(|index| self.apply([index % GRID_SIZE, index / GRID_SIZE % GRID_SIZE, index / (GRID_SIZE * GRID_SIZE)].map(|step| step as f32 / last)))
.collect();
LutGrid {
domain_min: [0.; 3],
domain_max: [1.; 3],
size: GRID_SIZE,
entries,
}
}
}
/// The points per axis of the grid that samples a mapping holding more than one 3D table.
const GRID_SIZE: usize = 33;
/// A cube of `size` entries per axis, red fastest, then green, then blue, spanning the input range `domain_min..domain_max`.
pub struct LutGrid {
pub domain_min: [f32; 3],
pub domain_max: [f32; 3],
pub size: usize,
pub entries: Vec<[f32; 3]>,
}
/// Gamma-encoded sRGB to CIELAB against the D50 white of the ICC profile connection space.
@@ -423,18 +475,16 @@ mod tests {
}
#[test]
fn a_cache_parses_a_file_once_until_the_file_changes() {
let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n1 1 1\n".to_vec());
let cache = LutCache::default();
let first = cache.parse(&file).unwrap();
assert!(Arc::ptr_eq(&first, &cache.parse(&file).unwrap()));
fn the_cache_parses_a_file_once_while_it_stays_recent() {
let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n0.5 1 1\n".to_vec());
let first = parse_cached(&file).unwrap();
assert!(Arc::ptr_eq(&first, &parse_cached(&file).unwrap()));
// A cloned node shares its cache
assert!(Arc::ptr_eq(&first, &cache.clone().parse(&file).unwrap()));
// Another file takes its place, a failed one included
assert!(cache.parse(&Resource::new(b"hello world".to_vec())).is_err());
assert!(!Arc::ptr_eq(&first, &cache.parse(&file).unwrap()));
// Enough other files push it out, failed ones included
for index in 0..MAX_PARSED_FILES {
assert!(parse_cached(&Resource::new(format!("not a table {index}").into_bytes())).is_err());
}
assert!(!Arc::ptr_eq(&first, &parse_cached(&file).unwrap()));
}
#[test]
@@ -0,0 +1,263 @@
//! The kernels of the passes that carry out an item's effects on the pixels of its content.
//! They work on images of premultiplied gamma-encoded channels, as Vello GPU blends, and on coverage held in every channel.
use crate::{RasterKernel, Wgsl, gpu_params};
use core_types::Color;
use core_types::blending::BlendMode;
/// A color as the premultiplied, gamma-encoded channels the passes work with, carried in a [`Color`] to be passed to them.
pub fn premultiplied_gamma_channels(color: Color) -> Color {
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
Color::from_rgbaf32_unchecked(red * alpha, green * alpha, blue * alpha, alpha)
}
gpu_params! {
/// The straight-alpha linear-light content, placed where its input lies, as the channels the passes work with, multiplied by `amount`.
#[derive(Clone)]
pub struct EffectEncode {
pub amount: f32,
}
}
impl RasterKernel for EffectEncode {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_encode.wgsl"))
}
}
gpu_params! {
/// The channels the passes work with, back into straight-alpha linear-light colors.
#[derive(Clone)]
pub struct EffectDecode {}
}
impl RasterKernel for EffectDecode {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_decode.wgsl"))
}
}
gpu_params! {
/// The coverage of the content's silhouette, or of the area outside it if `inverse`, cast by its input's placement.
#[derive(Clone)]
pub struct CastSilhouette {
pub inverse: bool,
}
}
impl RasterKernel for CastSilhouette {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_cast_silhouette.wgsl"))
}
}
gpu_params! {
/// The most coverage of its three inputs, the same coverage placed at the pixel and a step to either side along an axis.
#[derive(Clone)]
pub struct Dilate {}
}
impl RasterKernel for Dilate {
const INPUTS: usize = 3;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_dilate.wgsl"))
}
}
gpu_params! {
/// A silhouette's coverage in `color`, given as [`premultiplied_gamma_channels`].
#[derive(Clone)]
pub struct Tint {
pub color: Color,
}
}
impl RasterKernel for Tint {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_tint.wgsl"))
}
}
gpu_params! {
/// Stacks a silhouette's coverage, tinted `color` (given as [`premultiplied_gamma_channels`]), over the shadows and glows beneath the content.
#[derive(Clone)]
pub struct Accumulate {
pub color: Color,
}
}
impl RasterKernel for Accumulate {
const INPUTS: usize = 2;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_accumulate.wgsl"))
}
}
gpu_params! {
/// The image with a silhouette's coverage, tinted `color` (given as [`premultiplied_gamma_channels`]), placed over it within the full-strength content.
#[derive(Clone)]
pub struct CompositeWithin {
pub color: Color,
}
}
impl RasterKernel for CompositeWithin {
const INPUTS: usize = 3;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_composite_within.wgsl"))
}
}
gpu_params! {
/// The image with the shadows and glows beneath it, knocked out by the full-strength content.
#[derive(Clone)]
pub struct CompositeBeneath {}
}
impl RasterKernel for CompositeBeneath {
const INPUTS: usize = 3;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_composite_beneath.wgsl"))
}
}
gpu_params! {
/// The coverage of everything a coverage doesn't cover.
#[derive(Clone)]
pub struct InvertCoverage {}
}
impl RasterKernel for InvertCoverage {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_invert_coverage.wgsl"))
}
}
gpu_params! {
/// The coverage of satin's shading, from the two casts of the silhouette.
#[derive(Clone)]
pub struct SatinShading {
pub invert: bool,
}
}
impl RasterKernel for SatinShading {
const INPUTS: usize = 2;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_satin.wgsl"))
}
}
gpu_params! {
/// Starts a jump flood from the texels inside the content's silhouette, or outside it if `inward`.
#[derive(Clone)]
pub struct JumpFloodSeed {
pub inward: bool,
}
}
impl RasterKernel for JumpFloodSeed {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_jump_flood_seed.wgsl"))
}
}
gpu_params! {
/// One step of a jump flood, spreading the nearest seeds found so far by `step` texels.
#[derive(Clone)]
pub struct JumpFloodStep {
pub step: i32,
}
}
impl RasterKernel for JumpFloodStep {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_jump_flood_step.wgsl"))
}
}
gpu_params! {
/// The coverage of the band `width` texels wide along the silhouette's edge, from a finished jump flood.
#[derive(Clone)]
pub struct EdgeBand {
pub width: f32,
}
}
impl RasterKernel for EdgeBand {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_edge_band.wgsl"))
}
}
gpu_params! {
/// A bevel's height from 0 to 1, from the two finished jump floods across the silhouette's edge. `style` is a [`graphic_types::BevelStyle`].
#[derive(Clone)]
pub struct BevelHeight {
pub size: f32,
pub style: u32,
}
}
impl RasterKernel for BevelHeight {
const INPUTS: usize = 2;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_bevel_height.wgsl"))
}
}
gpu_params! {
/// The coverage of a bevel's highlight, or if `shadow` of its shadow, from its height lit from the direction of the unit vector `light`.
#[derive(Clone)]
pub struct BevelShading {
pub slope: f32,
pub light_x: f32,
pub light_y: f32,
pub light_z: f32,
pub shadow: bool,
}
}
impl RasterKernel for BevelShading {
const INPUTS: usize = 1;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_bevel_shading.wgsl"))
}
}
gpu_params! {
/// The first image, emptied wherever the second is empty, since an adjustment that changes alpha would otherwise conjure content from the empty space around it.
#[derive(Clone)]
pub struct KeepEmpty {}
}
impl RasterKernel for KeepEmpty {
const INPUTS: usize = 2;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/effect_keep_empty.wgsl"))
}
}
gpu_params! {
/// The image (input 0) with a straight-alpha linear-light paint (input 1) mixed over its colors by a blend mode, as much as the paint covers and `opacity` lets it, keeping the image's alpha.
#[derive(Clone)]
pub struct PaintOverlay {
pub blend_mode: BlendMode,
pub opacity: f32,
}
}
impl RasterKernel for PaintOverlay {
const INPUTS: usize = 2;
fn wgsl() -> Wgsl {
Wgsl::function(format!("{}\n{}", include_str!("wgsl/blending.wgsl"), include_str!("wgsl/effect_paint_overlay.wgsl")))
}
}
@@ -0,0 +1,183 @@
//! The kernels rendering each [`GeneratorPattern`] across any area of its space at any resolution.
use crate::{RasterKernel, RasterKernelVisitor, Wgsl, gpu_params};
use glam::{DVec2, UVec2, Vec2};
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
/// Hands `visitor` the kernel rendering `pattern` across `area` of its own space, from its minimum to its maximum corner, into a grid of `size` pixels.
pub fn visit_generator_kernel<V: RasterKernelVisitor>(pattern: &GeneratorPattern, area: [DVec2; 2], size: UVec2, visitor: V) -> V::Output {
let texel = ((area[1] - area[0]).as_vec2() / size.as_vec2()).to_array();
let corner = area[0].as_vec2().to_array();
match pattern {
GeneratorPattern::Noise(settings) => visit_noise_kernel(settings, corner, texel, visitor),
GeneratorPattern::Mandelbrot => visitor.visit(&Mandelbrot {
corner: (Vec2::from(corner) * 3. - Vec2::new(2., 1.5)).to_array(),
texel: (Vec2::from(texel) * 3.).to_array(),
}),
}
}
fn visit_noise_kernel<V: RasterKernelVisitor>(settings: &NoiseSettings, corner: [f32; 2], texel: [f32; 2], visitor: V) -> V::Output {
let NoiseSettings {
seed,
scale,
noise_type,
domain_warp_type,
domain_warp_amplitude,
fractal_type,
fractal_octaves,
fractal_lacunarity,
fractal_gain,
fractal_weighted_strength,
fractal_ping_pong_strength,
cellular_distance_function,
cellular_return_type,
cellular_jitter,
} = *settings;
if noise_type == NoiseType::WhiteNoise {
return visitor.visit(&WhiteNoise { corner, texel, seed: seed as u32 });
}
let domain_warp_type = match domain_warp_type {
DomainWarpType::None => None,
DomainWarpType::OpenSimplex2 => Some(0),
DomainWarpType::OpenSimplex2Reduced => Some(1),
DomainWarpType::BasicGrid => Some(2),
};
let noise = NoiseState {
seed: seed as i32,
frequency: 1. / (scale as f32).max(f32::EPSILON),
noise_type: match noise_type {
NoiseType::OpenSimplex2 | NoiseType::WhiteNoise => 0,
NoiseType::OpenSimplex2S => 1,
NoiseType::Cellular => 2,
NoiseType::Perlin => 3,
NoiseType::ValueCubic => 4,
NoiseType::Value => 5,
},
rotation_type_3d: 0,
fractal_type: match fractal_type {
FractalType::None => 0,
FractalType::FBm => 1,
FractalType::Ridged => 2,
FractalType::PingPong => 3,
FractalType::DomainWarpProgressive => 4,
FractalType::DomainWarpIndependent => 5,
},
octaves: fractal_octaves as i32,
lacunarity: fractal_lacunarity as f32,
gain: fractal_gain as f32,
weighted_strength: fractal_weighted_strength as f32,
ping_pong_strength: fractal_ping_pong_strength as f32,
cellular_distance_func: match cellular_distance_function {
CellularDistanceFunction::Euclidean => 0,
CellularDistanceFunction::EuclideanSq => 1,
CellularDistanceFunction::Manhattan => 2,
CellularDistanceFunction::Hybrid => 3,
},
cellular_return_type: match cellular_return_type {
CellularReturnType::CellValue => 0,
CellularReturnType::Nearest => 1,
CellularReturnType::NextNearest => 2,
CellularReturnType::Average => 3,
CellularReturnType::Difference => 4,
CellularReturnType::Product => 5,
CellularReturnType::Division => 6,
},
cellular_jitter_mod: cellular_jitter as f32,
domain_warp_type: domain_warp_type.unwrap_or(0),
domain_warp_amp: domain_warp_amplitude as f32,
};
visitor.visit(&NoisePattern {
corner,
texel,
domain_warp: domain_warp_type.is_some() && domain_warp_amplitude > 0.,
noise,
})
}
gpu_params! {
#[derive(Clone)]
struct NoiseState {
seed: i32,
frequency: f32,
noise_type: i32,
rotation_type_3d: i32,
fractal_type: i32,
octaves: i32,
lacunarity: f32,
gain: f32,
weighted_strength: f32,
ping_pong_strength: f32,
cellular_distance_func: i32,
cellular_return_type: i32,
cellular_jitter_mod: f32,
domain_warp_type: i32,
domain_warp_amp: f32,
}
}
gpu_params! {
#[derive(Clone)]
struct NoisePattern {
corner: [f32; 2],
texel: [f32; 2],
domain_warp: bool,
noise: NoiseState,
}
}
impl RasterKernel for NoisePattern {
const INPUTS: usize = 0;
fn wgsl() -> Wgsl {
Wgsl::function(concat!(include_str!("wgsl/fast_noise_lite.wgsl"), "\n", include_str!("wgsl/noise_pattern.wgsl")))
}
}
gpu_params! {
#[derive(Clone)]
struct WhiteNoise {
corner: [f32; 2],
texel: [f32; 2],
seed: u32,
}
}
impl RasterKernel for WhiteNoise {
const INPUTS: usize = 0;
fn wgsl() -> Wgsl {
Wgsl::function(include_str!("wgsl/white_noise.wgsl"))
}
}
gpu_params! {
#[derive(Clone)]
struct Mandelbrot {
corner: [f32; 2],
texel: [f32; 2],
}
}
impl RasterKernel for Mandelbrot {
const INPUTS: usize = 0;
fn wgsl() -> Wgsl {
Wgsl::body(
r#"
let c = vec2<f32>(coord) * vec2<f32>(texel[0], texel[1]) + vec2<f32>(corner[0], corner[1]);
var z = vec2<f32>(0.);
for (var iteration = 0u; iteration < 1024u; iteration++) {
z = vec2<f32>(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c;
let magnitude_squared = dot(z, z);
if magnitude_squared > 65536. {
let smooth_iteration = f32(iteration) + 1. - log2(0.5 * log2(magnitude_squared));
return vec4<f32>(vec3<f32>(clamp(smooth_iteration / 255., 0., 1.)), 1.);
}
}
return vec4<f32>(1.);
"#,
)
}
}
@@ -0,0 +1,385 @@
use core_types::color::Color;
/// The WGSL of a [`MapColor`] or [`RasterKernel`], which sees the shared prelude and the `Params` struct with its `params()` accessor.
pub enum Wgsl {
/// The body of the kernel's function, with every parameter bound as a local.
Body(String),
/// A source defining the kernel's function and any helpers it calls.
Function(String),
}
impl Wgsl {
pub fn body(body: impl Into<String>) -> Self {
Self::Body(body.into())
}
pub fn function(source: impl Into<String>) -> Self {
Self::Function(source.into())
}
}
/// A parameter struct passed to a [`MapColor`] or [`RasterKernel`] shader, declared with [`gpu_params!`].
pub trait GpuParams {
fn write(&self, slots: &mut Vec<u32>);
/// The WGSL declarations of the struct and its nested structs, aliased as `Params`, and the `params()` accessor, or nothing for a struct without fields.
fn wgsl() -> String;
/// The WGSL statements binding every field of `params()` as a local.
fn wgsl_locals() -> String;
/// The WGSL declaring the texture and accessors of each lookup field, bound in order from `binding`.
fn wgsl_lookups(_binding: usize) -> String {
String::new()
}
/// The tables of the lookup fields, in order.
fn lookups(&self) -> Vec<RasterKernelLookup<'_>> {
Vec::new()
}
}
/// A field type of a [`gpu_params!`] struct, occupying `SLOTS` 32-bit uniform slots.
pub trait GpuParamField {
const SLOTS: usize;
/// Whether the type is a lookup table, bound as its own texture rather than packed into slots, which only a top-level field may be.
const LOOKUP: bool = false;
fn wgsl_type() -> String;
fn write(&self, slots: &mut Vec<u32>);
fn wgsl_read(slot: usize) -> String;
/// Appends the WGSL struct declarations this type needs, each only once.
fn wgsl_declarations(_declarations: &mut Vec<String>) {}
/// The WGSL declaring a lookup table's texture at `binding` and its accessors named after `field`.
fn wgsl_lookup(_field: &str, _binding: usize) -> String {
String::new()
}
fn lookup<'a>(&'a self, _lookups: &mut Vec<RasterKernelLookup<'a>>) {}
}
fn wgsl_slot(slot: usize) -> String {
format!("uniform_params[{}][{}]", slot / 4, slot % 4)
}
impl GpuParamField for f32 {
const SLOTS: usize = 1;
fn wgsl_type() -> String {
"f32".into()
}
fn write(&self, slots: &mut Vec<u32>) {
slots.push(self.to_bits());
}
fn wgsl_read(slot: usize) -> String {
format!("bitcast<f32>({})", wgsl_slot(slot))
}
}
impl GpuParamField for u32 {
const SLOTS: usize = 1;
fn wgsl_type() -> String {
"u32".into()
}
fn write(&self, slots: &mut Vec<u32>) {
slots.push(*self);
}
fn wgsl_read(slot: usize) -> String {
wgsl_slot(slot)
}
}
impl GpuParamField for i32 {
const SLOTS: usize = 1;
fn wgsl_type() -> String {
"i32".into()
}
fn write(&self, slots: &mut Vec<u32>) {
slots.push(*self as u32);
}
fn wgsl_read(slot: usize) -> String {
format!("bitcast<i32>({})", wgsl_slot(slot))
}
}
impl GpuParamField for bool {
const SLOTS: usize = 1;
fn wgsl_type() -> String {
"bool".into()
}
fn write(&self, slots: &mut Vec<u32>) {
slots.push(*self as u32);
}
fn wgsl_read(slot: usize) -> String {
format!("{} != 0u", wgsl_slot(slot))
}
}
impl GpuParamField for Color {
const SLOTS: usize = 4;
fn wgsl_type() -> String {
"vec4<f32>".into()
}
fn write(&self, slots: &mut Vec<u32>) {
slots.extend(self.to_vec4().to_array().map(f32::to_bits));
}
fn wgsl_read(slot: usize) -> String {
let channels = (slot..slot + 4).map(<f32 as GpuParamField>::wgsl_read).collect::<Vec<_>>();
format!("vec4<f32>({})", channels.join(", "))
}
}
impl<T: GpuParamField, const N: usize> GpuParamField for [T; N] {
const SLOTS: usize = N * T::SLOTS;
fn wgsl_type() -> String {
format!("array<{}, {N}>", T::wgsl_type())
}
fn write(&self, slots: &mut Vec<u32>) {
self.iter().for_each(|element| element.write(slots));
}
fn wgsl_read(slot: usize) -> String {
let elements = (0..N).map(|index| T::wgsl_read(slot + index * T::SLOTS)).collect::<Vec<_>>();
format!("{}({})", Self::wgsl_type(), elements.join(", "))
}
fn wgsl_declarations(declarations: &mut Vec<String>) {
T::wgsl_declarations(declarations);
}
}
/// A lookup field of entries spread evenly across 0 to 1, read in WGSL by `fn <field>(t: f32) -> vec4<f32>`, which clamps `t` and interpolates linearly between the nearest two entries.
///
/// Holds 1 to 4096 entries, the texture width every device supports.
#[derive(Debug, Clone, PartialEq)]
pub struct Lut1d(pub Vec<Color>);
impl GpuParamField for Lut1d {
const SLOTS: usize = 0;
const LOOKUP: bool = true;
fn wgsl_type() -> String {
String::new()
}
fn write(&self, _: &mut Vec<u32>) {}
fn wgsl_read(_: usize) -> String {
String::new()
}
fn wgsl_lookup(field: &str, binding: usize) -> String {
include_str!("wgsl/lut_1d.wgsl").replace("LUT", field).replace("BINDING", &binding.to_string())
}
fn lookup<'a>(&'a self, lookups: &mut Vec<RasterKernelLookup<'a>>) {
assert!((1..=4096).contains(&self.0.len()), "A 1D lookup table holds 1 to 4096 entries");
lookups.push(RasterKernelLookup::Lut1d(&self.0));
}
}
/// A lookup field of a `size` cubed grid of entries, red fastest, then green, then blue, read in WGSL by `fn <field>_load(index: vec3<i32>) -> vec4<f32>`,
/// which clamps the index to the grid, and `fn <field>_size() -> i32`.
#[derive(Debug, Clone, PartialEq)]
pub struct Lut3d {
pub size: u32,
pub data: Vec<Color>,
}
impl GpuParamField for Lut3d {
const SLOTS: usize = 0;
const LOOKUP: bool = true;
fn wgsl_type() -> String {
String::new()
}
fn write(&self, _: &mut Vec<u32>) {}
fn wgsl_read(_: usize) -> String {
String::new()
}
fn wgsl_lookup(field: &str, binding: usize) -> String {
include_str!("wgsl/lut_3d.wgsl").replace("LUT", field).replace("BINDING", &binding.to_string())
}
fn lookup<'a>(&'a self, lookups: &mut Vec<RasterKernelLookup<'a>>) {
assert_eq!(self.data.len(), self.size.pow(3) as usize, "A 3D lookup table holds `size` cubed entries");
lookups.push(RasterKernelLookup::Lut3d { size: self.size, data: &self.data });
}
}
/// Declares a struct usable as [`GpuParams`] and as a nested [`GpuParamField`], generating its packing and WGSL unpacking.
///
/// The WGSL struct takes the Rust struct's name, so it must not collide with other WGSL names in the kernel.
/// Lookup fields such as [`Lut1d`] and [`Lut3d`] stay out of the WGSL struct, read instead through accessors named after the field.
#[macro_export]
macro_rules! gpu_params {
($(#[$attribute:meta])* $vis:vis struct $name:ident { $($(#[$field_attribute:meta])* $field_vis:vis $field:ident: $ty:ty),* $(,)? }) => {
$(#[$attribute])*
$vis struct $name {
$($(#[$field_attribute])* $field_vis $field: $ty),*
}
impl $crate::GpuParamField for $name {
const SLOTS: usize = 0 $(+ <$ty as $crate::GpuParamField>::SLOTS)*;
fn wgsl_type() -> String {
stringify!($name).into()
}
#[allow(unused_variables)]
fn write(&self, slots: &mut Vec<u32>) {
$(<$ty as $crate::GpuParamField>::write(&self.$field, slots);)*
}
#[allow(unused_mut, unused_variables, unused_assignments)]
fn wgsl_read(slot: usize) -> String {
let mut slot = slot;
let reads: Vec<(bool, String)> = vec![$({
let read = <$ty as $crate::GpuParamField>::wgsl_read(slot);
slot += <$ty as $crate::GpuParamField>::SLOTS;
(<$ty as $crate::GpuParamField>::LOOKUP, read)
}),*];
let reads: Vec<String> = reads.into_iter().filter(|(lookup, _)| !lookup).map(|(_, read)| read).collect();
format!("{}({})", stringify!($name), reads.join(", "))
}
#[allow(unused_variables)]
fn wgsl_declarations(declarations: &mut Vec<String>) {
$(<$ty as $crate::GpuParamField>::wgsl_declarations(declarations);)*
let fields: Vec<(bool, String)> = vec![$((
<$ty as $crate::GpuParamField>::LOOKUP,
format!("{}: {}", stringify!($field), <$ty as $crate::GpuParamField>::wgsl_type())
)),*];
let fields: Vec<String> = fields.into_iter().filter(|(lookup, _)| !lookup).map(|(_, field)| field).collect();
if fields.is_empty() {
return;
}
let declaration = format!("struct {} {{\n\t{},\n}}\n", stringify!($name), fields.join(",\n\t"));
if !declarations.contains(&declaration) {
declarations.push(declaration);
}
}
}
impl $crate::GpuParams for $name {
fn write(&self, slots: &mut Vec<u32>) {
<Self as $crate::GpuParamField>::write(self, slots);
}
fn wgsl() -> String {
let mut declarations = Vec::new();
<Self as $crate::GpuParamField>::wgsl_declarations(&mut declarations);
if declarations.is_empty() {
return String::new();
}
format!(
"{}\nalias Params = {};\n\nfn params() -> Params {{\n\treturn {};\n}}\n",
declarations.join("\n"),
stringify!($name),
<Self as $crate::GpuParamField>::wgsl_read(0)
)
}
fn wgsl_locals() -> String {
let fields: &[(bool, &str)] = &[$((<$ty as $crate::GpuParamField>::LOOKUP, stringify!($field))),*];
let fields: Vec<&str> = fields.iter().filter(|(lookup, _)| !lookup).map(|(_, field)| *field).collect();
if fields.is_empty() {
return String::new();
}
let locals = fields.iter().map(|field| format!("\tlet {field} = parameters.{field};\n")).collect::<String>();
format!("\tlet parameters = params();\n{locals}")
}
#[allow(unused_mut, unused_variables, unused_assignments)]
fn wgsl_lookups(binding: usize) -> String {
let mut binding = binding;
let mut source = String::new();
$(if <$ty as $crate::GpuParamField>::LOOKUP {
source += &<$ty as $crate::GpuParamField>::wgsl_lookup(stringify!($field), binding);
binding += 1;
})*
source
}
#[allow(unused_mut)]
fn lookups(&self) -> Vec<$crate::RasterKernelLookup<'_>> {
let mut lookups = Vec::new();
$(<$ty as $crate::GpuParamField>::lookup(&self.$field, &mut lookups);)*
lookups
}
}
};
}
/// Implements [`GpuParamField`] for enums converting into the `u32` or `i32` primitive `$repr`, such as through `IntoPrimitive`.
#[macro_export]
macro_rules! gpu_param_enum {
($repr:ident: $($ty:ty),* $(,)?) => {
$(
impl $crate::GpuParamField for $ty {
const SLOTS: usize = 1;
fn wgsl_type() -> String {
<$repr as $crate::GpuParamField>::wgsl_type()
}
fn write(&self, slots: &mut Vec<u32>) {
<$repr as $crate::GpuParamField>::write(&$repr::from(*self), slots);
}
fn wgsl_read(slot: usize) -> String {
<$repr as $crate::GpuParamField>::wgsl_read(slot)
}
}
)*
};
}
/// The [`GpuParams`] a kernel passes to its shader, which is the kernel itself unless it implements this to flatten richer data.
pub trait ToGpuParams {
type Params: GpuParams;
fn to_params(&self) -> Self::Params;
}
impl<T: GpuParams + Clone> ToGpuParams for T {
type Params = T;
fn to_params(&self) -> T {
self.clone()
}
}
/// A per-pixel color mapping, run by `map_cpu` on the CPU and by its WGSL on the GPU, which must agree.
///
/// Its WGSL function is `fn map_color(color: vec4<f32>) -> vec4<f32>`.
pub trait MapColor: ToGpuParams + 'static {
fn map_cpu(&self, color: Color) -> Color;
fn wgsl() -> Wgsl;
}
/// A GPU-only kernel computing each output pixel from `INPUTS` input rasters, which a type implements instead of [`MapColor`], not alongside it.
///
/// Its WGSL function is `fn kernel(coord: vec2<i32>) -> vec4<f32>`, which may call `output_size()` and, for each input `i`,
/// `input_i_size()`, `input_i_load(coord)` reading the input's own texel clamped to its edge,
/// and `input_i_at(coord)` sampling the input bilinearly where the output pixel's center lies, transparent beyond the input.
pub trait RasterKernel: ToGpuParams + 'static {
const INPUTS: usize;
/// Whether the inputs are bound filterable, adding `input_i_sample(texel)` sampling the input bilinearly at texel coordinates, whose texel centers lie at +0.5, clamped to its edge.
/// Every input must then be in a filterable format such as `Rgba16Float`, which the executor's raster format isn't.
const FILTERED: bool = false;
fn wgsl() -> Wgsl;
}
fn shader_module<Params: GpuParams>(signature: &str, wgsl: Wgsl, inputs: usize) -> String {
let function = match wgsl {
Wgsl::Body(body) => format!("{signature} {{\n{}{body}\n}}", Params::wgsl_locals()),
Wgsl::Function(source) => source,
};
format!("{}\n{}\n{}\n{function}", include_str!("wgsl/prelude.wgsl"), Params::wgsl(), Params::wgsl_lookups(2 + inputs))
}
/// The WGSL module running a [`MapColor`] on each texel of its one input.
pub fn map_color_module<K: MapColor>() -> String {
let module = shader_module::<K::Params>("fn map_color(color: vec4<f32>) -> vec4<f32>", K::wgsl(), 1);
format!("{module}\nfn kernel(coord: vec2<i32>) -> vec4<f32> {{\n\treturn map_color(input_0_load(coord));\n}}\n")
}
/// The WGSL module of a [`RasterKernel`].
pub fn raster_kernel_module<K: RasterKernel>() -> String {
shader_module::<K::Params>("fn kernel(coord: vec2<i32>) -> vec4<f32>", K::wgsl(), K::INPUTS)
}
/// A lookup table of a kernel, bound as an `Rgba32Float` texture after its inputs.
pub enum RasterKernelLookup<'a> {
/// A `width x 1` 2D texture of at most 4096 entries.
Lut1d(&'a [Color]),
/// A `size x size x size` 3D texture, its entries ordered with x fastest, then y, then z.
Lut3d { size: u32, data: &'a [Color] },
}
/// Receives a [`RasterKernel`] whose type depends on what it was picked for, such as the pattern a generator renders.
pub trait RasterKernelVisitor {
type Output;
fn visit<K: RasterKernel>(self, kernel: &K) -> Self::Output;
}
@@ -0,0 +1,12 @@
//! The kernels raster operations are carried out with: each a plain-data struct with the WGSL the GPU runs it by, and for those mapping each color alone, the CPU mapping that colors and gradients are adjusted by.
//! Running them on rasters is the job of `wgpu-executor`.
pub mod adjustments;
pub mod blending;
pub mod blur;
pub mod color_lookup_table;
pub mod effects;
pub mod generators;
mod kernel;
pub use kernel::*;
@@ -0,0 +1,28 @@
fn map_color(color: vec4<f32>) -> vec4<f32> {
let parameters = params();
let channels = to_gamma_srgb_channels(color);
let gray_base = min(min(channels.r, channels.g), channels.b);
let part = channels.rgb - gray_base;
var additional: f32;
if part.r == 0. {
let cyan_part = min(part.g, part.b);
additional = cyan_part * parameters.cyans + (part.g - cyan_part) * parameters.greens + (part.b - cyan_part) * parameters.blues;
} else if part.g == 0. {
let magenta_part = min(part.r, part.b);
additional = magenta_part * parameters.magentas + (part.r - magenta_part) * parameters.reds + (part.b - magenta_part) * parameters.blues;
} else {
let yellow_part = min(part.r, part.g);
additional = yellow_part * parameters.yellows + (part.r - yellow_part) * parameters.reds + (part.g - yellow_part) * parameters.greens;
}
let luminance = clamp(gray_base + additional, 0., 1.);
if !parameters.use_tint {
return from_gamma_srgb_channels(vec4<f32>(vec3<f32>(luminance), channels.a));
}
let tint = to_gamma_srgb_channels(parameters.tint).rgb;
let tinted = set_luminosity(tint, luma_rec_601_fixed_point(tint), luminance);
return from_gamma_srgb_channels(vec4<f32>(tinted, channels.a));
}
@@ -0,0 +1,291 @@
const BLEND_MODE_NORMAL: i32 = 0;
const BLEND_MODE_DARKEN: i32 = 1;
const BLEND_MODE_MULTIPLY: i32 = 2;
const BLEND_MODE_COLOR_BURN: i32 = 3;
const BLEND_MODE_LINEAR_BURN: i32 = 4;
const BLEND_MODE_DARKER_COLOR: i32 = 5;
const BLEND_MODE_LIGHTEN: i32 = 6;
const BLEND_MODE_SCREEN: i32 = 7;
const BLEND_MODE_COLOR_DODGE: i32 = 8;
const BLEND_MODE_LINEAR_DODGE: i32 = 9;
const BLEND_MODE_LIGHTER_COLOR: i32 = 10;
const BLEND_MODE_OVERLAY: i32 = 11;
const BLEND_MODE_SOFT_LIGHT: i32 = 12;
const BLEND_MODE_HARD_LIGHT: i32 = 13;
const BLEND_MODE_VIVID_LIGHT: i32 = 14;
const BLEND_MODE_LINEAR_LIGHT: i32 = 15;
const BLEND_MODE_PIN_LIGHT: i32 = 16;
const BLEND_MODE_HARD_MIX: i32 = 17;
const BLEND_MODE_DIFFERENCE: i32 = 18;
const BLEND_MODE_EXCLUSION: i32 = 19;
const BLEND_MODE_SUBTRACT: i32 = 20;
const BLEND_MODE_DIVIDE: i32 = 21;
const BLEND_MODE_HUE: i32 = 22;
const BLEND_MODE_SATURATION: i32 = 23;
const BLEND_MODE_COLOR: i32 = 24;
const BLEND_MODE_LUMINOSITY: i32 = 25;
const BLEND_MODE_ERASE: i32 = 26;
const BLEND_MODE_RESTORE: i32 = 27;
const BLEND_MODE_MULTIPLY_ALPHA: i32 = 28;
fn blend_normal(c_b: f32, c_s: f32) -> f32 {
return c_s;
}
fn blend_multiply(c_b: f32, c_s: f32) -> f32 {
return c_s * c_b;
}
fn blend_darken(c_b: f32, c_s: f32) -> f32 {
return min(c_s, c_b);
}
fn blend_color_burn(c_b: f32, c_s: f32) -> f32 {
if c_b == 1. {
return 1.;
} else if c_s == 0. {
return 0.;
}
return 1. - min((1. - c_b) / c_s, 1.);
}
fn blend_linear_burn(c_b: f32, c_s: f32) -> f32 {
return c_b + c_s - 1.;
}
fn blend_darker_color(color: vec4<f32>, other: vec4<f32>) -> vec4<f32> {
let darker = select(other, color, average_rgb_channels(color) <= average_rgb_channels(other));
return vec4<f32>(darker.rgb, other.a);
}
fn blend_screen(c_b: f32, c_s: f32) -> f32 {
return 1. - (1. - c_s) * (1. - c_b);
}
fn blend_lighten(c_b: f32, c_s: f32) -> f32 {
return max(c_s, c_b);
}
fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
if c_s == 1. {
return 1.;
}
return min(c_b / (1. - c_s), 1.);
}
fn blend_linear_dodge(c_b: f32, c_s: f32) -> f32 {
return c_b + c_s;
}
fn blend_lighter_color(color: vec4<f32>, other: vec4<f32>) -> vec4<f32> {
let lighter = select(other, color, average_rgb_channels(color) >= average_rgb_channels(other));
return vec4<f32>(lighter.rgb, other.a);
}
fn blend_softlight(c_b: f32, c_s: f32) -> f32 {
if c_s <= 0.5 {
return c_b - (1. - 2. * c_s) * c_b * (1. - c_b);
}
var d = 0.;
if c_b <= 0.25 {
d = ((16. * c_b - 12.) * c_b + 4.) * c_b;
} else {
d = sqrt(c_b);
}
return c_b + (2. * c_s - 1.) * (d - c_b);
}
fn blend_hardlight(c_b: f32, c_s: f32) -> f32 {
if c_s <= 0.5 {
return blend_multiply(2. * c_s, c_b);
}
return blend_screen(2. * c_s - 1., c_b);
}
fn blend_overlay(c_b: f32, c_s: f32) -> f32 {
return blend_hardlight(c_s, c_b);
}
fn blend_vivid_light(c_b: f32, c_s: f32) -> f32 {
if c_s <= 0.5 {
return blend_color_burn(2. * c_s, c_b);
}
return blend_color_dodge(2. * c_s - 1., c_b);
}
fn blend_linear_light(c_b: f32, c_s: f32) -> f32 {
if c_s <= 0.5 {
return blend_linear_burn(2. * c_s, c_b);
}
return blend_linear_dodge(2. * c_s - 1., c_b);
}
fn blend_pin_light(c_b: f32, c_s: f32) -> f32 {
if c_s <= 0.5 {
return blend_darken(2. * c_s, c_b);
}
return blend_lighten(2. * c_s - 1., c_b);
}
fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 {
return select(1., 0., blend_linear_light(c_b, c_s) < 0.5);
}
fn blend_difference(c_b: f32, c_s: f32) -> f32 {
return abs(c_b - c_s);
}
fn blend_exclusion(c_b: f32, c_s: f32) -> f32 {
return c_b + c_s - 2. * c_b * c_s;
}
fn blend_subtract(c_b: f32, c_s: f32) -> f32 {
return c_b - c_s;
}
fn blend_divide(c_b: f32, c_s: f32) -> f32 {
if c_b == 0. {
return 1.;
}
return c_b / c_s;
}
fn blend_channel(blend_mode: i32, c_b: f32, c_s: f32) -> f32 {
switch blend_mode {
case BLEND_MODE_DARKEN: {
return blend_darken(c_b, c_s);
}
case BLEND_MODE_MULTIPLY: {
return blend_multiply(c_b, c_s);
}
case BLEND_MODE_COLOR_BURN: {
return blend_color_burn(c_b, c_s);
}
case BLEND_MODE_LINEAR_BURN: {
return blend_linear_burn(c_b, c_s);
}
case BLEND_MODE_LIGHTEN: {
return blend_lighten(c_b, c_s);
}
case BLEND_MODE_SCREEN: {
return blend_screen(c_b, c_s);
}
case BLEND_MODE_COLOR_DODGE: {
return blend_color_dodge(c_b, c_s);
}
case BLEND_MODE_LINEAR_DODGE: {
return blend_linear_dodge(c_b, c_s);
}
case BLEND_MODE_OVERLAY: {
return blend_overlay(c_b, c_s);
}
case BLEND_MODE_SOFT_LIGHT: {
return blend_softlight(c_b, c_s);
}
case BLEND_MODE_HARD_LIGHT: {
return blend_hardlight(c_b, c_s);
}
case BLEND_MODE_VIVID_LIGHT: {
return blend_vivid_light(c_b, c_s);
}
case BLEND_MODE_LINEAR_LIGHT: {
return blend_linear_light(c_b, c_s);
}
case BLEND_MODE_PIN_LIGHT: {
return blend_pin_light(c_b, c_s);
}
case BLEND_MODE_HARD_MIX: {
return blend_hard_mix(c_b, c_s);
}
case BLEND_MODE_DIFFERENCE: {
return blend_difference(c_b, c_s);
}
case BLEND_MODE_EXCLUSION: {
return blend_exclusion(c_b, c_s);
}
case BLEND_MODE_SUBTRACT: {
return blend_subtract(c_b, c_s);
}
case BLEND_MODE_DIVIDE: {
return blend_divide(c_b, c_s);
}
default: {
return blend_normal(c_b, c_s);
}
}
}
fn blend_rgb(color: vec4<f32>, other: vec4<f32>, blend_mode: i32) -> vec4<f32> {
let red = blend_channel(blend_mode, color.r, other.r);
let green = blend_channel(blend_mode, color.g, other.g);
let blue = blend_channel(blend_mode, color.b, other.b);
return vec4<f32>(clamp(vec3<f32>(red, green, blue), vec3<f32>(0.), vec3<f32>(1.)), other.a);
}
fn gamma_rgb_in_range(color: vec4<f32>) -> vec3<f32> {
return clamp(to_gamma_srgb_channels(color).rgb, vec3<f32>(0.), vec3<f32>(1.));
}
fn blend_hue(color: vec4<f32>, c_s: vec4<f32>) -> vec4<f32> {
let backdrop = gamma_rgb_in_range(color);
let saturated = set_saturation(gamma_rgb_in_range(c_s), channel_range(backdrop));
let blended = set_luminosity(saturated, luma_rec_601_rounded(saturated), luma_rec_601_rounded(backdrop));
return from_gamma_srgb_channels(vec4<f32>(blended, c_s.a));
}
fn blend_saturation(color: vec4<f32>, c_s: vec4<f32>) -> vec4<f32> {
let backdrop = gamma_rgb_in_range(color);
let saturated = set_saturation(backdrop, channel_range(gamma_rgb_in_range(c_s)));
let blended = set_luminosity(saturated, luma_rec_601_rounded(saturated), luma_rec_601_rounded(backdrop));
return from_gamma_srgb_channels(vec4<f32>(blended, c_s.a));
}
fn blend_color(color: vec4<f32>, c_s: vec4<f32>) -> vec4<f32> {
let backdrop = gamma_rgb_in_range(color);
let source = gamma_rgb_in_range(c_s);
let blended = set_luminosity(source, luma_rec_601_rounded(source), luma_rec_601_rounded(backdrop));
return from_gamma_srgb_channels(vec4<f32>(blended, c_s.a));
}
fn blend_luminosity(color: vec4<f32>, c_s: vec4<f32>) -> vec4<f32> {
let backdrop = gamma_rgb_in_range(color);
let source = gamma_rgb_in_range(c_s);
let blended = set_luminosity(backdrop, luma_rec_601_rounded(backdrop), luma_rec_601_rounded(source));
return from_gamma_srgb_channels(vec4<f32>(blended, c_s.a));
}
fn apply_blend_mode(foreground: vec4<f32>, background: vec4<f32>, blend_mode: i32) -> vec4<f32> {
switch blend_mode {
case BLEND_MODE_DARKER_COLOR: {
return blend_darker_color(background, foreground);
}
case BLEND_MODE_LIGHTER_COLOR: {
return blend_lighter_color(background, foreground);
}
case BLEND_MODE_HUE: {
return blend_hue(background, foreground);
}
case BLEND_MODE_SATURATION: {
return blend_saturation(background, foreground);
}
case BLEND_MODE_COLOR: {
return blend_color(background, foreground);
}
case BLEND_MODE_LUMINOSITY: {
return blend_luminosity(background, foreground);
}
case BLEND_MODE_ERASE, BLEND_MODE_RESTORE, BLEND_MODE_MULTIPLY_ALPHA: {
return foreground;
}
default: {
return blend_rgb(background, foreground, blend_mode);
}
}
}
@@ -0,0 +1,41 @@
const BLUR_LINEAR: u32 = 1u;
const BLUR_GAMMA: u32 = 2u;
fn blur_weight(offset: i32, radius: f32, box_blur: bool) -> f32 {
let distance = f32(offset);
if box_blur {
return clamp(radius + 1. - abs(distance), 0., 1.);
}
return exp(-(distance * distance) / (2. * radius * radius));
}
fn blur_coverage(texel: vec2<i32>, full_size: array<i32, 2>, scale: i32) -> vec2<f32> {
let covered = clamp(vec2<i32>(full_size[0], full_size[1]) - texel * scale, vec2<i32>(0), vec2<i32>(scale));
return vec2<f32>(covered) / f32(scale);
}
fn blur_premultiply(color: vec4<f32>, space: u32) -> vec4<f32> {
if space == BLUR_LINEAR {
return vec4<f32>(color.rgb * color.a, color.a);
}
if space == BLUR_GAMMA {
return vec4<f32>(linear_to_srgb(color.rgb) * color.a, color.a);
}
return color;
}
fn blur_unpremultiply(color: vec4<f32>, space: u32) -> vec4<f32> {
if space == BLUR_LINEAR {
if color.a == 0. {
return color;
}
return vec4<f32>(color.rgb * (1. / color.a), color.a);
}
if space == BLUR_GAMMA {
if color.a <= 0. {
return vec4<f32>(0.);
}
return vec4<f32>(srgb_to_linear(color.rgb * (1. / color.a)), color.a);
}
return color;
}
@@ -0,0 +1,13 @@
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let parameters = params();
var sum = vec4<f32>(0.);
var weight_sum = 0.;
for (var corner = 0; corner < 4; corner++) {
let texel = coord * 2 + vec2<i32>(corner % 2, corner / 2);
let coverage = blur_coverage(texel, parameters.full_size, parameters.scale);
let weight = coverage.x * coverage.y;
sum += blur_premultiply(input_0_load(texel), parameters.space) * weight;
weight_sum += weight;
}
return sum / weight_sum;
}
@@ -0,0 +1,15 @@
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let parameters = params();
let first = -min(parameters.reach, coord.x);
let last = min(parameters.reach, input_0_size().x - 1 - coord.x);
var sum = vec4<f32>(0.);
var weight_sum = 0.;
for (var offset = first; offset <= last; offset++) {
let texel = vec2<i32>(coord.x + offset, coord.y);
let weight = blur_weight(offset, parameters.radius, parameters.box_blur) * blur_coverage(texel, parameters.full_size, parameters.scale).x;
sum += blur_premultiply(input_0_load(texel), parameters.space) * weight;
weight_sum += weight;
}
return sum / weight_sum;
}
@@ -0,0 +1,4 @@
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let parameters = params();
return blur_unpremultiply(input_0_sample((vec2<f32>(coord) + 0.5) / parameters.scale), parameters.space);
}
@@ -0,0 +1,37 @@
struct BlurSum {
color: vec4<f32>,
weight: f32,
}
fn blur_tap_weight(coord: vec2<i32>, offset: i32) -> f32 {
let parameters = params();
let coverage = blur_coverage(coord + vec2<i32>(0, offset), parameters.full_size, parameters.scale).y;
return blur_weight(abs(offset), parameters.radius, parameters.box_blur) * coverage;
}
fn blur_side(coord: vec2<i32>, direction: i32, taps: i32) -> BlurSum {
var sum = BlurSum(vec4<f32>(0.), 0.);
for (var near = 1; near <= taps; near += 2) {
let near_weight = blur_tap_weight(coord, direction * near);
if near + 1 > taps {
sum.color += input_0_load(coord + vec2<i32>(0, direction * near)) * near_weight;
sum.weight += near_weight;
break;
}
let far_weight = blur_tap_weight(coord, direction * (near + 1));
let weight = near_weight + far_weight;
let offset = f32(near) + far_weight / weight;
sum.color += input_0_sample(vec2<f32>(coord) + 0.5 + vec2<f32>(0., f32(direction) * offset)) * weight;
sum.weight += weight;
}
return sum;
}
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let parameters = params();
let above = blur_side(coord, -1, min(parameters.reach, coord.y));
let below = blur_side(coord, 1, min(parameters.reach, input_0_size().y - 1 - coord.y));
let center_weight = blur_tap_weight(coord, 0);
let sum = input_0_load(coord) * center_weight + above.color + below.color;
return blur_unpremultiply(sum / (center_weight + above.weight + below.weight), parameters.space);
}
@@ -0,0 +1,97 @@
fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, inverse_gamma: f32, output_minimum: f32, output_maximum: f32) -> f32 {
let highlights_minus_shadows = clamp(input_highlights - input_shadows, 1.1920929e-7, 1.);
let clamped = min(max(value - input_shadows, 0.) / highlights_minus_shadows, 1.);
let curved = pow(clamped, inverse_gamma);
return curved * (output_maximum - output_minimum) + output_minimum;
}
fn brightness_contrast_classic(value: f32, brightness: f32, contrast: f32, pivot: f32) -> f32 {
if contrast >= 1. {
return select(0., 1., value + brightness >= pivot - 1. / 65536.);
}
var result: f32;
if contrast > 0. {
let input_shadows = pivot * contrast - brightness;
result = apply_levels(value, input_shadows, input_shadows + 1. - contrast, 1., 0., 1.);
} else {
let output_minimum = brightness - pivot * contrast;
result = apply_levels(value, 0., 1., 1., output_minimum, output_minimum + 1. + contrast);
}
return clamp(result, 0., 1.);
}
fn brightness_curve_hermite(curve: BrightnessCurve, t: f32) -> vec2<f32> {
let length = 1. - curve.knee;
let start_tangent = length * curve.slope;
let end_tangent = length * curve.end_slope;
let t2 = t * t;
let t3 = t2 * t;
let value = (2. * t3 - 3. * t2 + 1.) * 0.5 + (t3 - 2. * t2 + t) * start_tangent + (-2. * t3 + 3. * t2) + (t3 - t2) * end_tangent;
let derivative = ((6. * t2 - 6. * t) * 0.5 + (3. * t2 - 4. * t + 1.) * start_tangent + (-6. * t2 + 6. * t) + (3. * t2 - 2. * t) * end_tangent) / length;
return vec2<f32>(value, derivative);
}
fn brightness_curve_forward(curve: BrightnessCurve, x: f32) -> f32 {
if x < curve.knee {
return curve.slope * x;
}
let t = min((x - curve.knee) / (1. - curve.knee), 1.);
return min(brightness_curve_hermite(curve, t).x, 1.);
}
fn brightness_curve_inverse(curve: BrightnessCurve, y: f32) -> f32 {
if y <= 0.5 {
return y / curve.slope;
}
var low = 0.;
var high = 1.;
var t = (y - 0.5) * 2.;
for (var i = 0; i < 8; i++) {
let hermite = brightness_curve_hermite(curve, t);
let error = hermite.x - y;
if error > 0. {
high = t;
} else {
low = t;
}
let step = t - error / (hermite.y * (1. - curve.knee));
t = select((low + high) * 0.5, step, step >= low && step <= high);
}
return curve.knee + t * (1. - curve.knee);
}
fn adjust(c: f32, parameters: Params) -> f32 {
if parameters.use_classic {
return brightness_contrast_classic(c, parameters.brightness / 255., parameters.contrast, parameters.classic_pivot);
}
var brightened: f32;
if parameters.brightness >= 0. {
brightened = brightness_curve_forward(parameters.second_curve, brightness_curve_forward(parameters.first_curve, c));
} else {
brightened = brightness_curve_inverse(parameters.first_curve, brightness_curve_inverse(parameters.second_curve, c));
}
let contrasted = brightened + 0.76 * parameters.contrast * (2. * brightened - 1.) * min(brightened, 1. - brightened);
return clamp(contrasted, 0., 1.);
}
fn map_color(color: vec4<f32>) -> vec4<f32> {
let parameters = params();
let channels = to_gamma_srgb_channels(color);
let adjusted = vec3<f32>(
adjust(channels.r, parameters),
adjust(channels.g, parameters),
adjust(channels.b, parameters),
);
return from_gamma_srgb_channels(vec4<f32>(adjusted, channels.a));
}
@@ -0,0 +1,22 @@
fn map_color(color: vec4<f32>) -> vec4<f32> {
let parameters = params();
let channels = to_gamma_srgb_channels(color);
let r = channels.r;
let g = channels.g;
let b = channels.b;
var mixed = vec3<f32>(0.);
if parameters.monochrome {
let gray = clamp(r * parameters.monochrome_r + g * parameters.monochrome_g + b * parameters.monochrome_b + parameters.monochrome_c, 0., 1.);
mixed = vec3<f32>(gray);
} else {
let red = clamp(r * parameters.red_r + g * parameters.red_g + b * parameters.red_b + parameters.red_c, 0., 1.);
let green = clamp(r * parameters.green_r + g * parameters.green_g + b * parameters.green_b + parameters.green_c, 0., 1.);
let blue = clamp(r * parameters.blue_r + g * parameters.blue_g + b * parameters.blue_b + parameters.blue_c, 0., 1.);
mixed = vec3<f32>(red, green, blue);
}
return from_gamma_srgb_channels(vec4<f32>(mixed, channels.a));
}
@@ -0,0 +1,5 @@
fn map_color(color: vec4<f32>) -> vec4<f32> {
let parameters = params();
let channels = to_gamma_srgb_channels(color);
return from_gamma_srgb_channels(vec4<f32>(levels_curve_apply(parameters.red, channels.r), levels_curve_apply(parameters.green, channels.g), levels_curve_apply(parameters.blue, channels.b), channels.a));
}
@@ -0,0 +1,50 @@
fn map_color(color: vec4<f32>) -> vec4<f32> {
let parameters = params();
let domain_min = vec3<f32>(parameters.domain_min[0], parameters.domain_min[1], parameters.domain_min[2]);
let domain_max = vec3<f32>(parameters.domain_max[0], parameters.domain_max[1], parameters.domain_max[2]);
let channels = to_gamma_srgb_channels(color);
let span = max(domain_max - domain_min, vec3<f32>(1.1920929e-7));
let normalized = clamp((channels.rgb - domain_min) / span, vec3<f32>(0.), vec3<f32>(1.));
let last = table_size() - 1;
let scaled = normalized * f32(last);
let lower = min(vec3<i32>(floor(scaled)), vec3<i32>(last));
let upper = min(lower + 1, vec3<i32>(last));
let f = scaled - vec3<f32>(lower);
var first: vec3<i32>;
var second: vec3<i32>;
var t: vec3<f32>;
if f.r >= f.g && f.g >= f.b {
first = vec3<i32>(upper.r, lower.g, lower.b);
second = vec3<i32>(upper.r, upper.g, lower.b);
t = vec3<f32>(f.r, f.g, f.b);
} else if f.r >= f.b && f.b >= f.g {
first = vec3<i32>(upper.r, lower.g, lower.b);
second = vec3<i32>(upper.r, lower.g, upper.b);
t = vec3<f32>(f.r, f.b, f.g);
} else if f.b >= f.r && f.r >= f.g {
first = vec3<i32>(lower.r, lower.g, upper.b);
second = vec3<i32>(upper.r, lower.g, upper.b);
t = vec3<f32>(f.b, f.r, f.g);
} else if f.g >= f.r && f.r >= f.b {
first = vec3<i32>(lower.r, upper.g, lower.b);
second = vec3<i32>(upper.r, upper.g, lower.b);
t = vec3<f32>(f.g, f.r, f.b);
} else if f.g >= f.b && f.b >= f.r {
first = vec3<i32>(lower.r, upper.g, lower.b);
second = vec3<i32>(lower.r, upper.g, upper.b);
t = vec3<f32>(f.g, f.b, f.r);
} else {
first = vec3<i32>(lower.r, lower.g, upper.b);
second = vec3<i32>(lower.r, upper.g, upper.b);
t = vec3<f32>(f.b, f.g, f.r);
}
let c000 = table_load(lower).rgb;
let c111 = table_load(upper).rgb;
let first_entry = table_load(first).rgb;
let second_entry = table_load(second).rgb;
let result = c000 + (t.x * (first_entry - c000) + t.y * (second_entry - first_entry) + t.z * (c111 - second_entry));
return from_gamma_srgb_channels(vec4<f32>(result, channels.a));
}
@@ -0,0 +1,6 @@
fn map_color(color: vec4<f32>) -> vec4<f32> {
let parameters = params();
let overlay = apply_blend_mode(parameters.color, color, parameters.blend_mode);
return vec4<f32>(color.rgb + (overlay.rgb - color.rgb) * parameters.opacity, color.a);
}
@@ -0,0 +1,43 @@
const LUMINANCE_REC_709: u32 = 0u;
const LUMA_REC_709: u32 = 1u;
const LUMA_REC_601: u32 = 2u;
const LIGHTNESS_OK_LAB: u32 = 3u;
const CHANNELS_AVERAGE: u32 = 4u;
const CHANNELS_MINIMUM: u32 = 5u;
const CHANNELS_MAXIMUM: u32 = 6u;
const LIGHTNESS_HSL: u32 = 7u;
fn map_color(color: vec4<f32>) -> vec4<f32> {
var luminance: f32;
switch params().method {
case LUMA_REC_709: {
let channels = to_gamma_srgb_channels(color);
luminance = srgb_to_linear(vec3<f32>(0.2126 * channels.r + 0.7152 * channels.g + 0.0722 * channels.b)).x;
}
case LUMA_REC_601: {
let channels = to_gamma_srgb_channels(color);
luminance = srgb_to_linear(vec3<f32>(0.299 * channels.r + 0.587 * channels.g + 0.114 * channels.b)).x;
}
case LIGHTNESS_OK_LAB: {
let lightness = lightness_oklab(color);
luminance = lightness * lightness * lightness;
}
case CHANNELS_AVERAGE: {
luminance = average_rgb_channels(color);
}
case CHANNELS_MINIMUM: {
luminance = minimum_rgb_channels(color);
}
case CHANNELS_MAXIMUM: {
luminance = maximum_rgb_channels(color);
}
case LIGHTNESS_HSL: {
let extremes = linear_to_srgb(vec3<f32>(maximum_rgb_channels(color), minimum_rgb_channels(color), 0.));
luminance = srgb_to_linear(vec3<f32>((extremes.x + extremes.y) / 2.)).x;
}
case LUMINANCE_REC_709, default: {
luminance = luminance_rec_709(color);
}
}
return vec4<f32>(vec3<f32>(luminance), color.a);
}
@@ -0,0 +1,6 @@
// Stacks a tinted silhouette (input 1's coverage) over the shadows and glows beneath the content (input 0)
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let beneath = input_0_load(coord);
let tinted = params().color * input_1_load(coord).a;
return tinted + beneath * (1. - tinted.a);
}
@@ -0,0 +1,34 @@
// A bevel's height from 0 to 1, shaped by the style over a slope `size` texels wide, from the nearest texels inside (input 0) and outside (input 1)
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let parameters = params();
let to_inside = input_0_load(coord);
let to_outside = input_1_load(coord);
let size = parameters.size;
// Texels inside the silhouette are those at no distance from it, and the edge lies about half a texel short of the nearest texel across it
let far = 4. * size + 4.;
var signed_distance: f32;
if to_inside.z > 0.5 && dot(to_inside.xy, to_inside.xy) == 0. {
signed_distance = select(far, length(to_outside.xy) - 0.5, to_outside.z > 0.5);
} else {
signed_distance = select(-far, 0.5 - length(to_inside.xy), to_inside.z > 0.5);
}
var progress: f32;
switch parameters.style {
case 0u: {
progress = signed_distance / size;
}
case 1u: {
progress = (signed_distance + size) / size;
}
case 2u: {
progress = (signed_distance + size / 2.) / size;
}
default: {
progress = abs(signed_distance) / (size / 2.);
}
}
let height = clamp(progress, 0., 1.);
return vec4<f32>(height * height * (3. - 2. * height));
}
@@ -0,0 +1,16 @@
// How far the light brightens the bevel's surface past a flat surface's brightness, or if `shadow`, how far it falls short.
// `slope` scales the height's gradient into the surface's steepness, and is negative for a bevel pressed into the surface.
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let parameters = params();
let gradient = vec2<f32>(
input_0_load(coord + vec2<i32>(1, 0)).a - input_0_load(coord - vec2<i32>(1, 0)).a,
input_0_load(coord + vec2<i32>(0, 1)).a - input_0_load(coord - vec2<i32>(0, 1)).a,
) / 2.;
let light = vec3<f32>(parameters.light_x, parameters.light_y, parameters.light_z);
let shade = dot(normalize(vec3<f32>(-parameters.slope * gradient, 1.)), light);
if parameters.shadow {
return vec4<f32>(clamp((light.z - shade) / max(light.z, 1e-4), 0., 1.));
}
return vec4<f32>(clamp((shade - light.z) / max(1. - light.z, 1e-4), 0., 1.));
}
@@ -0,0 +1,5 @@
// The coverage of the content's silhouette, or of the area outside it if `inverse`, where the input's placement casts it
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let coverage = input_0_at(coord).a;
return vec4<f32>(select(coverage, 1. - coverage, params().inverse));
}
@@ -0,0 +1,7 @@
// Places the shadows and glows (input 1) beneath the image (input 0), knocked out by the content at full strength (input 2) so a faded fill doesn't reveal them
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let image = input_0_load(coord);
let beneath = input_1_load(coord);
let full_content = input_2_load(coord);
return image + beneath * (1. - full_content.a);
}
@@ -0,0 +1,7 @@
// Places a tinted silhouette (input 1's coverage) over the image (input 0), within the content at full strength (input 2) so it stays visible over a faded fill
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let image = input_0_load(coord);
let tinted = params().color * input_1_load(coord).a;
let full_content = input_2_load(coord);
return tinted * full_content.a + image * (1. - tinted.a);
}
@@ -0,0 +1,8 @@
// Premultiplied gamma-encoded channels back into a straight-alpha linear-light color
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let color = input_0_load(coord);
if color.a <= 0. {
return vec4<f32>(0.);
}
return vec4<f32>(srgb_to_linear(max(color.rgb / color.a, vec3<f32>(0.))), color.a);
}
@@ -0,0 +1,4 @@
// Grows the shapes by one step along an axis, from the coverage placed at the pixel and one step to either side, so steps that double each time grow them by any distance in a few passes
fn kernel(coord: vec2<i32>) -> vec4<f32> {
return vec4<f32>(max(input_0_at(coord).a, max(input_1_at(coord).a, input_2_at(coord).a)));
}
@@ -0,0 +1,8 @@
// Covers the texels within `width` texels of the edge, which lies about half a texel short of the nearest seed, fading out over one texel
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let nearest = input_0_load(coord);
if nearest.z < 0.5 {
return vec4<f32>(0.);
}
return vec4<f32>(clamp(params().width + 1. - length(nearest.xy), 0., 1.));
}
@@ -0,0 +1,5 @@
// The straight-alpha linear-light content, sampled where the output pixel lies, as the premultiplied gamma-encoded channels the effects are carried out in, faded by `amount`
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let color = input_0_at(coord);
return vec4<f32>(linear_to_srgb(max(color.rgb, vec3<f32>(0.))) * color.a, color.a) * params().amount;
}
@@ -0,0 +1,3 @@
fn kernel(coord: vec2<i32>) -> vec4<f32> {
return vec4<f32>(1. - input_0_load(coord).a);
}
@@ -0,0 +1,7 @@
// Jump flooding keeps each texel's offset to the nearest seed found so far (xy) and whether one is found (z).
// The seeds are the texels inside the content's silhouette, or outside it if `inward`, and each is its own nearest.
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let inside = input_0_load(coord).a >= 0.5;
let seed = inside != params().inward;
return vec4<f32>(0., 0., select(0., 1., seed), 0.);
}
@@ -0,0 +1,25 @@
// Takes the nearest of the seeds that the texel and its eight neighbors `step` texels away have found so far
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let step = params().step;
var best = input_0_load(coord);
for (var neighbor_y = -1; neighbor_y <= 1; neighbor_y++) {
for (var neighbor_x = -1; neighbor_x <= 1; neighbor_x++) {
let direction = vec2<i32>(neighbor_x, neighbor_y);
let neighbor = coord + direction * step;
if any(neighbor < vec2<i32>(0)) || any(neighbor >= input_0_size()) {
continue;
}
let found = input_0_load(neighbor);
if found.z < 0.5 {
continue;
}
let candidate = found.xy + vec2<f32>(direction * step);
if best.z < 0.5 || dot(candidate, candidate) < dot(best.xy, best.xy) {
best = vec4<f32>(candidate, 1., 0.);
}
}
}
return best;
}
@@ -0,0 +1,7 @@
// The first image, emptied wherever the second is empty
fn kernel(coord: vec2<i32>) -> vec4<f32> {
if input_1_load(coord).a <= 0. {
return vec4<f32>(0.);
}
return input_0_load(coord);
}
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff. Show more