Compare commits

..
Author SHA1 Message Date
Timon 45757b45f4 Report attribute type conflicts from push/extend and when reading list attributes 2026-10-30 14:17:17 +00:00
Timon 207647e78f Report attribute type mismatches 2026-10-30 14:17:17 +00:00
Timon d90cc62bc1 Make nodes report errors instead of panicking or failing silently (#4837)
* Fix crashes and report errors in math nodes

* Fix crashes and report errors in text nodes and Boolean Operation

* Fix crashes and report errors in raster, brush and I/O nodes

* Fix crashes and report errors in vector and transform nodes

* Report errors from graphic and context nodes
2026-10-30 14:16:24 +00:00
Dennis Kobert 82c08464d1 Frame CLI exports to the artwork bounds (#4860)
* Frame CLI exports to the artwork bounds

* Include strokes in the bounds CLI exports frame to

* Count every item of a layer in the bounds CLI exports frame to

* Count every item of a layer in the bounds the editor exports
2026-10-30 12:35:09 +00:00
Timon a2e62ed47e Report GPU and resource failures as node errors (#4846)
* Allow lazy scope inputs

* Report a missing GPU instead of panicking

* Return pipeline errors instead of panicking

* Stop logging error paths outside the document

* Report missing resources as errors

* Report Vello failures in Rasterize

* Better GPU test error handling
2026-10-30 12:22:06 +00:00
Dennis Kobert 9939966b0e Visit each network definition once in recursive walks (#4857)
* Visit each definition once in recursive walks and validation

* Rename DefinitionId to NetworkId to mirror the storage model

* Review fixes

* Make test more precise
2026-10-30 12:42:40 +01:00
203 changed files with 7479 additions and 8694 deletions

No files matched your search

+1 -1
View File
@@ -56,7 +56,7 @@ jobs:
CARGO_TERM_COLOR: always
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from Binaryen
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from rust-gpu's codegen backend and Binaryen
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.127"
+1 -1
View File
@@ -135,7 +135,7 @@ jobs:
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder of its own
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from rust-gpu's codegen backend
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
steps:
- name: 📥 Clone repository
+45
View File
@@ -0,0 +1,45 @@
name: "Provide Shaders"
on:
push:
branches:
- master
workflow_dispatch: {}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
with:
extra-conf: |
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
- name: 🏗 Build graphene raster nodes shaders
run: nix build .#graphite-raster-nodes-shaders && cp result raster_nodes_shaders_entrypoint.wgsl
- name: 📤 Upload graphene raster nodes shaders to artifacts repository
run: |
bash .github/workflows/scripts/artifact-upload.bash \
${{ vars.ARTIFACTS_REPO_OWNER }} \
${{ vars.ARTIFACTS_REPO_NAME }} \
${{ vars.ARTIFACTS_REPO_BRANCH }} \
rev/${{ github.sha }}/raster_nodes_shaders_entrypoint.wgsl \
raster_nodes_shaders_entrypoint.wgsl \
"${{ github.sha }} raster_nodes_shaders_entrypoint.wgsl" \
${{ secrets.ARTIFACTS_REPO_TOKEN }}
- name: 📤 Push shaders to dev Nix cache
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
NIX_CACHE_NAME: graphite-dev
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build .#graphite-raster-nodes-shaders --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
+2
View File
@@ -31,6 +31,7 @@ let
deps = {
crane = lib.call ./deps/crane.nix;
rustGPU = lib.call ./deps/rust-gpu.nix;
cargoAbout = lib.call ./deps/cargo-about.nix;
};
@@ -56,6 +57,7 @@ in
default = graphite;
graphite = (lib.call ./pkgs/graphite.nix) { };
graphite-dev = (lib.call ./pkgs/graphite.nix) { dev = true; };
graphite-raster-nodes-shaders = lib.call ./pkgs/graphite-raster-nodes-shaders.nix;
graphite-branding = lib.call ./pkgs/graphite-branding.nix;
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
+55
View File
@@ -0,0 +1,55 @@
{ pkgs, ... }:
let
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
extensions = [
"rust-src"
"rust-analyzer"
"clippy"
"cargo"
"rustc-dev"
"llvm-tools"
];
};
cargo = pkgs.writeShellScriptBin "cargo" ''
#!${pkgs.lib.getExe pkgs.bash}
filtered_args=()
for arg in "$@"; do
case "$arg" in
+nightly|+nightly-*) ;;
*) filtered_args+=("$arg") ;;
esac
done
exec ${toolchain}/bin/cargo ${"\${filtered_args[@]}"}
'';
rustc_codegen_spirv =
(pkgs.makeRustPlatform {
cargo = toolchain;
rustc = toolchain;
}).buildRustPackage
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0.10.0";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-QluNI2TdJI0j2CBOeAbB9DfOv+8LqzWk7siZyT1WWLU=";
};
cargoHash = "sha256-vvviUccnip+j60Ml1vqLNJ49KyEF40VLUoV1TMALHMs=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
"--features=use-compiled-tools"
"--no-default-features"
];
doCheck = false;
});
in
{
toolchain = toolchain;
env = {
RUST_GPU_PATH_OVERRIDE = "${cargo}/bin:${toolchain}/bin";
RUSTC_CODEGEN_SPIRV_PATH = "${rustc_codegen_spirv}/lib/librustc_codegen_spirv.so";
};
}
+2 -6
View File
@@ -47,17 +47,13 @@ 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";
};
}
deps.rustGPU
(lib.optionalAttrs desktop (
{
libs = [
pkgs.wayland
pkgs.vulkan-loader
pkgs.libGL
pkgs.libxkbcommon
self.packages.${system}.graphite-cef
@@ -0,0 +1,28 @@
{
info,
deps,
self,
system,
...
}:
(deps.crane.lib.overrideToolchain (_: deps.rustGPU.toolchain)).buildPackage {
pname = "graphite-raster-nodes-shaders";
inherit (info) version src;
inherit (self.packages.${system}.graphite) cargoVendorDir cargoArtifacts;
strictDeps = true;
env = deps.rustGPU.env;
buildPhase = ''
cargo build -r -p raster-nodes-shaders
'';
installPhase = ''
cp target/spirv-builder/spirv-unknown-naga-wgsl/release/deps/raster_nodes_shaders_entrypoint.wgsl $out
'';
doCheck = false;
}
+2
View File
@@ -35,6 +35,7 @@ let
inherit (deps.crane.lib.findCargoFiles (deps.crane.lib.cleanCargoSource info.src)) cargoConfigs;
cargoLockList = [
"${info.src}/Cargo.lock"
"${deps.rustGPU.toolchain.availableComponents.rust-src}/lib/rustlib/src/rust/library/Cargo.lock"
];
}
);
@@ -96,6 +97,7 @@ deps.crane.lib.buildPackage (
makeCacheWritable = true;
env = {
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
Generated
+390 -44
View File
@@ -313,6 +313,7 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
dependencies = [
"bytemuck",
"serde_core",
]
@@ -335,7 +336,7 @@ name = "blending-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"glam 0.33.10",
"graphic-types",
"node-macro",
"serde",
@@ -377,7 +378,7 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"graphic-types",
"half",
@@ -395,7 +396,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"serde",
]
@@ -487,6 +488,29 @@ dependencies = [
"serde",
]
[[package]]
name = "cargo-gpu-install"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "668b4bd1b59810c4f907eeb36bb0f0a450c824219b2e599b9b8ef2b3ae056e94"
dependencies = [
"anyhow",
"cargo_metadata 0.21.0",
"directories",
"log",
"serde",
"spirv-builder",
]
[[package]]
name = "cargo-platform"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84982c6c0ae343635a3a4ee6dedef965513735c8b183caa7289fa6e27399ebd4"
dependencies = [
"serde",
]
[[package]]
name = "cargo-platform"
version = "0.3.3"
@@ -526,6 +550,37 @@ dependencies = [
"notify-debouncer-full",
]
[[package]]
name = "cargo-util-schemas"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dc1a6f7b5651af85774ae5a34b4e8be397d9cf4bc063b7e6dbd99a841837830"
dependencies = [
"semver",
"serde",
"serde-untagged",
"serde-value",
"thiserror 2.0.18",
"toml 0.8.23",
"unicode-xid",
"url",
]
[[package]]
name = "cargo_metadata"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cfca2aaa699835ba88faf58a06342a314a950d2b9686165e038286c30316868"
dependencies = [
"camino",
"cargo-platform 0.2.0",
"cargo-util-schemas",
"semver",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "cargo_metadata"
version = "0.23.1"
@@ -533,7 +588,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9"
dependencies = [
"camino",
"cargo-platform",
"cargo-platform 0.3.3",
"semver",
"serde",
"serde_json",
@@ -564,7 +619,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb823e721b3ea203f4635e71532db2b010696c074518eb4f6154fd7f47fc6fcb"
dependencies = [
"anyhow",
"cargo_metadata",
"cargo_metadata 0.23.1",
"cef-dll-sys",
"clap",
"libloading 0.9.0",
@@ -726,6 +781,8 @@ version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
"serde",
"termcolor",
"unicode-width",
]
@@ -802,7 +859,7 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
name = "control-protocol"
version = "0.0.0"
dependencies = [
"glam",
"glam 0.33.10",
"serde",
"serde_json",
]
@@ -891,19 +948,17 @@ dependencies = [
"ctor",
"dyn-any",
"futures",
"glam",
"glam 0.33.10",
"graphene-hash",
"half",
"image",
"kurbo",
"log",
"lyon_geom",
"no-std-types",
"node-macro",
"num-derive",
"num-traits",
"num_enum",
"parley",
"petgraph",
"petgraph 0.7.1",
"polycool",
"rand",
"rand_chacha",
@@ -911,6 +966,7 @@ dependencies = [
"serde",
"serde_json",
"skrifa",
"thiserror 2.0.18",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -1171,6 +1227,15 @@ dependencies = [
"crypto-common",
]
[[package]]
name = "directories"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs"
version = "6.0.0"
@@ -1363,7 +1428,7 @@ name = "dyn-any"
version = "0.3.1"
dependencies = [
"dyn-any-derive",
"glam",
"glam 0.33.10",
"reqwest",
]
@@ -1461,6 +1526,16 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "erased-serde"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e004d887f51fcb9fef17317a2f3525c887d8aa3f4f50fed920816a688284a5b7"
dependencies = [
"serde",
"typeid",
]
[[package]]
name = "errno"
version = "0.3.13"
@@ -1506,6 +1581,15 @@ 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"
@@ -1893,6 +1977,36 @@ dependencies = [
"xml-rs",
]
[[package]]
name = "glam"
version = "0.30.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
dependencies = [
"bytemuck",
"libm",
]
[[package]]
name = "glam"
version = "0.31.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "556f6b2ea90b8d15a74e0e7bb41671c9bdf38cd9f78c284d750b9ce58a2b5be7"
dependencies = [
"bytemuck",
"libm",
]
[[package]]
name = "glam"
version = "0.32.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0"
dependencies = [
"bytemuck",
"libm",
]
[[package]]
name = "glam"
version = "0.33.10"
@@ -1900,6 +2014,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928452f9c953e142b2f0973e4bd5f34445fcaa8069556ea97a3c9d34d15a4cf8"
dependencies = [
"bytemuck",
"libm",
"serde_core",
]
@@ -1952,7 +2067,7 @@ dependencies = [
"core-types",
"criterion",
"dyn-any",
"glam",
"glam 0.33.10",
"graph-craft",
"graphene-animation",
"graphene-application-io",
@@ -1987,7 +2102,7 @@ name = "graphene-animation"
version = "0.0.0"
dependencies = [
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"kurbo",
"serde",
@@ -2000,7 +2115,7 @@ dependencies = [
"blake3",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"graphene-resource",
"log",
@@ -2017,7 +2132,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-application-io",
"log",
"serde",
@@ -2055,7 +2170,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-animation",
"graphene-hash",
"graphic-types",
@@ -2063,6 +2178,7 @@ dependencies = [
"node-macro",
"raster-types",
"serde",
"thiserror 2.0.18",
"tsify",
"wasm-bindgen",
]
@@ -2071,7 +2187,7 @@ dependencies = [
name = "graphene-hash"
version = "0.0.0"
dependencies = [
"glam",
"glam 0.33.10",
"graphene-hash-derive",
"kurbo",
]
@@ -2106,7 +2222,7 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graph-craft",
"graphene-application-io",
"graphene-canvas-utils",
@@ -2144,12 +2260,13 @@ dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphic-types",
"node-macro",
"rand",
"raster-types",
"serde",
"thiserror 2.0.18",
"vector-types",
]
@@ -2160,7 +2277,7 @@ dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"node-macro",
"raster-types",
@@ -2181,7 +2298,7 @@ dependencies = [
"dirs",
"fd-lock",
"futures",
"glam",
"glam 0.33.10",
"graphite-desktop-ui",
"graphite-desktop-wrapper",
"interprocess",
@@ -2306,7 +2423,7 @@ dependencies = [
"dyn-any",
"env_logger",
"futures",
"glam",
"glam 0.33.10",
"graph-craft",
"graphene-hash",
"graphene-std",
@@ -2910,7 +3027,7 @@ dependencies = [
"criterion",
"dyn-any",
"futures",
"glam",
"glam 0.33.10",
"graph-craft",
"graphene-animation",
"graphene-core",
@@ -3188,7 +3305,7 @@ dependencies = [
"ena",
"itertools 0.14.0",
"lalrpop-util",
"petgraph",
"petgraph 0.7.1",
"regex",
"regex-syntax 0.8.6",
"sha3",
@@ -3497,13 +3614,13 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-core",
"graphic-types",
"log",
"math-parser",
"node-macro",
"rand",
"thiserror 2.0.18",
"vector-types",
]
@@ -3518,6 +3635,16 @@ 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"
@@ -3623,6 +3750,7 @@ dependencies = [
"naga-types",
"num-traits",
"once_cell",
"petgraph 0.8.2",
"rustc-hash 1.1.0",
"spirv",
"thiserror 2.0.18",
@@ -3641,6 +3769,21 @@ 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"
@@ -3689,6 +3832,27 @@ dependencies = [
"libc",
]
[[package]]
name = "no-std-types"
version = "0.0.0"
dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam 0.33.10",
"graphene-hash",
"half",
"log",
"node-macro",
"num-derive",
"num-traits",
"num_enum",
"serde",
"spirv-std",
"tsify",
"wasm-bindgen",
]
[[package]]
name = "node-docs"
version = "0.0.0"
@@ -3708,6 +3872,7 @@ dependencies = [
"convert_case 0.12.0",
"core-types",
"indoc",
"no-std-types",
"proc-macro-crate",
"proc-macro-error2",
"proc-macro2",
@@ -3791,6 +3956,15 @@ 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"
@@ -4013,6 +4187,15 @@ dependencies = [
"libredox",
]
[[package]]
name = "ordered-float"
version = "2.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
dependencies = [
"num-traits",
]
[[package]]
name = "ordered-float"
version = "4.6.0"
@@ -4102,13 +4285,14 @@ name = "path-bool-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"glam 0.33.10",
"graphic-types",
"linesweeper",
"log",
"node-macro",
"smallvec",
"text-nodes",
"thiserror 2.0.18",
"vector-types",
]
@@ -4147,6 +4331,17 @@ dependencies = [
"indexmap",
]
[[package]]
name = "petgraph"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54acf3a685220b533e437e264e4d932cfbdc4cc7ec0cd232ed73c08d03b8a7ca"
dependencies = [
"fixedbitset",
"hashbrown 0.15.5",
"indexmap",
]
[[package]]
name = "phf"
version = "0.13.1"
@@ -4407,7 +4602,7 @@ dependencies = [
"core-types",
"dyn-any",
"futures",
"glam",
"glam 0.33.10",
"graph-craft",
"graphene-std",
"interpreted-executor",
@@ -4627,16 +4822,26 @@ dependencies = [
"color",
"core-types",
"dyn-any",
"fastnoise-lite",
"futures",
"glam",
"glam 0.33.10",
"graphene-core",
"graphene-hash",
"graphene-resource",
"image",
"kurbo",
"ndarray",
"no-std-types",
"node-macro",
"num-traits",
"num_enum",
"rand",
"rand_chacha",
"raster-nodes-shaders",
"raster-types",
"serde",
"spirv-std",
"thiserror 2.0.18",
"tokio",
"tsify",
"vector-types",
@@ -4644,6 +4849,22 @@ dependencies = [
"wgpu-executor",
]
[[package]]
name = "raster-nodes-shaders"
version = "0.0.0"
dependencies = [
"cargo-gpu-install",
"env_logger",
"log",
]
[[package]]
name = "raster-nodes-shaders-entrypoint"
version = "0.0.0"
dependencies = [
"raster-nodes",
]
[[package]]
name = "raster-types"
version = "0.0.0"
@@ -4652,17 +4873,24 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"image",
"node-macro",
"serde",
"serde_json",
"thiserror 2.0.18",
"tsify",
"wasm-bindgen",
"wgpu",
]
[[package]]
name = "raw-string"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0501e134c6905fee1f10fed25b0a7e1261bf676cffac9543a7d0730dec01af2"
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -4681,6 +4909,12 @@ 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"
@@ -4817,7 +5051,7 @@ dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-hash",
"graphene-resource",
"graphic-types",
@@ -4839,7 +5073,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"glam 0.33.10",
"graphene-core",
"graphic-types",
"kurbo",
@@ -4969,6 +5203,16 @@ dependencies = [
"memchr",
]
[[package]]
name = "rspirv"
version = "0.13.0+sdk-1.4.341.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "091dca2e1d6fd3098417b5ec88e77e80d1ba5945750943419dc976858082c296"
dependencies = [
"rustc-hash 1.1.0",
"spirv",
]
[[package]]
name = "rustc-demangle"
version = "0.1.26"
@@ -4987,6 +5231,20 @@ version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]]
name = "rustc_codegen_spirv-types"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d703f5624720c5b6012f4b88d6e6766f43ed50d80144eaffd6791c3270754cdc"
dependencies = [
"rspirv",
"semver",
"serde",
"serde_json",
"spirv",
"thiserror 2.0.18",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -5244,6 +5502,27 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "serde-untagged"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34836a629bcbc6f1afdf0907a744870039b1e14c0561cb26094fa683b158eff3"
dependencies = [
"erased-serde",
"serde",
"typeid",
]
[[package]]
name = "serde-value"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
dependencies = [
"ordered-float 2.10.1",
"serde",
]
[[package]]
name = "serde-wasm-bindgen"
version = "0.6.5"
@@ -5511,7 +5790,7 @@ name = "snapping"
version = "0.0.0"
dependencies = [
"criterion",
"glam",
"glam 0.33.10",
"kurbo",
]
@@ -5552,8 +5831,62 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
dependencies = [
"bitflags 2.13.2",
"serde",
]
[[package]]
name = "spirv-builder"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57fa119866f0311546e5309b18770b72141c25d185452c11a812be2c7b9d84e9"
dependencies = [
"cargo_metadata 0.21.0",
"log",
"memchr",
"raw-string",
"rustc_codegen_spirv-types",
"semver",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "spirv-std"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d98471765e294d4dd6289350e3633b5c5ba57bb382c3287d83e69ee737179e0"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"glam 0.30.10",
"glam 0.31.1",
"glam 0.32.1",
"glam 0.33.10",
"libm",
"num-traits",
"spirv-std-macros",
"spirv-std-types",
]
[[package]]
name = "spirv-std-macros"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13a6a0d063d4dd003e43818135b7aa4a30c41c48b5d0efe2cac02220448d4f19"
dependencies = [
"proc-macro2",
"quote",
"spirv-std-types",
"syn 3.0.6",
]
[[package]]
name = "spirv-std-types"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "655632248eaaa205cea4656bc73c8285cbd8109fc784010b24ea6bd0bab79ac1"
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
@@ -5772,6 +6105,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
"winapi-util",
]
[[package]]
name = "text-nodes"
version = "0.0.0"
@@ -5780,17 +6122,17 @@ dependencies = [
"core-types",
"dyn-any",
"fancy-regex",
"glam",
"glam 0.33.10",
"graphene-hash",
"graphene-resource",
"ipsum",
"log",
"node-macro",
"parley",
"rand",
"serde",
"serde_json",
"skrifa",
"thiserror 2.0.18",
"titlecase",
"tsify",
"unicode-segmentation",
@@ -6185,11 +6527,12 @@ name = "transform-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"glam 0.33.10",
"graphic-types",
"node-macro",
"rand",
"serde",
"thiserror 2.0.18",
"vector-types",
]
@@ -6439,7 +6782,7 @@ dependencies = [
"delaunator",
"dyn-any",
"futures",
"glam",
"glam 0.33.10",
"graphene-core",
"graphene-hash",
"graphic-types",
@@ -6451,6 +6794,7 @@ dependencies = [
"repeat-nodes",
"rustc-hash 2.1.1",
"serde",
"thiserror 2.0.18",
"tokio",
"tsify",
"vector-types",
@@ -6467,19 +6811,20 @@ dependencies = [
"core-types",
"dyn-any",
"fixedbitset",
"glam",
"glam 0.33.10",
"graphene-hash",
"kurbo",
"log",
"lyon_geom",
"node-macro",
"num-traits",
"petgraph",
"petgraph 0.7.1",
"polycool",
"robust",
"rustc-hash 2.1.1",
"serde",
"serde_json",
"thiserror 2.0.18",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -6764,7 +7109,7 @@ dependencies = [
"clap",
"control-protocol",
"getrandom 0.3.3",
"glam",
"glam 0.33.10",
"image",
"interprocess",
"serde",
@@ -6872,6 +7217,7 @@ dependencies = [
"hashbrown 0.17.1",
"js-sys",
"log",
"naga",
"parking_lot",
"portable-atomic",
"profiling",
@@ -6966,13 +7312,13 @@ dependencies = [
"core-types",
"dyn-any",
"futures",
"glam",
"glam 0.33.10",
"graphene-application-io",
"half",
"log",
"node-macro",
"raster-types",
"rendering",
"thiserror 2.0.18",
"vello_gpu",
"web-sys",
"wgpu",
@@ -7013,7 +7359,7 @@ dependencies = [
"objc2-metal",
"objc2-quartz-core",
"once_cell",
"ordered-float",
"ordered-float 4.6.0",
"parking_lot",
"portable-atomic",
"portable-atomic-util",
+13 -3
View File
@@ -22,6 +22,8 @@ members = [
"node-graph/libraries/graphene-hash",
"node-graph/libraries/*",
"node-graph/nodes/*",
"node-graph/nodes/raster/shaders",
"node-graph/nodes/raster/shaders/entrypoint",
"node-graph/graph-craft",
"node-graph/graphene-cli",
"node-graph/nodes/gstd",
@@ -81,6 +83,7 @@ graphene-application-io = { path = "node-graph/libraries/application-io" }
graphene-resource = { path = "node-graph/libraries/resources" }
graphene-animation = { path = "node-graph/libraries/animation" }
core-types = { path = "node-graph/libraries/core-types" }
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" }
@@ -152,6 +155,7 @@ wgpu = { version = "30.0", default-features = false, features = [
"webgl",
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
"fragile-send-sync-non-atomic-wasm",
"spirv",
"strict_asserts",
] }
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
@@ -193,7 +197,7 @@ color = "0.3"
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
"std",
"nostd-libm",
"scalar-math",
"bytemuck",
"debug-glam-assert",
@@ -219,7 +223,7 @@ pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
num_enum = { version = "0.7", default-features = false }
num-derive = "0.4"
num-traits = "0.2"
num-traits = { version = "0.2", default-features = false, features = ["libm"] }
tsify = { version = "0.5", default-features = false, features = ["js"] }
syn = { version = "2.0", default-features = false, features = [
"full",
@@ -253,6 +257,10 @@ open = "5.3"
spin = "0.10"
clap = "4.5"
# Ensure these are kept in sync with .nix/deps/rust-gpu.nix
spirv-std = { version = "0.10.0", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0", default-features = false }
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
@@ -260,12 +268,14 @@ linesweeper = "0.4"
smallvec = "1.13.2"
zip = { version = "8", default-features = false }
[workspace.lints]
[workspace.lints.rust]
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
[profile.dev]
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 }
+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}],[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
{"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
+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}},{"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
{"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
+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}],[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
{"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
+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}],[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
{"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
+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}],[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
{"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
+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":[],"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
{"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
+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}],[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
{"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
+1 -1
View File
@@ -187,7 +187,7 @@ allow-git = []
[sources.allow-org]
# 1 or more github.com organizations to allow git sources for
github = ["linebender"]
github = ["linebender", "Rust-GPU"]
# 1 or more gitlab.com organizations to allow git sources for
#gitlab = [""]
# 1 or more bitbucket.org organizations to allow git sources for
+1 -1
View File
@@ -15,7 +15,7 @@ publish.workspace = true
workspace = true
[features]
gpu = ["graphite-editor/gpu"]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
[dependencies]
# Local dependencies
@@ -625,6 +625,8 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
index: (*import_index).try_into().map_err(|_| ConversionError::IndexOverflow(*import_index))?,
},
GraphCraftNodeInput::Reflection(_) => NodeInput::Reflection,
// GPU-specific; not modeled in the Registry format.
GraphCraftNodeInput::Inline(_) => return Err(ConversionError::UnsupportedImplementation),
})
}
@@ -197,7 +197,7 @@ mod tests {
for file_type in [FileType::Png, FileType::Jpg, FileType::Webp, FileType::Tiff, FileType::Bmp, FileType::Tga, FileType::Ico] {
let encoded = file_type.encode(2, 1, pixels.clone()).unwrap_or_else(|error| panic!("{file_type:?}: {error}"));
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{file_type:?} should read back"));
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|error| panic!("{file_type:?} should read back: {error}"));
assert_eq!((decoded.width, decoded.height), (2, 1), "{file_type:?}");
// Only JPG lacks transparency, so it lands on white
@@ -18,7 +18,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, Storage};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::text::TextAlign;
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -944,15 +944,9 @@ impl TableItemLayout for Raster<GPU> {
"Raster"
}
fn identifier(&self) -> String {
let size = self.size();
format!("Raster ({} x {})", size.x, size.y)
format!("Raster ({} x {})", self.data().width(), self.data().height())
}
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)]
}
@@ -611,10 +611,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::node(NodeId(0), 0),
NodeInput::scope(raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string()),
],
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
@@ -626,13 +623,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String("graphite:null".to_string()), false)],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
input_metadata: vec![
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
("URL", "The web address or local asset path of the image to load.").into(),
],
output_names: vec!["Image".to_string()],
output_descriptions: vec!["The loaded image, which is empty if it fails to load or decode.".to_string()],
output_descriptions: vec!["The loaded image.".to_string()],
..Default::default()
},
description: Cow::Borrowed("Loads an image from a given URL."),
@@ -1368,8 +1368,8 @@ fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
vec![
concrete!(Graphic),
concrete!(Vector),
concrete!(Raster<GPU>),
concrete!(Raster<CPU>),
concrete!(Raster<GPU>),
concrete!(Color),
concrete!(Gradient),
concrete!(String),
@@ -1179,7 +1179,7 @@ impl OverlayContextInternal {
// Lay out the text once, taking its dimensions and vector paths from the same thread-local context pass
let (text_size, text_list) = TextContext::with_thread_local(|text_context| {
let text_size = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false).unwrap_or_default();
(text_size, text_list)
});
let text_width = text_size.x;
@@ -347,21 +347,20 @@ 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. Falls back to the click-target-based
/// bounds for non-vector layers (groups, raster, text, color, gradient).
/// 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]> {
if let Some(item) = self.layer_vector_data.get(&layer) {
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
let stroke = self
.layer_appearance_attributes
.get(&layer)
.and_then(|appearance| appearance.first_coverage_of(graphene_std::Cover::Stroke))
.map(graphene_std::Coverage::stroke_params);
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
if let Some(bounds) = item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref()) {
return Some(bounds);
}
}
self.bounding_box_document(layer)
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
});
[stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)
}
/// Get the bounding box of the click target of the specified layer in viewport space
@@ -717,6 +716,26 @@ pub struct NodeRelations {
mod tests {
use super::*;
#[test]
fn stroked_bounds_include_the_items_after_the_first() {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
let line = |from: f64, to: f64| {
let mut path = BezPath::new();
path.move_to((from, 0.));
path.line_to((to, 0.));
path
};
// Only the first item is recorded as vector data, while click targets cover every item
let mut metadata = DocumentMetadata::default();
metadata.layer_vector_data.insert(layer, Arc::new(Vector::item_from_bezpath(&line(0., 10.))));
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();
assert_eq!((min.x, max.x), (0., 110.));
}
#[test]
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
@@ -50,7 +50,7 @@ use glam::{DAffine2, DVec2, IVec2};
use graph_craft::Type;
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DefinitionId, DocumentNode, DocumentNodeImplementation, NetworkLocation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graphene_std::Appearance;
use graphene_std::math::quad::Quad;
use graphene_std::registry::MULTI_OUTPUT_NODES;
@@ -140,6 +140,9 @@ impl NodeNetworkInterface {
pub fn migrate_path_modify_node(&mut self) {
self.migrate_graph(fix_network);
fn fix_network(network: &mut NodeNetwork) {
for definition in network.definitions.values_mut() {
fix_network(definition);
}
for node in network.nodes.values_mut() {
if let Some(network) = node.implementation.get_network_mut() {
fix_network(network);
@@ -192,7 +195,7 @@ mod network_interface_tests {
fn instance_paths_resolve_through_the_definitions_table() {
use super::*;
let definition = DefinitionId(1);
let definition = NetworkId(1);
let instance = |implementation| DocumentNode { implementation, ..Default::default() };
let instances = [NodeId(10), NodeId(11)];
@@ -207,12 +210,14 @@ mod network_interface_tests {
definition_metadata.persistent_metadata.node_metadata.insert(NodeId(0), DocumentNodeMetadata::default());
let mut network_metadata = NodeNetworkMetadata::default();
let mut instance_metadata = DocumentNodeMetadata::default();
instance_metadata.persistent_metadata.output_names = vec![String::new()];
for id in instances {
network_metadata.persistent_metadata.node_metadata.insert(id, DocumentNodeMetadata::default());
network_metadata.persistent_metadata.node_metadata.insert(id, instance_metadata.clone());
}
network_metadata.persistent_metadata.definitions.insert(definition, definition_metadata);
let interface = NodeNetworkInterface::from_trees(network, network_metadata);
let interface = NodeNetworkInterface::from_trees(network.clone(), network_metadata.clone());
let paths = instances.map(|id| [id]);
let views = paths.each_ref().map(|path| interface.view(path).unwrap());
@@ -224,5 +229,28 @@ mod network_interface_tests {
assert_eq!(document_view.reference(&NodeId(10)), Ok(Some(DefinitionIdentifier::Network("Artboard".into()))));
assert_eq!(document_view.number_of_outputs(&NodeId(10)), Ok(1));
assert_eq!(interface.validate_invariants(), Vec::<String>::new());
let unused = NetworkId(2);
let mut network_with_unused = network.clone();
network_with_unused
.definitions
.insert(unused, NodeNetwork::value_network(instance(DocumentNodeImplementation::default())));
let mut metadata_with_unused = network_metadata.clone();
metadata_with_unused.persistent_metadata.definitions.insert(unused, NodeNetworkMetadata::default());
let with_unused = NodeNetworkInterface::from_trees(network_with_unused, metadata_with_unused);
assert_eq!(with_unused.validate_invariants(), vec!["Node 0 in network [] has no metadata entry".to_string()]);
let mut mismatched_network = network;
mismatched_network.nodes.get_mut(&NodeId(11)).unwrap().inputs.push(NodeInput::value(TaggedValue::None, false));
network_metadata
.persistent_metadata
.node_metadata
.get_mut(&NodeId(11))
.unwrap()
.persistent_metadata
.input_metadata
.push(InputMetadata::default());
let mismatched = NodeNetworkInterface::from_trees(mismatched_network, network_metadata);
assert_eq!(mismatched.validate_invariants().len(), 1);
}
}
@@ -902,7 +902,7 @@ impl NodeNetworkInterface {
let layer_output = NodeInput::node(layer.to_node(), 0);
match post_node_input {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
// First child in the stack: wire layer output to the post_node input
self.set_input_for_import(&post_node, layer_output, network_path);
}
@@ -1031,7 +1031,7 @@ impl NodeNetworkInterface {
if !inserting_into_stack {
match post_node_input {
// Create a new stack
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
self.create_wire(&OutputConnector::primary_output(layer.to_node()), &post_node, network_path);
let final_layer_position = after_move_post_layer_position + IVec2::new(-LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP);
@@ -1057,7 +1057,7 @@ impl NodeNetworkInterface {
} else {
match post_node_input {
// Move to the bottom of the stack
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
let offset = after_move_post_layer_position - previous_layer_position + IVec2::new(0, STACK_VERTICAL_GAP + height_above_layer);
self.shift_absolute_node_position(&layer.to_node(), offset, network_path);
self.create_wire(&OutputConnector::primary_output(layer.to_node()), &post_node, network_path);
@@ -659,13 +659,13 @@ impl NodeNetworkInterface {
}
// A wire to or from the imports changed
(NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Import { .. }, NodeInput::Import { .. })
| (NodeInput::Import { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. }) => {
(NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. } | NodeInput::Import { .. }, NodeInput::Import { .. })
| (NodeInput::Import { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }) => {
self.unload_wire(input_connector, network_path);
}
// A node was disconnected
(NodeInput::Node { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Import { .. }) => {
(NodeInput::Node { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. } | NodeInput::Import { .. }) => {
self.unload_wire(input_connector, network_path);
if let Some((old_upstream_node_id, previous_position)) = disconnected_upstream
@@ -1,7 +1,7 @@
use std::collections::{HashMap, HashSet};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeInput};
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
use graph_craft::proto::{GraphErrorType, GraphErrors, Promotion};
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
use graphene_std::NodeIOTypes;
@@ -257,6 +257,7 @@ impl NodeNetworkInterface {
}
NodeInput::Scope(_) => TypeSource::Compiled(concrete!(())),
NodeInput::Reflection(document_node_metadata) => TypeSource::Compiled(document_node_metadata.ty()),
NodeInput::Inline(_) => TypeSource::Compiled(concrete!(InlineRust)),
}
}
@@ -75,7 +75,7 @@ impl Default for NodeTemplate {
#[derive(Debug, Clone, PartialEq)]
pub enum NodeTemplateImplementation {
Network(NodeNetworkTemplate),
Definition(DefinitionId),
Definition(NetworkId),
ProtoNode(ProtoNodeIdentifier),
Extract,
}
@@ -580,7 +580,7 @@ pub struct NodeNetworkPersistentMetadata {
#[serde(skip)]
pub selection_redo_history: VecDeque<SelectedNodes>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub definitions: HashMap<DefinitionId, NodeNetworkMetadata>,
pub definitions: HashMap<NetworkId, NodeNetworkMetadata>,
}
/// A lazily computed cache slot whose load and read paths work through &self, with interior mutability guarding the stored value.
@@ -1137,6 +1137,9 @@ pub(crate) fn visit_network_resources(network: &NodeNetwork, visit: &mut impl Fn
for node in network.nodes.values() {
visit_node_resources(node, visit);
}
for definition in network.definitions.values() {
visit_network_resources(definition, visit);
}
}
pub(crate) fn visit_node_resources(node: &DocumentNode, visit: &mut impl FnMut(ResourceId)) {
@@ -1192,6 +1195,37 @@ mod tests {
assert_eq!(visits.len(), 4);
}
#[test]
fn resource_visits_reach_each_definition_once() {
let definition = NetworkId(1);
let used = ResourceId::from(1);
let instance = || DocumentNode {
implementation: DocumentNodeImplementation::Definition(definition),
..Default::default()
};
let body = NodeNetwork {
nodes: [(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Resource(used), false)],
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
};
let network = NodeNetwork {
nodes: [(NodeId(1), instance()), (NodeId(2), instance())].into_iter().collect(),
definitions: [(definition, body)].into_iter().collect(),
..Default::default()
};
let mut visits = Vec::new();
visit_network_resources(&network, &mut |id| visits.push(id));
assert_eq!(visits, vec![used]);
}
#[test]
fn port_click_targets_reach_around_the_connector_where_wires_attach() {
let center = DVec2::new(100., 50.);
@@ -1,5 +1,5 @@
use super::{InputConnector, NodeNetworkInterface, NodeNetworkMetadata};
use graph_craft::document::{DefinitionId, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::document::{DocumentNodeImplementation, NetworkId, NodeId, NodeInput, NodeNetwork};
use std::collections::{HashMap, HashSet};
impl NodeNetworkInterface {
@@ -9,12 +9,44 @@ impl NodeNetworkInterface {
// O(nodes + wires) summed across all nesting levels, plus an acyclicity walk per network
pub fn validate_invariants(&self) -> Vec<String> {
let mut violations = Vec::new();
validate_network(self.document_network(), self.document_network(), &self.network_metadata, &mut Vec::new(), 0, &mut violations);
self.validate_definition_tables(&mut violations);
let mut root = DocumentRoot {
network: self.document_network(),
metadata: &self.network_metadata,
definition_import_counts: HashMap::new(),
};
validate_network(&mut root, self.document_network(), &self.network_metadata, &mut Vec::new(), Some(0), &mut violations);
for (id, definition) in &self.document_network().definitions {
if root.definition_import_counts.contains_key(id) {
continue;
}
let Some(definition_metadata) = self.network_metadata.persistent_metadata.definitions.get(id) else {
continue;
};
root.definition_import_counts.insert(*id, None);
validate_network(&mut root, definition, definition_metadata, &mut Vec::new(), None, &mut violations);
}
self.validate_outward_wires(&mut Vec::new(), &mut HashSet::new(), &mut violations);
self.validate_dots_stay_on_wires(&mut violations);
violations
}
/// The definitions table and its metadata table must contain exactly the same definitions.
fn validate_definition_tables(&self, violations: &mut Vec<String>) {
let definitions = &self.document_network().definitions;
let definition_metadata = &self.network_metadata.persistent_metadata.definitions;
for id in definitions.keys().filter(|id| !definition_metadata.contains_key(id)) {
violations.push(format!("Definition {id:?} has no metadata entry"));
}
for id in definition_metadata.keys().filter(|id| !definitions.contains_key(id)) {
violations.push(format!("Metadata entry for definition {id:?} has no corresponding definition"));
}
}
/// A redirect dot an edit took a wire from must be gone by the time the edit is done if that left it orphaned.
fn validate_dots_stay_on_wires(&self, violations: &mut Vec<String>) {
for (network_path, lost_wires) in &self.dots_that_lost_a_wire {
@@ -25,7 +57,7 @@ impl NodeNetworkInterface {
}
/// A loaded outward wire cache must match a fresh computation from the network.
fn validate_outward_wires(&self, path: &mut Vec<NodeId>, validated_definitions: &mut HashSet<DefinitionId>, violations: &mut Vec<String>) {
fn validate_outward_wires(&self, path: &mut Vec<NodeId>, validated_definitions: &mut HashSet<NetworkId>, violations: &mut Vec<String>) {
let Some(network) = self.nested_network(path) else { return };
if let Some(computed) = self.compute_outward_wires(path)
@@ -68,7 +100,15 @@ fn wire_counts(inputs: &[InputConnector]) -> HashMap<InputConnector, usize> {
counts
}
fn validate_network(document_network: &NodeNetwork, network: &NodeNetwork, network_metadata: &NodeNetworkMetadata, path: &mut Vec<NodeId>, import_count: usize, violations: &mut Vec<String>) {
struct DocumentRoot<'a> {
network: &'a NodeNetwork,
metadata: &'a NodeNetworkMetadata,
definition_import_counts: HashMap<NetworkId, Option<usize>>,
}
fn validate_network(root: &mut DocumentRoot, network: &NodeNetwork, network_metadata: &NodeNetworkMetadata, path: &mut Vec<NodeId>, import_count: Option<usize>, violations: &mut Vec<String>) {
let (document_network, document_metadata) = (root.network, root.metadata);
let node_metadata = &network_metadata.persistent_metadata.node_metadata;
// The network and its metadata tree must contain exactly the same set of nodes
@@ -99,8 +139,12 @@ fn validate_network(document_network: &NodeNetwork, network: &NodeNetwork, netwo
}
_ => {}
},
NodeInput::Import { import_index, .. } if *import_index >= import_count => {
violations.push(format!("{location} in network {path:?} references nonexistent import {import_index} of {import_count}"));
NodeInput::Import { import_index, .. } => {
if let Some(import_count) = import_count
&& *import_index >= import_count
{
violations.push(format!("{location} in network {path:?} references nonexistent import {import_index} of {import_count}"));
}
}
_ => {}
};
@@ -131,19 +175,22 @@ fn validate_network(document_network: &NodeNetwork, network: &NodeNetwork, netwo
));
}
let validate_output_names = |export_count: usize, violations: &mut Vec<String>| {
if persistent.output_names.len() != export_count {
violations.push(format!(
"Node {node_id} in network {path:?} has {export_count} exports but {} output names",
persistent.output_names.len()
));
}
};
// Nested network metadata must exist exactly for nodes implemented as networks
match (&node.implementation, &persistent.network_metadata) {
(DocumentNodeImplementation::Network(nested_network), Some(nested_metadata)) => {
if persistent.output_names.len() != nested_network.exports.len() {
violations.push(format!(
"Node {node_id} in network {path:?} has {} exports but {} output names",
nested_network.exports.len(),
persistent.output_names.len()
));
}
validate_output_names(nested_network.exports.len(), violations);
path.push(*node_id);
validate_network(document_network, nested_network, nested_metadata, path, node.inputs.len(), violations);
validate_network(root, nested_network, nested_metadata, path, Some(node.inputs.len()), violations);
path.pop();
}
(DocumentNodeImplementation::Network(_), None) => {
@@ -152,6 +199,31 @@ fn validate_network(document_network: &NodeNetwork, network: &NodeNetwork, netwo
(_, Some(_)) => {
violations.push(format!("Non-network node {node_id} in network {path:?} has nested network metadata"));
}
(DocumentNodeImplementation::Definition(id), None) => {
let Some(definition) = document_network.definitions.get(id) else {
violations.push(format!("Node {node_id} in network {path:?} references nonexistent definition {id:?}"));
continue;
};
validate_output_names(definition.exports.len(), violations);
match root.definition_import_counts.get(id) {
Some(&Some(validated_import_count)) if validated_import_count != node.inputs.len() => violations.push(format!(
"Node {node_id} in network {path:?} has {} inputs but another instance of definition {id:?} has {validated_import_count}",
node.inputs.len()
)),
Some(_) => {}
None => {
root.definition_import_counts.insert(*id, Some(node.inputs.len()));
let Some(definition_metadata) = document_metadata.persistent_metadata.definitions.get(id) else {
continue;
};
path.push(*node_id);
validate_network(root, definition, definition_metadata, path, Some(node.inputs.len()), violations);
path.pop();
}
}
}
(_, None) => {}
}
}
@@ -16,7 +16,6 @@ use graphene_std::ParameterRef;
use graphene_std::ProtoNodeIdentifier;
use graphene_std::extract_xy::XY;
use graphene_std::raster::RedGreenBlueAlpha;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
@@ -498,7 +497,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_raster_nodes::adjustments::BlackAndWhiteNode",
"graphene_core::raster::adjustments::BlackAndWhiteNode",
"graphene_core::raster::BlackAndWhiteNode",
"raster_nodes::adjustments::black_and_white_shader_node::BlackAndWhiteShaderNodeNode",
],
},
NodeReplacement {
@@ -524,7 +522,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::adjustments::BrightnessContrastNode",
"graphene_raster_nodes::adjustments::brightness_contrast_classic",
"graphene_raster_nodes::adjustments::BrightnessContrastClassicNode",
"raster_nodes::adjustments::brightness_contrast_shader_node::BrightnessContrastShaderNodeNode",
],
},
NodeReplacement {
@@ -533,13 +530,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_raster_nodes::adjustments::ChannelMixerNode",
"graphene_core::raster::adjustments::ChannelMixerNode",
"graphene_core::raster::ChannelMixerNode",
"raster_nodes::adjustments::channel_mixer_shader_node::ChannelMixerShaderNodeNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::color_balance::IDENTIFIER,
aliases: &["raster_nodes::adjustments::color_balance_shader_node::ColorBalanceShaderNodeNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
aliases: &[
@@ -549,7 +541,6 @@ 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::color_overlay_shader_node::ColorOverlayShaderNodeNode",
],
},
NodeReplacement {
@@ -570,7 +561,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_raster_nodes::adjustments::ExposureNode",
"graphene_core::raster::adjustments::ExposureNode",
"graphene_core::raster::ExposureNode",
"raster_nodes::adjustments::exposure_shader_node::ExposureShaderNodeNode",
],
},
NodeReplacement {
@@ -579,11 +569,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::GammaCorrectionNode",
"graphene_core::raster::adjustments::GammaCorrectionNode",
"raster_nodes::adjustments::gamma_correction_shader_node::GammaCorrectionShaderNodeNode",
],
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::gradient_map::IDENTIFIER,
@@ -602,7 +588,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_raster_nodes::adjustments::HueSaturationNode",
"graphene_core::raster::adjustments::HueSaturationNode",
"graphene_core::raster::HueSaturationNode",
"raster_nodes::adjustments::hue_saturation_shader_node::HueSaturationShaderNodeNode",
],
},
NodeReplacement {
@@ -628,7 +613,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::adjustments::InvertNode",
"graphene_core::raster::InvertNode",
"graphene_core::raster::InvertRGBNode",
"raster_nodes::adjustments::invert_shader_node::InvertShaderNodeNode",
],
},
NodeReplacement {
@@ -637,7 +621,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_raster_nodes::adjustments::LevelsNode",
"graphene_core::raster::adjustments::LevelsNode",
"graphene_core::raster::LevelsNode",
"raster_nodes::adjustments::levels_shader_node::LevelsShaderNodeNode",
],
},
NodeReplacement {
@@ -647,7 +630,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_raster_nodes::adjustments::LuminanceNode",
"graphene_core::raster::adjustments::LuminanceNode",
"graphene_core::raster::LuminanceNode",
"raster_nodes::adjustments::desaturate_shader_node::DesaturateShaderNodeNode",
],
},
NodeReplacement {
@@ -656,7 +638,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_raster_nodes::adjustments::MakeOpaqueNode",
"graphene_core::raster::adjustments::MakeOpaqueNode",
"graphene_core::raster::ExtractOpaqueNode",
"raster_nodes::adjustments::make_opaque_shader_node::MakeOpaqueShaderNodeNode",
],
},
NodeReplacement {
@@ -667,17 +648,12 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::MaskNode", "graphene_std::raster::MaskNode", "graphene_std::raster::MaskImageNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::photo_filter::IDENTIFIER,
aliases: &["raster_nodes::adjustments::photo_filter_shader_node::PhotoFilterShaderNodeNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::posterize::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::PosterizeNode",
"graphene_core::raster::adjustments::PosterizeNode",
"graphene_core::raster::PosterizeNode",
"raster_nodes::adjustments::posterize_shader_node::PosterizeShaderNodeNode",
],
},
NodeReplacement {
@@ -686,11 +662,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::selective_color::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::SelectiveColorNode",
"graphene_core::raster::adjustments::SelectiveColorNode",
"raster_nodes::adjustments::selective_color_shader_node::SelectiveColorShaderNodeNode",
],
aliases: &["graphene_raster_nodes::adjustments::SelectiveColorNode", "graphene_core::raster::adjustments::SelectiveColorNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER,
@@ -698,7 +670,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_raster_nodes::adjustments::ThresholdNode",
"graphene_core::raster::adjustments::ThresholdNode",
"graphene_core::raster::ThresholdNode",
"raster_nodes::adjustments::threshold_shader_node::ThresholdShaderNodeNode",
],
},
NodeReplacement {
@@ -707,7 +678,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_raster_nodes::adjustments::VibranceNode",
"graphene_core::raster::adjustments::VibranceNode",
"graphene_core::raster::VibranceNode",
"raster_nodes::adjustments::vibrance_shader_node::VibranceShaderNodeNode",
],
},
// ================================
@@ -1849,35 +1819,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::Integer(integer), exposed), &network_path);
}
let cpu_raster_type_defaults: Vec<(NodeId, Vec<NodeId>, usize, Type, bool)> = document
.network_interface
.document_network()
.recursive_nodes()
.flat_map(|(node_id, node, path)| {
node.inputs
.iter()
.enumerate()
.filter_map(|(index, input)| {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
let TaggedValue::TypeDefault(stored_type) = &**tagged_value else { return None };
let gpu_type = if *stored_type == item!(Raster<CPU>) {
item!(Raster<GPU>)
} else if *stored_type == list!(Raster<CPU>) {
list!(Raster<GPU>)
} else {
return None;
};
Some((*node_id, path.clone(), index, gpu_type, *exposed))
})
.collect::<Vec<_>>()
})
.collect();
for (node_id, network_path, index, gpu_type, exposed) in cpu_raster_type_defaults {
document
.network_interface
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::type_default(gpu_type, exposed), &network_path);
}
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
@@ -3506,6 +3447,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[2].clone(), network_path);
}
// Load Image's URL is empty until set, it used to be `graphite:null`
if reference == DefinitionIdentifier::Network("Load Image".into())
&& let Some(url) = node.inputs.get(1)
&& matches!(url.as_value(), Some(TaggedValue::String(url)) if url == "graphite:null")
{
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 1),
NodeInput::value(TaggedValue::String(String::new()), url.is_exposed()),
network_path,
);
}
// `wgpu-executor` scope was removed, change to the auto injected scope node `graphene_std::platform_application_io::wgpu_executor`
for (i, input) in node.inputs.iter().enumerate() {
if let NodeInput::Scope(name) = input
@@ -3519,56 +3472,6 @@ 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::blending_nodes::color_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::std_nodes::noise_pattern::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER,
graphene_std::raster_nodes::filter::median_filter::IDENTIFIER,
graphene_std::raster_nodes::filter::blur::IDENTIFIER,
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::image::IDENTIFIER,
graphene_std::platform_application_io::bytes_to_image::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) {
@@ -3674,11 +3577,11 @@ fn modifications_following_turned_segments(network: &graph_craft::document::Node
};
// Where the output comes from: the node itself, or the nodes a network node exports
let sources: Vec<Location> = match &origin_node.implementation {
DocumentNodeImplementation::Network(nested) => (0..nested.exports.len())
let sources: Vec<Location> = match network.implementation_network(&origin_node.implementation) {
Some(nested) => (0..nested.exports.len())
.filter_map(|output| producing_node(network, origin_path, &NodeInput::node(*origin_id, output), 0))
.collect(),
_ => vec![origin.clone()],
None => vec![origin.clone()],
};
let mut reached = HashSet::new();
@@ -3736,9 +3639,9 @@ fn producing_node(network: &graph_craft::document::NodeNetwork, network_path: &[
match input {
NodeInput::Node { node_id, output_index } => {
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
match &node.implementation {
DocumentNodeImplementation::Network(nested) => producing_node(network, &[network_path, &[*node_id]].concat(), nested.exports.get(*output_index)?, depth + 1),
_ => Some((network_path.to_vec(), *node_id)),
match network.implementation_network(&node.implementation) {
Some(nested) => producing_node(network, &[network_path, &[*node_id]].concat(), nested.exports.get(*output_index)?, depth + 1),
None => Some((network_path.to_vec(), *node_id)),
}
}
NodeInput::Import { import_index, .. } => {
@@ -3880,13 +3783,11 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
}
}
// The removed Upload Texture node, in its proto node form or its old wrapper-network form, degrades to a passthrough of its content since rasters now load onto the GPU
if matches!(
document.network_interface.reference(node_id, network_path),
Some(DefinitionIdentifier::ProtoNode(identifier)) if identifier.as_str().ends_with("::UploadTextureNode")
) || matches!(document.network_interface.reference(node_id, network_path), Some(DefinitionIdentifier::Network(name)) if name == "Upload Texture")
// The Upload Texture node's old wrapper-network form maps onto its proto node form, which draws the executor from scope
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
&& name == "Upload Texture"
{
let mut node_template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)?.default_node_template();
let mut node_template = resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER)?.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)?;
if let Some(content) = old_inputs.first() {
@@ -4103,6 +4004,7 @@ mod tests {
#[test]
fn removed_definition_swap_targets_resolve() {
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
assert!(resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER).is_some());
}
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
@@ -4567,7 +4469,7 @@ mod tests {
migrate(&mut document);
let image_node = &document.network_interface.document_network().nodes[&image_id];
assert_eq!(image_node.inputs.len(), 3, "the image node should gain its placeholder primary input and pipeline scope input");
assert_eq!(image_node.inputs.len(), 2, "the image node should gain its placeholder primary input");
let migrated = &image_node.inputs[1];
match legacy_input.as_value() {
None => assert_eq!(migrated.as_node(), Some(upstream_id), "the wire should sit at input 1"),
@@ -4602,49 +4504,6 @@ mod tests {
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
}
#[test]
fn cpu_raster_type_defaults_become_gpu_defaults() {
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let mut blur_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::filter::blur::IDENTIFIER))
.expect("the definition should exist")
.default_node_template();
blur_template.inputs[0] = NodeInput::type_default(item!(Raster<CPU>), true);
document.network_interface.insert_node(node_id, blur_template, &[]);
migrate(&mut document);
let migrated = &document.network_interface.document_network().nodes[&node_id].inputs[0];
assert_eq!(
migrated.as_value(),
Some(&TaggedValue::TypeDefault(item!(Raster<GPU>))),
"the CPU raster default should become the GPU raster default"
);
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
}
#[test]
fn upload_texture_becomes_passthrough() {
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let mut template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)
.expect("the definition should exist")
.default_node_template();
template.implementation = NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_std::platform_application_io::UploadTextureNode"));
template.inputs = vec![
NodeInput::type_default(item!(Raster<GPU>), true),
NodeInput::scope("graphene_std::platform_application_io::WgpuExecutorNode"),
];
document.network_interface.insert_node(node_id, template, &[]);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
assert_eq!(node.inputs.len(), 1, "the executor scope input should be dropped");
assert_eq!(node.inputs[0].as_value(), Some(&TaggedValue::TypeDefault(item!(Raster<GPU>))), "the content should be kept");
}
#[test]
fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -480,7 +480,8 @@ pub fn star_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMessa
let viewport = document.metadata().transform_to_viewport(layer);
let points = sides as u64;
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(star_polygon_bezpath(DVec2::ZERO, points, radius1, radius2))];
let Ok(star) = star_polygon_bezpath(DVec2::ZERO, points, radius1, radius2) else { return };
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(star)];
overlay_context.outline(targets.iter(), viewport, None);
}
@@ -495,7 +496,8 @@ pub fn polygon_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMe
let viewport = document.metadata().transform_to_viewport(layer);
let points = sides as u64;
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(regular_polygon_bezpath(DVec2::ZERO, points, radius))];
let Ok(polygon) = regular_polygon_bezpath(DVec2::ZERO, points, radius) else { return };
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(polygon)];
overlay_context.outline(targets.iter(), viewport, None);
}
+49 -10
View File
@@ -58,7 +58,7 @@ pub type NodeErrorTrace = Box<[NodePaths]>;
pub type NodePaths = Box<[Box<[NodeId]>]>;
impl EvaluationErrors {
fn iter(&self) -> impl Iterator<Item = (&(dyn std::error::Error + Send + Sync), &NodeErrorTrace)> {
pub(crate) fn iter(&self) -> impl Iterator<Item = (&(dyn std::error::Error + Send + Sync + 'static), &NodeErrorTrace)> {
self.0.iter().map(|(error, trace)| (&**error, trace))
}
}
@@ -97,6 +97,11 @@ pub struct NodeGraphExecutor {
node_graph_document: Option<DocumentId>,
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
previous_node_to_inspect: Vec<NodeId>,
/// The canvas images the frontend holds, so a render sends only those it lacks.
canvas_images_sent: HashSet<u64>,
/// Evaluation errors of the last evaluation, used in tests
#[cfg(test)]
evaluation_errors: Option<EvaluationErrors>,
// TODO: Eventually remove this document upgrade code
/// In-progress one-time pre-pass that converts legacy bounding-box-relative gradients to absolute space, if any.
gradient_migration: Option<GradientMigration>,
@@ -104,8 +109,6 @@ pub struct NodeGraphExecutor {
/// Documents whose gradient migration pass already ran this session, so entries that failed to measure
/// (kept pending for a retry on the next open) don't re-run the pass on every render request.
gradient_migration_attempted: HashSet<DocumentId>,
/// The canvas images the frontend holds, so a render sends only those it lacks.
canvas_images_sent: HashSet<u64>,
}
#[derive(Debug, Clone)]
@@ -140,17 +143,19 @@ impl NodeGraphExecutor {
let node_runtime = NodeRuntime::new(request_receiver, response_sender, editor_wake);
let node_executor = Self {
futures: Default::default(),
sender: request_sender,
receiver: response_receiver,
futures: Default::default(),
pending: None,
current_execution_id: 0,
node_graph_hash: 0,
node_graph_document: None,
current_execution_id: 0,
previous_node_to_inspect: Vec::new(),
canvas_images_sent: HashSet::new(),
#[cfg(test)]
evaluation_errors: None,
gradient_migration: None,
gradient_migration_attempted: HashSet::new(),
pending: None,
canvas_images_sent: HashSet::new(),
};
(node_executor, node_runtime)
}
@@ -166,6 +171,12 @@ impl NodeGraphExecutor {
self.current_execution_id
}
/// Allows the test runner to access last executions evaluation errors.
#[cfg(test)]
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
self.evaluation_errors.take()
}
/// Execute the network by flattening it and creating a borrow stack.
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
let execution_id = self.current_execution_id;
@@ -198,6 +209,7 @@ impl NodeGraphExecutor {
// We should always invalidate the cache.
self.node_graph_hash = crate::application::generate_uuid();
let mut network = document.network_interface.document_network().clone();
network.inline_definitions().map_err(|error| error.to_string())?;
let instrumented = Instrumented::new(&mut network);
let resources = document.resources.registry.clone();
@@ -493,7 +505,10 @@ impl NodeGraphExecutor {
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
let errors = match &result {
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
let in_document = |path: &&[NodeId]| path.split_last().is_some_and(|(node, network)| document.network_interface.document_node(node, network).is_some());
let in_document = |path: &&[NodeId]| {
path.split_last()
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
};
errors
.iter()
.flat_map(|(error, trace)| {
@@ -515,10 +530,28 @@ impl NodeGraphExecutor {
responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors });
}
#[cfg(test)]
{
self.evaluation_errors = None;
}
let node_graph_output = match result {
ExecutionResult::Pending => Ok(None),
ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => Ok(Some(value)),
ExecutionResult::Error(errors) => Err(errors.to_string()),
ExecutionResult::Value(value) => Ok(Some(value)),
ExecutionResult::Fallback(value, _errors) => {
#[cfg(test)]
{
self.evaluation_errors = Some(_errors);
}
Ok(Some(value))
}
ExecutionResult::Error(errors) => {
let message = errors.to_string();
#[cfg(test)]
{
self.evaluation_errors = Some(errors);
}
Err(message)
}
ExecutionResult::Panic(payload) => {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
Err(format!("Panicked: {}", message.unwrap_or("no message")))
@@ -729,6 +762,12 @@ impl NodeGraphExecutor {
// On this throwaway clone, redirect each level's export down to the Fill, un-hiding the Fill and its enclosing subnetworks so it's measured as a real Fill rather than a passthrough.
// But upstream generators keep their visibility, so a hidden one intentionally contributes no geometry.
let full_path: Vec<NodeId> = network_path.iter().copied().chain(std::iter::once(fill_node_id)).collect();
if let Err(error) = network.inline_definitions() {
log::error!("Gradient migration: could not inline the document's network definitions: {error}; dropping the pending gradient bake of fill node {fill_node_id:?}");
remove_pending_gradient_bake(document, &network_path, fill_node_id);
self.advance_gradient_migration(document, document_id, responses);
return;
}
if !redirect_export_chain(&mut network, &full_path) {
// The fill was deleted or is otherwise unreachable, so drop its stale entry instead of retrying it on every open
log::warn!("Gradient migration: could not redirect the document network's export chain to fill node {fill_node_id:?}; dropping its pending gradient bake");
+35 -22
View File
@@ -9,17 +9,17 @@ use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::Instrumented;
use crate::node_graph_executor::NodeRuntime;
use crate::node_graph_executor::{EvaluationErrors, NodeRuntime};
use crate::task::{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::uuid::NodeId;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, LazyLock};
/// A set of utility functions to make the writing of editor test more declarative
pub struct EditorTestUtils {
@@ -42,7 +42,7 @@ impl EditorTestUtils {
.with_resource_storage(Arc::new(HashMapResourceStorage::new()))
.with_document_store(Arc::new(MemoryStore::default())),
)
.with_runtime(RuntimeBuilder::new().with_wake(|| {}).with_application_io(gpu_application_io()))
.with_runtime(RuntimeBuilder::new().with_wake(|| {}).with_application_io(PlatformApplicationIo::default()))
.with_spawner(BlockingSpawner)
.with_random_seed(0)
.build();
@@ -68,7 +68,7 @@ impl EditorTestUtils {
/// Submit an evaluation to the executor, run the runtime, and process the results.
///
/// If a deferred message triggers a second graph run, this will not occur. See [`Self::eval_graph_until_finished`] for this behaviour.
async fn eval_graph_once(&mut self) -> Result<Instrumented, String> {
async fn eval_graph_once(&mut self) -> Result<Instrumented, TestGraphError> {
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);
@@ -76,17 +76,23 @@ impl EditorTestUtils {
let instrumented = match executor.update_node_graph_instrumented(document) {
Ok(instrumented) => instrumented,
Err(e) => return Err(format!("update_node_graph_instrumented failed\n\n{e}")),
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
};
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
}
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());
let evaluation_errors = self.portfolio_message_handler_mut().executor.take_evaluation_errors();
if evaluation_errors.is_none() && frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
return Err(TestGraphError::Render);
}
#[cfg(feature = "gpu")]
let evaluation_errors = evaluation_errors.filter(|errors| !errors.iter().all(|(error, _)| error.is::<wgpu_executor::NoGpuError>()));
if let Some(errors) = evaluation_errors {
return Err(TestGraphError::Evaluation(errors));
}
for message in frontend_messages {
@@ -97,7 +103,7 @@ impl EditorTestUtils {
}
/// 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, String> {
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
const MAX_ITERATIONS: usize = 16;
for _iteration in 0..MAX_ITERATIONS {
let execution_id = self.portfolio_message_handler().executor.current_execution_id();
@@ -107,7 +113,7 @@ impl EditorTestUtils {
return Ok(result);
}
}
return Err(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping"));
return Err(TestGraphError::Other(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping")));
}
pub async fn handle_message(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
@@ -416,6 +422,23 @@ impl FrontendMessageTestUtils for FrontendMessage {
}
}
#[derive(Debug)]
pub enum TestGraphError {
Evaluation(EvaluationErrors),
Render,
Other(String),
}
impl std::fmt::Display for TestGraphError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Evaluation(errors) => write!(f, "Graph evaluation failed:\n{errors}"),
Self::Render => write!(f, "Graph should render"),
Self::Other(message) => write!(f, "{message}"),
}
}
}
thread_local! {
static CAPTURED_ERRORS: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
}
@@ -459,16 +482,6 @@ 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();
@@ -501,7 +514,7 @@ pub mod test_prelude {
pub use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, is_layer_fed_by_node_of_name};
pub use crate::messages::tool::utility_types::ToolType;
pub use crate::node_graph_executor::NodeRuntime;
pub use crate::test_utils::EditorTestUtils;
pub use crate::test_utils::{EditorTestUtils, TestGraphError};
pub use core::f64;
pub use glam::{DVec2, IVec2};
pub use graph_craft::document::DocumentNode;
+2 -1
View File
@@ -11,10 +11,11 @@ publish.workspace = true
readme = "./README.md"
[features]
default = ["gpu", "web"]
default = ["gpu", "shader-nodes", "web"]
web = ["editor", "editor?/wasm"]
editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:spin", "dep:wgpu"]
gpu = ["editor?/gpu"]
shader-nodes = ["graphene-std?/shader-nodes", "gpu"]
native = []
[lib]
+74 -18
View File
@@ -9,7 +9,7 @@ use core_types::{Context, Cow, MemoHash, NodeCompileMetadata, NodeParameter, Pro
use dyn_any::DynAny;
use glam::IVec2;
use log::Metadata;
use rustc_hash::FxHashMap;
use rustc_hash::{FxHashMap, FxHashSet};
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
@@ -145,6 +145,10 @@ impl DocumentNode {
let mut construction_args = ConstructionArgs::Nodes(vec![]);
// If we have one input of the type inline, set it as the construction args
if let &[NodeInput::Inline(ref inline)] = self.inputs.as_slice() {
construction_args = ConstructionArgs::Inline(inline.clone());
}
// If we have one input of the type inline, set it as the construction args
if let &[NodeInput::Value { ref tagged_value, .. }] = self.inputs.as_slice() {
construction_args = ConstructionArgs::Value(tagged_value.clone());
@@ -191,6 +195,22 @@ pub enum NodeInput {
/// Input that is replaced at graph compilation with introspective metadata about this node's location.
Reflection(DocumentNodeMetadata),
/// A Rust source code string. Allows us to insert literal Rust code. Only used for GPU compilation.
/// We can use this whenever we spin up Rustc. Sort of like inline assembly, but because our language is Rust, it acts as inline Rust.
Inline(InlineRust),
}
#[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
pub struct InlineRust {
pub expr: String,
pub ty: Type,
}
impl InlineRust {
pub fn new(expr: String, ty: Type) -> Self {
Self { expr, ty }
}
}
#[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
@@ -243,6 +263,7 @@ impl NodeInput {
NodeInput::Node { .. } => true,
NodeInput::Value { exposed, .. } => *exposed,
NodeInput::Import { .. } => true,
NodeInput::Inline(_) => false,
NodeInput::Scope(_) => false,
NodeInput::Reflection(_) => false,
}
@@ -254,6 +275,7 @@ impl NodeInput {
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
// Stored import types are normalized to their structural form once at document migration
NodeInput::Import { import_type, .. } => import_type.clone(),
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
NodeInput::Reflection(_) => concrete!(Metadata),
}
@@ -286,9 +308,9 @@ pub enum OldDocumentNodeImplementation {
#[repr(transparent)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, core_types::CacheHash, PartialOrd, Ord, DynAny, serde::Serialize, serde::Deserialize)]
pub struct DefinitionId(pub u64);
pub struct NetworkId(pub u64);
impl DefinitionId {
impl NetworkId {
pub fn new() -> Self {
Self(generate_uuid())
}
@@ -301,7 +323,7 @@ pub enum DocumentNodeImplementation {
///
/// A nested [`NodeNetwork`] that is flattened by the [`NodeNetwork::flatten`] function.
Network(NodeNetwork),
Definition(DefinitionId),
Definition(NetworkId),
/// This describes a (document) node implemented as a proto node.
///
/// A proto node identifier which can be found in `node_registry.rs`.
@@ -550,21 +572,21 @@ pub struct NodeNetwork {
)]
pub scope_injections: FxHashMap<String, (NodeId, Type)>,
#[serde(default, skip_serializing_if = "FxHashMap::is_empty")]
pub definitions: FxHashMap<DefinitionId, NodeNetwork>,
pub definitions: FxHashMap<NetworkId, NodeNetwork>,
#[serde(skip)]
pub generated: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NetworkLocation<'a> {
pub definition: Option<DefinitionId>,
pub definition: Option<NetworkId>,
pub inline_path: &'a [NodeId],
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DefinitionError {
Missing(DefinitionId),
Cycle(Vec<DefinitionId>),
Missing(NetworkId),
Cycle(Vec<NetworkId>),
NestedTable,
}
@@ -581,9 +603,9 @@ impl std::fmt::Display for DefinitionError {
impl std::error::Error for DefinitionError {}
struct DefinitionInliner {
definitions: FxHashMap<DefinitionId, NodeNetwork>,
inlined: FxHashMap<DefinitionId, NodeNetwork>,
visiting: Vec<DefinitionId>,
definitions: FxHashMap<NetworkId, NodeNetwork>,
inlined: FxHashMap<NetworkId, NodeNetwork>,
visiting: Vec<NetworkId>,
}
impl DefinitionInliner {
@@ -603,7 +625,7 @@ impl DefinitionInliner {
Ok(())
}
fn inlined_definition(&mut self, id: DefinitionId) -> Result<&NodeNetwork, DefinitionError> {
fn inlined_definition(&mut self, id: NetworkId) -> Result<&NodeNetwork, DefinitionError> {
if !self.inlined.contains_key(&id) {
if let Some(start) = self.visiting.iter().position(|&visiting| visiting == id) {
return Err(DefinitionError::Cycle(self.visiting[start..].to_vec()));
@@ -927,6 +949,9 @@ impl NodeNetwork {
for node in self.nodes.values_mut() {
node.normalize_stored_types();
}
for definition in self.definitions.values_mut() {
definition.normalize_stored_types();
}
}
/// Replace all references in the graph of a node ID with a new node ID defined by the function `f`.
@@ -1177,6 +1202,7 @@ impl NodeNetwork {
*import_index = parent_input_index;
}
NodeInput::Value { .. } => unreachable!("Value inputs should have been replaced with value nodes"),
NodeInput::Inline(_) => (),
NodeInput::Scope(_) => unreachable!("Scope inputs should have been resolved by resolve_scope_inputs_recursive before flattening"),
NodeInput::Reflection(_) => unreachable!("Reflection inputs should have been replaced with value nodes"),
}
@@ -1418,7 +1444,11 @@ impl NodeNetwork {
/// Create a [`RecursiveNodeIter`] that iterates over all [`DocumentNode`]s, including ones that are deeply nested.
pub fn recursive_nodes(&self) -> RecursiveNodeIter<'_> {
let nodes = self.nodes.iter().map(|(id, node)| (id, node, Vec::new())).collect();
RecursiveNodeIter { nodes }
RecursiveNodeIter {
definitions: &self.definitions,
visited_definitions: FxHashSet::default(),
nodes,
}
}
/// Ensure the cached list of dependants exactly matches the real list of dependants
@@ -1455,7 +1485,10 @@ impl NodeNetwork {
}
/// An iterator over all [`DocumentNode`]s, including ones that are deeply nested.
/// Each definition body is visited once, under the path of the first instance reached.
pub struct RecursiveNodeIter<'a> {
definitions: &'a FxHashMap<NetworkId, NodeNetwork>,
visited_definitions: FxHashSet<NetworkId>,
nodes: Vec<(&'a NodeId, &'a DocumentNode, Vec<NodeId>)>,
}
@@ -1463,7 +1496,12 @@ impl<'a> Iterator for RecursiveNodeIter<'a> {
type Item = (&'a NodeId, &'a DocumentNode, Vec<NodeId>);
fn next(&mut self) -> Option<Self::Item> {
let (current_id, node, path) = self.nodes.pop()?;
if let DocumentNodeImplementation::Network(network) = &node.implementation {
let nested_network = match &node.implementation {
DocumentNodeImplementation::Network(network) => Some(network),
DocumentNodeImplementation::Definition(id) if self.visited_definitions.insert(*id) => self.definitions.get(id),
_ => None,
};
if let Some(network) = nested_network {
self.nodes.extend(network.nodes.iter().map(|(id, node)| {
let mut nested_path = path.clone();
nested_path.push(*current_id);
@@ -2088,7 +2126,7 @@ mod test {
DocumentNode { implementation, ..Default::default() }
}
fn network_with(nodes: impl IntoIterator<Item = (NodeId, DocumentNodeImplementation)>, definitions: impl IntoIterator<Item = (DefinitionId, NodeNetwork)>) -> NodeNetwork {
fn network_with(nodes: impl IntoIterator<Item = (NodeId, DocumentNodeImplementation)>, definitions: impl IntoIterator<Item = (NetworkId, NodeNetwork)>) -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(10), 0)],
nodes: nodes.into_iter().map(|(id, implementation)| (id, node_with(implementation))).collect(),
@@ -2097,7 +2135,7 @@ mod test {
}
}
const ADD: DefinitionId = DefinitionId(1);
const ADD: NetworkId = NetworkId(1);
fn two_add_instances() -> NodeNetwork {
network_with(
@@ -2123,7 +2161,7 @@ mod test {
#[test]
fn definitions_referencing_definitions_inline_transitively() {
let outer = DefinitionId(2);
let outer = NetworkId(2);
let mut network = network_with(
[(NodeId(10), DocumentNodeImplementation::Definition(outer))],
[(ADD, add_network()), (outer, network_with([(NodeId(10), DocumentNodeImplementation::Definition(ADD))], []))],
@@ -2136,7 +2174,7 @@ mod test {
#[test]
fn invalid_definition_tables_are_rejected() {
let (first, second) = (DefinitionId(2), DefinitionId(3));
let (first, second) = (NetworkId(2), NetworkId(3));
let mut cyclic = network_with(
[(NodeId(10), DocumentNodeImplementation::Definition(first))],
[
@@ -2178,4 +2216,22 @@ mod test {
network.definitions.get_mut(&ADD).unwrap().exports.push(NodeInput::node(NodeId(0), 0));
assert_ne!(network.current_hash(), before);
}
#[test]
fn recursive_nodes_visit_each_definition_once() {
let network = two_add_instances();
let body_paths = network.recursive_nodes().map(|(_, _, path)| path).filter(|path| !path.is_empty()).collect::<Vec<_>>();
assert_eq!(body_paths.len(), add_network().nodes.len());
assert!(body_paths.windows(2).all(|pair| pair[0] == pair[1]));
let (first, second) = (NetworkId(2), NetworkId(3));
let cyclic = network_with(
[(NodeId(10), DocumentNodeImplementation::Definition(first))],
[
(first, network_with([(NodeId(10), DocumentNodeImplementation::Definition(second))], [])),
(second, network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], [])),
],
);
assert_eq!(cyclic.recursive_nodes().count(), 3);
}
}
+1 -3
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, GPU, Image, Raster};
use graphic_types::raster_types::{CPU, 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,7 +36,6 @@ macro_rules! for_each_item_type_default {
$action!(Vector);
$action!(f64);
$action!(Raster<CPU>);
$action!(Raster<GPU>);
$action!(Graphic);
$action!(Color);
$action!(Gradient);
@@ -53,7 +52,6 @@ macro_rules! for_each_list_type_default {
$action!(Graphic);
$action!(Artboard);
$action!(Raster<CPU>);
$action!(Raster<GPU>);
$action!(Vector);
$action!(String);
$action!(Color);
+11 -2
View File
@@ -1,5 +1,5 @@
use crate::document::value;
use crate::document::value::TaggedValue;
use crate::document::{InlineRust, value};
use crate::document::{NodeId, OriginalLocation};
pub use core_types::registry::*;
use core_types::*;
@@ -51,6 +51,10 @@ impl core::fmt::Display for ProtoNetwork {
write_node(f, network, *id, indent + 1)?;
}
}
ConstructionArgs::Inline(inline) => {
f.write_str(&"\t".repeat(indent + 1))?;
f.write_fmt(format_args!("Inline construction argument: {inline:?}"))?
}
}
f.write_str(&"\t".repeat(indent))?;
f.write_str("}\n")?;
@@ -71,6 +75,8 @@ pub enum ConstructionArgs {
/// The bool indicates whether to treat the node as lambda node.
// TODO: use a struct for clearer naming.
Nodes(Vec<NodeId>),
/// Used for GPU computation to work around the limitations of rust-gpu.
Inline(InlineRust),
}
impl Eq for ConstructionArgs {}
@@ -103,6 +109,7 @@ impl CacheHash for ConstructionArgs {
}
}
Self::Value(value) => value.cache_hash(state),
Self::Inline(inline) => inline.hash(state),
}
}
}
@@ -112,6 +119,7 @@ impl ConstructionArgs {
match self {
ConstructionArgs::Nodes(nodes) => nodes.iter().map(|n| format!("n{:0x}", n.0)).collect(),
ConstructionArgs::Value(value) => vec![value.to_primitive_string()],
ConstructionArgs::Inline(inline) => vec![inline.expr.clone()],
}
}
}
@@ -432,7 +440,7 @@ impl ProtoNetwork {
Some(id),
);
}
ConstructionArgs::Value(_) => return (dependencies.extract.into(), Some(id)),
ConstructionArgs::Value(_) | ConstructionArgs::Inline(_) => return (dependencies.extract.into(), Some(id)),
};
// Compute the dependencies for each branch and combine all of them
@@ -869,6 +877,7 @@ impl TypingContext {
.map(|node| node.ty())
})
.collect::<Result<Vec<Type>, GraphErrors>>()?,
ConstructionArgs::Inline(ref inline) => vec![inline.ty.clone()],
};
// Get the node input type from the proto node declaration
+2
View File
@@ -152,6 +152,7 @@ pub fn print(network: &ProtoNetwork, document: &Document, format: Format, upstre
let arguments = match &node.proto.construction_args {
ConstructionArgs::Nodes(_) => format!("({})", node.inputs.iter().map(|&input| id(input)).collect::<Vec<_>>().join(", ")),
ConstructionArgs::Value(value) => format!("{{{}}}", summary(value, 80)),
ConstructionArgs::Inline(inline) => format!("{{{}}}", inline.expr),
};
let shared = if node.origins.len() > 1 { "(shared)" } else { "" };
let provenance = [node.kind.tag(), &location(node.origins[0]), shared]
@@ -245,6 +246,7 @@ fn constant<'a>(nodes: &[Node<'a>], mut n: usize) -> Option<&'a TaggedValue> {
match &nodes[n].proto.construction_args {
ConstructionArgs::Value(value) => return Some(&**value),
ConstructionArgs::Nodes(_) => n = *nodes[n].inputs.first()?,
ConstructionArgs::Inline(_) => return None,
}
}
}
+81 -3
View File
@@ -1,11 +1,13 @@
use crate::TokioSpawner;
use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2};
use graph_craft::document::value::{DAffine2, DVec2, RenderOutputType, TaggedValue, UVec2};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::core_types::ops::ConvertAsync;
use graphene_std::core_types::transform::Footprint;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::{no_paths, paths_from_item_attributes};
use graphene_std::{Cover, Coverage};
use graphene_std::{NodeError, Poll};
use image::ImageFormat;
use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -73,6 +75,80 @@ pub struct ExportSettings {
pub size: (Option<u32>, Option<u32>),
/// Whether raster formats that can keep transparency do so, instead of compositing onto white
pub transparent: bool,
/// The document region to render, which [`ExportSettings::framed`] fits to the artwork when no size is given
pub framing: Option<Framing>,
}
/// A document-space region mapped onto the output pixels.
#[derive(Debug, Clone, Copy)]
pub struct Framing {
pub transform: DAffine2,
pub resolution: UVec2,
}
impl ExportSettings {
/// Frame the artwork as it is at time zero, unless a size was given.
/// Every frame of an animation shares this framing, so they all have one size.
pub async fn framed(mut self, executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Self, Box<dyn Error>> {
if self.size.0.is_some() && self.size.1.is_some() {
return Ok(self);
}
let [min, max] = artwork_bounds(executor, runtime, spawner).await?.ok_or("The document has no artwork to export")?;
let resolution = ((max - min) * self.scale).round().max(DVec2::ONE).as_uvec2();
self.framing = Some(Framing {
transform: DAffine2::from_translation(min).inverse(),
resolution,
});
Ok(self)
}
}
/// The document-space bounds of every layer including its stroke, artboards included, from the metadata of an SVG render.
/// Content an artboard clips away still counts, since this has no layer tree to tell which artboard holds it.
async fn artwork_bounds(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Option<[DVec2; 2]>, Box<dyn Error>> {
// An identity viewport, since the default one is degenerate and its transforms come out NaN
let render_config = RenderConfig {
viewport: Footprint {
transform: DAffine2::IDENTITY,
resolution: UVec2::ONE,
..Default::default()
},
scale: 1.,
export_format: ExportFormat::Svg,
for_export: true,
..Default::default()
};
let TaggedValue::RenderOutput(output) = execute_until_settled(executor, runtime, spawner, render_config).await? else {
return Err("The document did not render".into());
};
let metadata = &output.metadata;
let layer_bounds = metadata.click_targets.iter().filter_map(|(layer, click_targets)| {
let footprint = metadata.upstream_footprints.get(layer).map(|footprint| footprint.transform).unwrap_or_default();
let local_transform = metadata.local_transforms.get(layer).copied().unwrap_or_default();
let transform = footprint * local_transform;
// A stroke extends past the path a click target outlines, so a vector layer also measures its rendered geometry.
// Metadata only records the first item of a layer, so the other items count through their click targets, without their strokes.
let stroked = metadata.vector_data.get(layer).and_then(|item| {
let appearance = metadata.appearance_attributes.get(layer);
let stroke = appearance.and_then(|appearance| appearance.first_coverage_of(Cover::Stroke)).map(Coverage::stroke_params);
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
item.element().stroke_inclusive_bounding_box_with_transform(paths, transform, stroke.as_ref())
});
click_targets
.iter()
.filter_map(|click_target| click_target.bounding_box_with_transform(transform))
.chain(stroked)
.reduce(combine_bounds)
});
Ok(layer_bounds.reduce(combine_bounds))
}
fn combine_bounds([a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]) -> [DVec2; 2] {
[a_min.min(b_min), a_max.max(b_max)]
}
/// Renders the document at the given animation time, as SVG text for an SVG export and as pixels for every other file type.
@@ -104,8 +180,10 @@ async fn render_frame(
..Default::default()
};
// Set viewport dimensions if specified
if let (Some(w), Some(h)) = (width, height) {
if let Some(framing) = settings.framing {
render_config.viewport.transform = framing.transform;
render_config.viewport.resolution = framing.resolution;
} else if let (Some(w), Some(h)) = (width, height) {
render_config.viewport.resolution = UVec2::new(w, h);
}
+4 -1
View File
@@ -237,7 +237,10 @@ async fn main() -> Result<(), Box<dyn Error>> {
scale,
size: (width, height),
transparent,
};
framing: None,
}
.framed(&executor, &runtime, &spawner)
.await?;
let animation = export::AnimationParams::new(fps, frames, duration);
if file_type == export::FileType::Gif {
export::export_gif(&executor, wgpu_executor_ref, output, settings, animation, &runtime, &spawner).await?;
@@ -503,6 +503,7 @@ impl BorrowTree {
/// - Updates the source map using [`update_source_map`](BorrowTree::update_source_map) before inserting the node.
/// - Handles different types of construction arguments:
/// - `Value`: Creates a node from a `TaggedValue`, with special handling for `EditorApi` values.
/// - `Inline`: Currently unimplemented. Only used for `rust-gpu` support.
/// - `Nodes`: Constructs a node using other nodes as dependencies.
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
/// - Returns an error if no constructor is found for the given node ID.
@@ -517,6 +518,7 @@ impl BorrowTree {
let node = ObservedNode::new(Box::new(upcasted) as TypeErasedBox<'_>);
self.store_node(node, id, path.into(), Box::default());
}
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
ConstructionArgs::Nodes(ids) => {
let ids = ids.to_vec();
let mut construction_nodes = self.node_deps(&ids);
@@ -1,7 +1,7 @@
use dyn_any::StaticType;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::application_io::resource::Resource;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::RenderOutput;
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
use graphene_animation::AnimationCurve;
@@ -51,8 +51,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
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<DashPattern>]),
@@ -88,10 +86,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<AttributeValueDyn>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Arc<PlatformEditorApi>>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Arc<PlatformApplicationIo>>, Context => Item<graphene_std::ContextModification>]),
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
@@ -136,6 +134,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ListDyn]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<RenderOutput>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Arc<PlatformEditorApi>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Arc<PlatformApplicationIo>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::RuntimeHandle>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::SourceId>]),
#[cfg(feature = "gpu")]
@@ -143,7 +142,6 @@ 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.
+7 -23
View File
@@ -1,6 +1,6 @@
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeInput, NodeNetwork};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, 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(6), 0)],
exports: vec![NodeInput::node(NodeId(5), 0)],
nodes: [
DocumentNode {
call_argument: concrete!(Context),
@@ -42,23 +42,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::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::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -69,7 +53,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::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -80,7 +64,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(3), 0)],
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -93,7 +77,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(4), 0),
NodeInput::node(NodeId(3), 0),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
@@ -105,7 +89,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::node(NodeId(5), 0)],
inputs: vec![NodeInput::node(NodeId(4), 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 -5
View File
@@ -16,13 +16,15 @@ workspace = true
[features]
default = ["serde"]
serde = ["dep:serde", "glam/serde", "half/serde"]
serde = ["dep:serde"]
nightly = []
type_id_logging = []
dealloc_nodes = []
wasm = ["tsify", "wasm-bindgen"]
wasm = ["tsify", "wasm-bindgen", "no-std-types/wasm"]
[dependencies]
# Local dependencies
no-std-types = { workspace = true, features = ["std"] }
graphene-hash = { workspace = true, features = ["derive"] }
# Workspace dependencies
@@ -31,9 +33,6 @@ 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 }
@@ -52,6 +51,7 @@ log = { workspace = true }
base64 = { workspace = true }
polycool = { workspace = true }
futures = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
+2 -24
View File
@@ -1,6 +1,7 @@
use crate::runtime::{Generations, SourceId};
use crate::transform::Footprint;
use glam::{DAffine2, DVec2};
use glam::DVec2;
pub use no_std_types::context::{ArcCtx, Ctx};
use std::any::Any;
use std::borrow::Borrow;
use std::collections::BTreeSet;
@@ -8,15 +9,6 @@ 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
// ==============
@@ -772,20 +764,6 @@ 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
+5 -12
View File
@@ -1,9 +1,6 @@
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;
@@ -37,6 +34,11 @@ pub use list::{
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 no_std_types::shaders;
pub use num_traits;
pub use poll::{Finality, Interrupt, LazyInput, NodeError, Poll, PollInput, Status};
pub use runtime::{Generations, RuntimeHandle, SourceId};
@@ -164,12 +166,3 @@ 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
}
}
+182 -44
View File
@@ -1,3 +1,4 @@
use crate::TypeDescriptor;
use crate::bounds::{BoundingBox, RenderBoundingBox};
use crate::math::quad::Quad;
use crate::transform::ApplyTransform;
@@ -203,6 +204,12 @@ fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> {
}
}
/// What pushing and extending lists pad a missing `key` attribute with: `key`'s implicit default if it has type `T`, otherwise
/// `T::default()`.
pub fn implicit_default<T: Clone + Default + 'static>(key: &str) -> T {
implicit_default_value(key).and_then(|default| default.as_any().downcast_ref::<T>().cloned()).unwrap_or_default()
}
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]).
fn pad_with_implicit_default(key: &str, attribute: &mut dyn AnyAttribute, count: usize) {
match implicit_default_value(key) {
@@ -398,8 +405,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
/// Converts the shared attribute into one that can be downcast to its concrete type.
fn into_any_arc(self: Arc<Self>) -> Arc<dyn std::any::Any + Send + Sync>;
/// Pushes a scalar attribute value onto the end of this attribute.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>);
/// Pushes a scalar attribute value onto the end of this attribute, or a default if it has another type, which returns `false`.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) -> bool;
/// Pushes a default value onto the end of this attribute.
fn push_default(&mut self);
@@ -409,8 +416,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
fn push_repeated(&mut self, value: &dyn AnyAttributeValue, count: usize);
/// Sets the value at the given index, padding with defaults if the attribute is shorter than `index`.
/// Falls back to a default if the value's type doesn't match.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>);
/// Hands the value back if it has another type.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) -> Result<(), Box<dyn AnyAttributeValue>>;
/// Creates a new attribute of the same type filled with `count` number of default values.
fn new_with_defaults(&self, count: usize) -> Arc<dyn AnyAttribute>;
@@ -423,8 +430,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
self.len() == 0
}
/// Appends all values from another attribute of the same type.
fn extend(&mut self, other: Arc<dyn AnyAttribute>);
/// Appends all values from another attribute of the same type, or defaults for them if it has another type, which returns `false` unless it is empty.
fn extend(&mut self, other: Arc<dyn AnyAttribute>) -> bool;
/// Returns a shared reference to the value at the requested index.
fn get_any(&self, index: usize) -> Option<&dyn std::any::Any>;
@@ -444,6 +451,9 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
/// Compares this attribute to another for value-by-value equality (object-safe wrapper around `PartialEq`).
/// Returns `false` if the underlying types differ.
fn eq_dyn(&self, other: &dyn AnyAttribute) -> bool;
/// The type of this attribute's values.
fn value_type(&self) -> TypeDescriptor;
}
/// Adapts a `&mut dyn Hasher` so generic `CacheHash::cache_hash<H>` calls (which require `H: Sized + Hasher`) can
@@ -542,9 +552,11 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
/// Pushes an attribute value onto the end of this attribute's list, downcasting it to `T`.
/// Falls back to a default value if the type doesn't match, to maintain the attribute-length invariant.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) {
let value = value.into_any_arc().downcast::<T>().map(Arc::unwrap_or_clone).unwrap_or_default();
self.0.push(value);
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) -> bool {
let value = value.into_any_arc().downcast::<T>().map(Arc::unwrap_or_clone);
let matches = value.is_ok();
self.0.push(value.unwrap_or_default());
matches
}
/// Pushes a default `T` value onto the end of this attribute list.
@@ -559,8 +571,11 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
}
/// Sets the value at the given index, padding with defaults if the attribute is shorter than `index`.
/// Falls back to a default if the value's type doesn't match.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) {
/// Hands the value back if it isn't a `T`.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) -> Result<(), Box<dyn AnyAttributeValue>> {
if !value.as_any().is::<T>() {
return Err(value);
}
while self.0.len() < index {
self.0.push(T::default());
}
@@ -570,6 +585,7 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
} else {
self.0[index] = value;
}
Ok(())
}
/// Creates a new attribute filled with `count` default `T` values.
@@ -585,14 +601,18 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
/// Appends all values from another attribute, downcasting it to the same `Attribute<T>` type.
/// Falls back to padding with defaults if the type doesn't match, to maintain the attribute-length invariant.
fn extend(&mut self, other: Arc<dyn AnyAttribute>) {
fn extend(&mut self, other: Arc<dyn AnyAttribute>) -> bool {
let other_len = other.len();
match other.into_any_arc().downcast::<Self>().map(Arc::try_unwrap) {
Ok(Ok(other)) => self.0.extend(other.0),
Ok(Err(shared)) => self.0.extend_from_slice(&shared.0),
Err(_) => self.0.extend(std::iter::repeat_with(T::default).take(other_len)),
Err(_) => {
self.0.extend(std::iter::repeat_with(T::default).take(other_len));
return other_len == 0;
}
}
true
}
/// Returns a shared reference to the value at the given index as a type-erased `Any`.
@@ -629,6 +649,10 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
fn eq_dyn(&self, other: &dyn AnyAttribute) -> bool {
other.as_any().downcast_ref::<Self>().is_some_and(|other| self.0 == other.0)
}
fn value_type(&self) -> TypeDescriptor {
crate::descriptor!(T)
}
}
// ==================
@@ -700,6 +724,11 @@ impl ListDyn {
pub fn attribute<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
self.attributes.get_value(key, index)
}
/// Returns the type of the values the attribute for the given key holds, or `None` if absent.
pub fn attribute_type(&self, key: &str) -> Option<TypeDescriptor> {
self.attributes.value_type(key)
}
}
impl<T> From<List<T>> for ListDyn {
@@ -1081,23 +1110,31 @@ impl Attributes {
/// Pushes an item's scalar attributes into this attribute store.
/// Existing attributes that the item lacks receive a default value.
/// New attribute keys create a new attribute padded with defaults for all prior items.
fn push_item(&mut self, item: ItemAttributeValues) {
/// Returns the first attribute that holds another type than the item's value for it, which gets the default instead.
fn push_item(&mut self, item: ItemAttributeValues) -> Option<AttributeTypeConflictError> {
let len = self.len;
self.len += 1;
if self.attributes.is_empty() && item.0.is_none() {
return;
return None;
}
let mut item_entries = item.into_entries();
let mut conflict = None;
// Push values into existing attributes, or the implicit default if the item lacks that attribute
for (attribute_key, attribute) in self.attributes.as_mut_slice() {
let attribute = unshared(attribute);
match item_entries.iter().position(|(key, _)| key == attribute_key) {
Some(position) => attribute.push(item_entries.swap_remove(position).1),
None => pad_with_implicit_default(attribute_key.as_str(), attribute, 1),
// An attribute without values holds no type to keep
Some(position) if len == 0 => *attribute = item_entries.swap_remove(position).1.into_attribute(attribute_key.as_str(), 0),
Some(position) => {
if !unshared(attribute).push(item_entries.swap_remove(position).1) {
conflict.get_or_insert_with(|| AttributeTypeConflictError {
name: attribute_key.as_str().to_string(),
});
}
}
None => pad_with_implicit_default(attribute_key.as_str(), unshared(attribute), 1),
}
}
@@ -1106,33 +1143,41 @@ impl Attributes {
let attribute = value.into_attribute(key.as_str(), len);
self.attributes.push((key, attribute));
}
conflict
}
/// Appends all attribute data from another attribute store into this one.
/// Attributes present in only one side are padded with defaults for the other side's items.
fn extend(&mut self, other: Attributes) {
/// Returns the first attribute both stores hold with values of different types, where the other store's items get the default.
fn extend(&mut self, other: Attributes) -> Option<AttributeTypeConflictError> {
let (len, other_len) = (self.len, other.len);
self.len += other_len;
// An empty store takes on the other's attributes whole, sharing them
if len == 0 && self.entries().is_empty() {
self.attributes = other.attributes;
return;
return None;
}
// Nothing to add or pad, so self's attributes can stay shared
if other.attributes.is_empty() && (other_len == 0 || self.attributes.is_empty()) {
return;
return None;
}
let mut other_entries = other.attributes.into_vec();
let mut conflict = None;
// Extend matching attributes, or pad self's attributes with implicit defaults for the other's item count
for (key, self_attribute) in self.attributes.as_mut_slice() {
let self_attribute = unshared(self_attribute);
match other_entries.iter().position(|(other_key, _)| other_key == key) {
Some(position) => self_attribute.extend(other_entries.swap_remove(position).1),
None => pad_with_implicit_default(key.as_str(), self_attribute, other_len),
// An attribute without values holds no type to keep
Some(position) if len == 0 => *self_attribute = other_entries.swap_remove(position).1,
Some(position) => {
if !unshared(self_attribute).extend(other_entries.swap_remove(position).1) {
conflict.get_or_insert_with(|| AttributeTypeConflictError { name: key.as_str().to_string() });
}
}
None => pad_with_implicit_default(key.as_str(), unshared(self_attribute), other_len),
}
}
@@ -1145,6 +1190,13 @@ impl Attributes {
self.attributes.push((key, combined));
}
conflict
}
/// The type of the values the attribute for the given key holds, if present.
fn value_type(&self, key: &str) -> Option<TypeDescriptor> {
self.entries().iter().find(|(k, _)| k.is(key)).map(|(_, attribute)| attribute.value_type())
}
/// Gets a reference to the value at the given index from the attribute for the given key.
@@ -1221,18 +1273,24 @@ impl Attributes {
}
/// Sets a single type-erased value at the given index of a list of `item_count` items, creating the attribute from the
/// value's type if the key holds none.
fn set_value_dyn(&mut self, key: &str, index: usize, value: Box<dyn AnyAttributeValue>, item_count: usize) {
let position = self.position(key);
if let Some((_, attribute)) = position.and_then(|position| self.attributes.as_mut_slice().get_mut(position)) {
unshared(attribute).set_at(index, value);
} else {
let mut new_attribute = Arc::<dyn AnyAttributeValue>::from(value).into_attribute(key, index);
let trailing_defaults = item_count.saturating_sub(new_attribute.len());
pad_with_implicit_default(key, unshared(&mut new_attribute), trailing_defaults);
self.attributes.push((AttributeKey::new(key), new_attribute));
/// value's type if the key holds none. An attribute of another type is replaced, padded with implicit defaults.
fn set_value_dyn(&mut self, key: &str, index: usize, mut value: Box<dyn AnyAttributeValue>, item_count: usize) {
if let Some(position) = self.position(key)
&& let Some((_, attribute)) = self.attributes.as_mut_slice().get_mut(position)
{
match unshared(attribute).set_at(index, value) {
Ok(()) => return,
Err(mistyped) => {
self.attributes.remove(position);
value = mistyped;
}
}
}
let mut new_attribute = Arc::<dyn AnyAttributeValue>::from(value).into_attribute(key, index);
let trailing_defaults = item_count.saturating_sub(new_attribute.len());
pad_with_implicit_default(key, unshared(&mut new_attribute), trailing_defaults);
self.attributes.push((AttributeKey::new(key), new_attribute));
}
/// Returns a debug-formatted string for the value at the given index in the attribute for the given key.
@@ -1327,6 +1385,12 @@ impl Attributes {
}
}
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("The \"{name}\" attribute holds different types of values in the lists being combined")]
pub struct AttributeTypeConflictError {
pub name: String,
}
// =======
// List<T>
// =======
@@ -1488,7 +1552,7 @@ impl<T> List<T> {
}
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
/// Falls back to default if the value's type doesn't match an existing attribute.
/// An existing attribute of another type is replaced the same way.
pub fn set_attribute_value_dyn(&mut self, key: impl AsRef<str>, index: usize, value: AttributeValueDyn) {
self.attributes.set_value_dyn(key.as_ref(), index, value.0, self.element.len());
}
@@ -1545,14 +1609,16 @@ impl<T: Clone> List<T> {
Arc::make_mut(&mut self.element)
}
/// Appends an item to the end of this list.
pub fn push(&mut self, item: Item<T>) {
/// Appends an item to the end of this list, returning the first attribute the list holds with another type than the item's value for it.
/// The list keeps its type for it, giving the item its default.
pub fn push(&mut self, item: Item<T>) -> Option<AttributeTypeConflictError> {
self.elements_mut().push(item.element);
self.attributes.push_item(item.attributes);
self.attributes.push_item(item.attributes)
}
/// Appends all items from another list into this one.
pub fn extend(&mut self, list: List<T>) {
/// Appends all items from another list into this one, returning the first attribute both lists have with values of different types.
/// This list keeps its type for it, giving the other list's items its default.
pub fn extend(&mut self, list: List<T>) -> Option<AttributeTypeConflictError> {
// An empty list adopts the other's elements without copying them
if self.element.is_empty() {
self.element = list.element;
@@ -1563,7 +1629,7 @@ impl<T: Clone> List<T> {
Err(shared) => elements.extend_from_slice(&shared),
}
}
self.attributes.extend(list.attributes);
self.attributes.extend(list.attributes)
}
/// Returns an iterator over mutable references to all element values.
@@ -2179,6 +2245,78 @@ mod tests {
assert_eq!(starts(&rebuilt), [11, 21, 10, 20, 0]);
}
// Combining lists keeps only the first type of an attribute both have, and reports the attribute whose values were lost
#[test]
fn combining_lists_reports_attribute_type_conflicts() {
let mut base = List::new_from_elements(vec![1_u32, 2]);
base.set_attribute_values(ATTR_START, vec![10_u64, 20]);
base.set_attribute_values(ATTR_NAME, vec![String::from("a"), String::from("b")]);
let mut matching = List::new_from_elements(vec![3_u32]);
matching.set_attribute_values(ATTR_START, vec![30_u64]);
matching.set_attribute_values(ATTR_END, vec![1.5_f64]);
assert_eq!(base.extend(matching), None);
let mut empty = List::new();
empty.set_attribute_values(ATTR_NAME, Vec::<i64>::new());
assert_eq!(base.extend(empty), None, "an empty list loses no values");
let mut mistyped = List::new_from_elements(vec![4_u32]);
mistyped.set_attribute_values(ATTR_NAME, vec![7_i64]);
let conflict = AttributeTypeConflictError { name: ATTR_NAME.to_string() };
assert_eq!(base.extend(mistyped), Some(conflict.clone()));
assert_eq!(conflict.to_string(), "The \"name\" attribute holds different types of values in the lists being combined");
assert_eq!(base.attribute::<String>(ATTR_NAME, 3), Some(&String::new()));
assert_eq!(base.push(Item::new_from_element(5).with_attribute(ATTR_START, 50_u64)), None);
let mistyped_item = Item::new_from_element(6).with_attribute(ATTR_START, 60_f64);
assert_eq!(base.push(mistyped_item), Some(AttributeTypeConflictError { name: ATTR_START.to_string() }));
assert_eq!(base.attribute::<u64>(ATTR_START, 5), Some(&0));
}
#[test]
fn an_attribute_without_values_takes_the_type_of_the_values_added_to_it() {
let mut mistyped = List::new_from_elements(vec![1_u32]);
mistyped.set_attribute_values(ATTR_NAME, vec![7_i64]);
let mut extended = List::<u32>::new();
extended.set_attribute_values(ATTR_NAME, Vec::<String>::new());
assert_eq!(extended.extend(mistyped), None);
assert_eq!(extended.attribute::<i64>(ATTR_NAME, 0), Some(&7));
let mut pushed = List::<u32>::new();
pushed.set_attribute_values(ATTR_NAME, Vec::<String>::new());
assert_eq!(pushed.push(Item::new_from_element(1).with_attribute(ATTR_NAME, 7_i64)), None);
assert_eq!(pushed.attribute::<i64>(ATTR_NAME, 0), Some(&7));
}
// An attribute's type reads back from a list's type-erased view, and a missing value reads as what padding fills in
#[test]
fn attribute_types_and_implicit_defaults_read_back() {
let mut list = List::new_from_elements(vec![1_u32]);
list.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
let list = ListDyn::from(list);
assert_eq!(list.attribute_type(ATTR_OPACITY), Some(crate::descriptor!(f64)));
assert_eq!(list.attribute_type(ATTR_OPACITY).map(|value_type| value_type.to_string()), Some("Number".to_string()));
assert_eq!(list.attribute_type(ATTR_START), None);
assert_eq!(implicit_default::<f64>(ATTR_OPACITY), 1.);
assert_eq!(implicit_default::<f64>(ATTR_START), 0.);
assert_eq!(implicit_default::<i64>(ATTR_OPACITY), 0);
}
// A type-erased value of another type replaces the attribute, as a typed one does, instead of becoming the old type's default
#[test]
fn setting_a_value_of_another_type_replaces_the_attribute() {
let mut list = List::new_from_elements(vec![1_u32, 2]);
list.set_attribute_values(ATTR_OPACITY, vec![0.5_f64, 0.25]);
list.set_attribute_value_dyn(ATTR_OPACITY, 1, AttributeValueDyn(Box::new(3_i64)));
assert_eq!(list.iter_attribute_values::<i64>(ATTR_OPACITY).map(|values| values.copied().collect::<Vec<_>>()), Some(vec![0, 3]));
list.set_attribute_value_dyn(ATTR_OPACITY, 0, AttributeValueDyn(Box::new(0.75_f64)));
assert_eq!(list.iter_attribute_values::<f64>(ATTR_OPACITY).map(|values| values.copied().collect::<Vec<_>>()), Some(vec![0.75, 1.]));
}
// Keys are stored inline up to a length limit and shared beyond it, which reads the same either way
#[test]
fn attribute_keys_of_any_length_read_back() {
+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<crate::color::Color, D::Error> {
use crate::color::Color;
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;
use serde::Deserialize;
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
@@ -121,7 +121,7 @@ impl TransferCurveEvaluator {
}
// O(log n) search for the segment holding x
let upper = points.partition_point(|point| point.x <= x).min(points.len() - 1);
let upper = points.partition_point(|point| point.x <= x).clamp(1, points.len() - 1);
let lower = upper - 1;
let (a, b) = (points[lower], points[upper]);
let width = (b.x - a.x).max(f64::EPSILON);
@@ -206,6 +206,17 @@ mod tests {
}
}
#[test]
fn sampling_survives_a_value_or_point_that_is_not_a_number() {
assert!(TransferCurve::default().evaluate(f64::NAN).is_nan());
// A negative NaN sorts first, so every x between the points meets it
let curve = TransferCurve::new(vec![DVec2::new(-f64::NAN, 0.), DVec2::new(0.5, 0.7), DVec2::ONE]);
for x in (1..100).map(|i| i as f64 / 100.) {
curve.evaluate(x);
}
}
#[test]
fn a_moved_point_may_pass_another_while_keeping_its_index() {
let mut curve = TransferCurve::default();
@@ -179,8 +179,6 @@ 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)),
@@ -191,6 +189,10 @@ impl Footprint {
};
pub fn viewport_bounds_in_local_space(&self) -> AxisAlignedBbox {
if self.transform.matrix2.determinant() == 0. {
return AxisAlignedBbox::ZERO;
}
let inverse = self.transform.inverse();
let res = self.resolution.as_dvec2();
let c0 = inverse.transform_point2(DVec2::ZERO);
@@ -203,61 +205,6 @@ 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()
}
@@ -310,59 +257,3 @@ 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));
}
}
@@ -15,9 +15,11 @@ publish.workspace = true
workspace = true
[features]
default = ["std"]
std = ["dep:kurbo"]
derive = ["graphene-hash-derive"]
[dependencies]
graphene-hash-derive = { path = "derive", optional = true }
glam = { workspace = true }
kurbo = { workspace = true }
kurbo = { workspace = true, optional = true }
@@ -1,3 +1,8 @@
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "derive")]
pub use graphene_hash_derive::CacheHash;
@@ -61,6 +66,7 @@ impl_via_hash! {
glam::BVec2, glam::BVec3, glam::BVec4,
}
#[cfg(feature = "std")]
impl_via_hash! {
String,
}
@@ -148,6 +154,7 @@ impl_glam_array! {
}
// kurbo path types: hash each element's verb and point coordinates via to_bits().
#[cfg(feature = "std")]
impl CacheHash for kurbo::Point {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -156,6 +163,7 @@ impl CacheHash for kurbo::Point {
}
}
#[cfg(feature = "std")]
impl CacheHash for kurbo::PathEl {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(&core::mem::discriminant(self), state);
@@ -175,6 +183,7 @@ impl CacheHash for kurbo::PathEl {
}
}
#[cfg(feature = "std")]
impl CacheHash for kurbo::BezPath {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -215,6 +224,7 @@ impl<T: CacheHash, const N: usize> CacheHash for [T; N] {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash> CacheHash for Vec<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -222,6 +232,7 @@ impl<T: CacheHash> CacheHash for Vec<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -232,6 +243,7 @@ impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -239,6 +251,7 @@ impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash + ?Sized> CacheHash for std::sync::Arc<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -232,7 +232,9 @@ impl Appearance {
let row = cover_row(coverage, paint);
match placement {
CoverPlacement::Above => self.0.push(row),
CoverPlacement::Above => {
self.0.push(row);
}
CoverPlacement::Below => {
let mut reordered = List::new_from_item(row);
reordered.extend(std::mem::take(&mut self.0));
@@ -2,7 +2,7 @@ use crate::appearance::{Appearance, Cover, Coverage};
use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, Item, ItemAttributeValues, List, NodeIdPath};
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, AttributeTypeConflictError, Item, ItemAttributeValues, List, NodeIdPath};
use core_types::math::quad::Quad;
use core_types::none;
use core_types::ops::FromAnchorPosition;
@@ -180,15 +180,16 @@ pub fn is_lone_anonymous_leaf(content: &List<Graphic>) -> bool {
/// Deeply flattens a `List<Graphic>`, collecting only elements matching a specific variant (extracted by `extract_variant`)
/// and discarding all other non-matching content. Recursion through `Graphic::GraphicList` sub-`List`s composes transforms and opacity.
fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> List<T> {
/// Also gives the first attribute that the flattened lists have with values of different types.
fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> (List<T>, Option<AttributeTypeConflictError>) {
// Its list is already the flat answer, so hand it back rather than rebuilding it item by item
if is_lone_anonymous_leaf(&content) {
let Some(item) = content.into_iter().next() else { return List::new() };
let Some(item) = content.into_iter().next() else { return (List::new(), None) };
return extract_variant(item.into_element()).unwrap_or_default();
return (extract_variant(item.into_element()).unwrap_or_default(), None);
}
fn flatten_recursive<T: Clone>(output: &mut List<T>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) {
fn flatten_recursive<T: Clone>(output: &mut List<T>, conflict: &mut Option<AttributeTypeConflictError>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) {
for current_graphic_item in current_graphic_list.into_iter() {
// Whether the parent carries each composed attribute: a structural fact (attribute presence), never a value comparison.
// Flattening composes a parent attribute onto its children only when the parent has it,
@@ -244,7 +245,7 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
}
}
flatten_recursive(output, sub_list, extract_variant);
flatten_recursive(output, conflict, sub_list, extract_variant);
}
// Extract the target variant and push its items, composing the parent's attributes onto each
other => {
@@ -273,7 +274,9 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
item.set_attribute(ATTR_APPEARANCE, appearance.clone());
}
output.push(item);
if let Some(item_conflict) = output.push(item) {
conflict.get_or_insert(item_conflict);
}
}
}
}
@@ -282,8 +285,9 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
}
let mut output = List::new();
flatten_recursive(&mut output, content, extract_variant);
output
let mut conflict = None;
flatten_recursive(&mut output, &mut conflict, content, extract_variant);
(output, conflict)
}
/// Whether a normalized paint graphic list actually carries renderable paint.
@@ -360,16 +364,6 @@ 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 {
@@ -415,7 +409,19 @@ pub trait IntoGraphicList: Clone + Send + Sync + Default + std::fmt::Debug + Par
where
Self: std::marker::Sized,
{
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic)
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic).0
}
/// Deeply flattens any content of type `T`, failing with the flattened list and the first attribute that holds values of different
/// types in the flattened lists (their later items hold the first type's default).
fn try_into_flattened_list<T: TryFromGraphic>(self) -> Result<List<T>, (List<T>, AttributeTypeConflictError)>
where
Self: std::marker::Sized,
{
match flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic) {
(list, None) => Ok(list),
(list, Some(conflict)) => Err((list, conflict)),
}
}
}
@@ -1059,6 +1065,27 @@ mod tests {
assert_eq!(color_of(1), Some(Color::WHITE), "a padded item should inherit the parent appearance");
}
// Flattening lists that hold an attribute with different types keeps the first type, and says which attribute lost values
#[test]
fn flatten_reports_an_attribute_holding_different_types() {
let tagged = |value: Item<Vector>| Item::new_from_element(Graphic::VectorList(List::new_from_item(value)));
let mut graphics = List::new();
graphics.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 1_f64)));
graphics.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", String::from("two"))));
let Err((flattened, conflict)) = graphics.clone().try_into_flattened_list::<Vector>() else {
panic!("expected the conflicting tag to be reported")
};
assert_eq!(conflict.name, "tag");
assert_eq!(flattened, graphics.clone().into_flattened_list::<Vector>());
assert_eq!(flattened.attribute::<f64>("tag", 1), Some(&0.));
let mut matching = List::new();
matching.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 1_f64)));
matching.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 2_f64)));
assert!(matching.try_into_flattened_list::<Vector>().is_ok());
}
#[test]
fn embedded_item_keeps_its_attributes_inside_the_variant() {
let color = Item::new_from_element(Color::RED).with_attribute(ATTR_POSITION, 0.25_f64);
@@ -0,0 +1,70 @@
[package]
name = "no-std-types"
description = "no_std types for Graphene (shader-compatible)"
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]
# any feature that
# * must be usable in shaders
# * but requires std
# * and should be on by default
# should be in this list instead of `[workspace.dependency]`
std = [
"dep:dyn-any",
"dep:graphene-hash",
"dep:serde",
"dep:log",
"glam/debug-glam-assert",
"glam/std",
"glam/serde",
"half/std",
"half/serde",
"num-traits/std",
"num_enum/std",
]
wasm = ["tsify", "wasm-bindgen"]
[dependencies]
# Local dependencies
node-macro = { workspace = true }
# Local std dependencies
dyn-any = { workspace = true, optional = true }
graphene-hash = { workspace = true, optional = true }
# Workspace dependencies
bytemuck = { workspace = true }
glam = { workspace = true }
half = { workspace = true, default-features = false }
num-derive = { workspace = true }
num-traits = { workspace = true }
num_enum = { workspace = true }
spirv-std = { workspace = true }
# Workspace std dependencies
serde = { workspace = true, optional = true }
log = { workspace = true, optional = true }
# Workspace wasm dependencies
tsify = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
[dev-dependencies]
core-types = { workspace = true }
[lints.rust]
# the spirv target is not in the list of common cfgs so must be added manually
unexpected_cfgs = { level = "warn", check-cfg = [
'cfg(target_arch, values("spirv"))',
] }
[package.metadata.cargo-shear]
ignored = ["core-types"]
@@ -1,11 +1,13 @@
use crate::color::Color;
use core::fmt::Display;
use node_macro::BufferStruct;
use num_enum::{FromPrimitive, IntoPrimitive};
#[repr(i32)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[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))]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "std", derive(graphene_hash::CacheHash))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, BufferStruct, FromPrimitive, IntoPrimitive)]
pub enum BlendMode {
// Basic group
#[default]
@@ -130,6 +132,7 @@ impl BlendMode {
}
/// Renders the blend mode CSS style declaration.
#[cfg(feature = "std")]
pub fn render(&self) -> String {
format!(
r#" mix-blend-mode: {};"#,
@@ -3,6 +3,8 @@ use bytemuck::{Pod, Zeroable};
use core::fmt::Debug;
use glam::DVec2;
use num_derive::*;
#[cfg(not(feature = "std"))]
use num_traits::float::Float;
pub trait Linear {
fn from_f32(x: f32) -> Self;
@@ -86,6 +88,7 @@ pub trait SRGB: Rec709Primaries {}
// TODO: Come up with a better name for this trait
pub trait Pixel: Clone + Pod + Zeroable + Default {
#[cfg(feature = "std")]
fn to_bytes(&self) -> Vec<u8> {
bytemuck::bytes_of(self).to_vec()
}
@@ -5,10 +5,16 @@ use bytemuck::{Pod, Zeroable};
use core::fmt::Debug;
use glam::Vec4;
use half::f16;
use node_macro::BufferStruct;
#[cfg(not(feature = "std"))]
use num_traits::Euclid;
#[cfg(not(feature = "std"))]
use num_traits::float::Float;
#[repr(C)]
#[derive(Default, Clone, Copy, PartialEq, Pod, Zeroable, Debug, dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Default, Clone, Copy, PartialEq, Pod, Zeroable)]
#[cfg_attr(not(target_arch = "spirv"), derive(Debug))]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, serde::Serialize, serde::Deserialize))]
pub struct RGBA16F {
red: f16,
green: f16,
@@ -16,6 +22,14 @@ pub struct RGBA16F {
alpha: f16,
}
/// hack around half still masking out impl Debug for f16 on spirv
#[cfg(target_arch = "spirv")]
impl core::fmt::Debug for RGBA16F {
fn fmt(&self, _f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
Ok(())
}
}
impl From<Color> for RGBA16F {
#[inline(always)]
fn from(c: Color) -> Self {
@@ -82,8 +96,9 @@ 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(dyn_any::DynAny, graphene_hash::CacheHash, Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Pod, Zeroable)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "std", derive(graphene_hash::CacheHash))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Pod, Zeroable)]
pub struct SRGBA8 {
pub red: u8,
pub green: u8,
@@ -110,6 +125,7 @@ impl SRGBA8 {
/// Parse `RRGGBB` or `RRGGBBAA` (with or without a leading `#`). Returns `None` for any other format.
/// For full CSS Color 4 parsing (named colors, shorthand hex, `rgb(...)`, `hsl(...)`), parse in the caller and construct via [`Self::new`].
#[cfg(feature = "std")]
pub fn from_hex_str(hex: &str) -> Option<Self> {
let hex = hex.trim().trim_start_matches('#');
if hex.len() != 6 && hex.len() != 8 {
@@ -125,16 +141,19 @@ impl SRGBA8 {
}
/// `rrggbb` (lowercase, no `#` prefix, alpha discarded). Use where alpha is specified separately, e.g. SVG `fill="#..." fill-opacity="..."`.
#[cfg(feature = "std")]
pub fn to_rgb_hex(self) -> String {
format!("{:02x}{:02x}{:02x}", self.red, self.green, self.blue)
}
/// `rrggbbaa` (lowercase, no `#` prefix).
#[cfg(feature = "std")]
pub fn to_rgba_hex(self) -> String {
format!("{:02x}{:02x}{:02x}{:02x}", self.red, self.green, self.blue, self.alpha)
}
/// `#rrggbb` if fully opaque, `#rrggbbaa` otherwise. Suitable for direct insertion into a CSS property or SVG attribute.
#[cfg(feature = "std")]
pub fn to_css_hex(self) -> String {
if self.alpha == 255 {
format!("#{}", self.to_rgb_hex())
@@ -204,8 +223,8 @@ impl From<SRGBA8> for Color {
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny, Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, serde::Serialize, serde::Deserialize))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable)]
pub struct Luma(pub f32);
impl Luminance for Luma {
@@ -240,7 +259,9 @@ impl Pixel for Luma {}
///
/// Anything crossing the Wasm/JS boundary must go through [`SRGBA8`] instead.
#[repr(C)]
#[derive(dyn_any::DynAny, graphene_hash::CacheHash, Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny))]
#[cfg_attr(feature = "std", derive(graphene_hash::CacheHash))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable, BufferStruct)]
pub struct Color {
red: f32,
green: f32,
@@ -252,7 +273,7 @@ pub struct Color {
impl Eq for Color {}
// TODO: Eventually remove this document upgrade code
#[cfg(feature = "serde")]
#[cfg(feature = "std")]
impl serde::Serialize for Color {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
@@ -269,7 +290,7 @@ impl serde::Serialize for Color {
}
// TODO: Eventually remove this document upgrade code
#[cfg(feature = "serde")]
#[cfg(feature = "std")]
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.
@@ -330,6 +351,7 @@ impl AlphaMut for Color {
}
impl Pixel for Color {
#[cfg(feature = "std")]
fn to_bytes(&self) -> Vec<u8> {
let SRGBA8 { red, green, blue, alpha } = (*self).into();
[red, green, blue, alpha].to_vec()
@@ -422,7 +444,10 @@ impl Color {
lightness + saturation - lightness * saturation
};
let temp2 = 2. * lightness - temp1;
#[cfg(feature = "std")]
let rem = |x: f32| x.rem_euclid(1.);
#[cfg(not(feature = "std"))]
let rem = |x: f32| x.rem_euclid(&1.);
let mut red = rem(hue + 1. / 3.);
let mut green = rem(hue);
@@ -798,7 +823,10 @@ impl Color {
/// Convert this color to HSV coordinates (all between 0 and 1).
/// HSV is defined on sRGB display values, so this color's linear RGB is gamma-encoded before the HSV math.
pub fn to_hsva(&self) -> [f32; 4] {
#[cfg(feature = "std")]
let rem = |x: f32, m: f32| x.rem_euclid(m);
#[cfg(not(feature = "std"))]
let rem = |x: f32, m: f32| x.rem_euclid(&m);
let [red, green, blue, alpha] = self.to_gamma_srgb_channels();
let max = red.max(green).max(blue);
@@ -845,7 +873,10 @@ impl Color {
} else {
4. + (red - green) / (max_channel - min_channel)
} / 6.;
#[cfg(feature = "std")]
let hue = hue.rem_euclid(1.);
#[cfg(not(feature = "std"))]
let hue = hue.rem_euclid(&1.);
[hue, saturation, lightness, alpha]
}
@@ -3,6 +3,9 @@
//! These work in `f32` at full precision. For round-trip-exact `u8` ⇄ `f32` conversion at the
//! display byte boundary, use the lookup tables in [`super::discrete_srgb`] instead.
#[cfg(not(feature = "std"))]
use num_traits::float::Float;
/// Decode an sRGB gamma-encoded channel value to linear-light.
#[inline(always)]
pub fn srgb_to_linear(channel: f32) -> f32 {
@@ -0,0 +1,9 @@
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 {}
#[cfg(feature = "std")]
impl<T: ArcCtx> Ctx for std::sync::Arc<T> {}
@@ -0,0 +1,20 @@
#![cfg_attr(not(feature = "std"), no_std)]
pub mod blending;
pub mod choice_type;
pub mod color;
pub mod context;
pub mod list;
pub mod shaders;
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,41 @@
//! A zero-cost stand-in for `core_types::list::Item` used when node kernels are compiled for the GPU.
//!
//! Shader node kernels compile twice: under `std` against the real attribute-carrying `Item`, and under
//! `no_std` (SPIR-V) against this transparent wrapper, imported as `Item`. Only the element-access surface is
//! provided, since rust-gpu cannot allocate and attributes have no per-pixel meaning; attribute use fails the
//! shader build. It is named distinctly from `Item` so a search for the canonical type finds only that one.
/// A rank-0 wire value holding a single element, mirroring the element-access API of the real `Item`.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct ShaderItem<T> {
element: T,
}
impl<T> ShaderItem<T> {
/// Constructs an item with the given element.
pub fn new_from_element(element: T) -> Self {
Self { element }
}
/// Returns a shared reference to this item's element.
pub fn element(&self) -> &T {
&self.element
}
/// Returns a mutable reference to this item's element.
pub fn element_mut(&mut self) -> &mut T {
&mut self.element
}
/// Consumes this item and returns the owned element.
pub fn into_element(self) -> T {
self.element
}
}
impl<T> From<T> for ShaderItem<T> {
fn from(element: T) -> Self {
Self::new_from_element(element)
}
}
@@ -0,0 +1,112 @@
use crate::shaders::buffer_struct::BufferStruct;
macro_rules! glam_array {
($t:ty, $a:ty) => {
unsafe impl BufferStruct for $t {
type Buffer = $a;
#[inline]
fn write(from: Self) -> Self::Buffer {
<$t>::to_array(&from)
}
#[inline]
fn read(from: Self::Buffer) -> Self {
<$t>::from_array(from)
}
}
};
}
macro_rules! glam_cols_array {
($t:ty, $a:ty) => {
unsafe impl BufferStruct for $t {
type Buffer = $a;
#[inline]
fn write(from: Self) -> Self::Buffer {
<$t>::to_cols_array(&from)
}
#[inline]
fn read(from: Self::Buffer) -> Self {
<$t>::from_cols_array(&from)
}
}
};
}
glam_array!(glam::Vec2, [f32; 2]);
glam_array!(glam::Vec3, [f32; 3]);
// glam_array!(Vec3A, [f32; 4]);
glam_array!(glam::Vec4, [f32; 4]);
glam_cols_array!(glam::Mat2, [f32; 4]);
glam_cols_array!(glam::Mat3, [f32; 9]);
// glam_cols_array!(Mat3A, [f32; 4]);
glam_cols_array!(glam::Mat4, [f32; 16]);
glam_cols_array!(glam::Affine2, [f32; 6]);
glam_cols_array!(glam::Affine3A, [f32; 12]);
glam_array!(glam::DVec2, [f64; 2]);
glam_array!(glam::DVec3, [f64; 3]);
glam_array!(glam::DVec4, [f64; 4]);
glam_cols_array!(glam::DMat2, [f64; 4]);
glam_cols_array!(glam::DMat3, [f64; 9]);
glam_cols_array!(glam::DMat4, [f64; 16]);
glam_cols_array!(glam::DAffine2, [f64; 6]);
glam_cols_array!(glam::DAffine3, [f64; 12]);
glam_array!(glam::I16Vec2, [i16; 2]);
glam_array!(glam::I16Vec3, [i16; 3]);
glam_array!(glam::I16Vec4, [i16; 4]);
glam_array!(glam::U16Vec2, [u16; 2]);
glam_array!(glam::U16Vec3, [u16; 3]);
glam_array!(glam::U16Vec4, [u16; 4]);
glam_array!(glam::IVec2, [i32; 2]);
glam_array!(glam::IVec3, [i32; 3]);
glam_array!(glam::IVec4, [i32; 4]);
glam_array!(glam::UVec2, [u32; 2]);
glam_array!(glam::UVec3, [u32; 3]);
glam_array!(glam::UVec4, [u32; 4]);
glam_array!(glam::I64Vec2, [i64; 2]);
glam_array!(glam::I64Vec3, [i64; 3]);
glam_array!(glam::I64Vec4, [i64; 4]);
glam_array!(glam::U64Vec2, [u64; 2]);
glam_array!(glam::U64Vec3, [u64; 3]);
glam_array!(glam::U64Vec4, [u64; 4]);
unsafe impl BufferStruct for glam::Vec3A {
type Buffer = [f32; 4];
#[inline]
fn write(from: Self) -> Self::Buffer {
glam::Vec4::to_array(&from.extend(0.))
}
#[inline]
fn read(from: Self::Buffer) -> Self {
glam::Vec3A::from_vec4(glam::Vec4::from_array(from))
}
}
/// do NOT use slices, otherwise spirv will fail to compile
unsafe impl BufferStruct for glam::Mat3A {
type Buffer = [f32; 12];
#[inline]
fn write(from: Self) -> Self::Buffer {
let a = from.to_cols_array();
[a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], 0., 0., 0.]
}
#[inline]
fn read(from: Self::Buffer) -> Self {
let a = from;
glam::Mat3A::from_cols_array(&[a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]])
}
}
@@ -0,0 +1,63 @@
//! I (@firestar99) copied this entire mod from one of my projects, as I haven't uploaded that lib to crates. Hopefully
//! rust-gpu improves and this entire thing becomes unnecessary in the future.
//!
//! https://github.com/Firestar99/nanite-at-home/tree/008dac8df656959c71efeddd2d3ddabcb801771c/rust-gpu-bindless/crates/buffer-content
use bytemuck::Pod;
mod glam;
mod primitive;
/// A BufferStruct is a "parallel representation" of the original struct with some fundamental types remapped. This
/// struct hierarchy represents how data is stored in GPU Buffers, where all types must be [`Pod`] to allow
/// transmuting them to `&[u8]` with [`bytemuck`].
///
/// Notable type remappings (original: buffer):
/// * bool: u32 of 0 or 1
/// * any repr(u32) enum: u32 with remapping via [`num_enum`]
///
/// By adding `#[derive(ShaderStruct)]` to your struct (or enum), a parallel `{name}Buffer` struct is created with all
/// the members of the original struct, but with their types using the associated remapped types as specified by this
/// trait.
///
/// # Origin
/// I (@firestar99) copied this entire mod from my [Nanite-at-home] project, specifically the [buffer-content] crate
/// and the [buffer_struct] proc macro. The variant here has quite some modifications, to both cleaned up some of the
/// mistakes my implementation has and to customize it a bit for graphite.
///
/// Hopefully rust-gpu improves to the point where this remapping becomes unnecessary.
///
/// [Nanite-at-home]: https://github.com/Firestar99/nanite-at-home
/// [buffer-content]: https://github.com/Firestar99/nanite-at-home/tree/008dac8df656959c71efeddd2d3ddabcb801771c/rust-gpu-bindless/crates/buffer-content
/// [buffer_struct]: https://github.com/Firestar99/nanite-at-home/blob/008dac8df656959c71efeddd2d3ddabcb801771c/rust-gpu-bindless/crates/macros/src/buffer_struct.rs
///
/// # Safety
/// The associated type Transfer must be the same on all targets. Writing followed by reading back a value must result
/// in the same value.
pub unsafe trait BufferStruct: Copy + Send + Sync + 'static {
type Buffer: Pod + Send + Sync;
fn write(from: Self) -> Self::Buffer;
fn read(from: Self::Buffer) -> Self;
}
/// Trait marking all [`BufferStruct`] whose read and write methods are identity. While [`BufferStruct`] only
/// requires `t == read(write(t))`, this trait additionally requires `t == read(t) == write(t)`. As this removes the
/// conversion requirement for writing to or reading from a buffer, one can acquire slices from buffers created of these
/// types.
///
/// Implementing this type is completely safe due to the [`Pod`] requirement.
pub trait BufferStructIdentity: Pod + Send + Sync {}
unsafe impl<T: BufferStructIdentity> BufferStruct for T {
type Buffer = Self;
fn write(from: Self) -> Self::Buffer {
from
}
fn read(from: Self::Buffer) -> Self {
from
}
}
@@ -0,0 +1,134 @@
use crate::shaders::buffer_struct::{BufferStruct, BufferStructIdentity};
use bytemuck::Pod;
use core::marker::PhantomData;
use core::num::Wrapping;
use spirv_std::arch::IndexUnchecked;
macro_rules! identity {
($t:ty) => {
impl BufferStructIdentity for $t {}
};
}
identity!(());
identity!(u8);
identity!(u16);
identity!(u32);
identity!(u64);
identity!(u128);
identity!(usize);
identity!(i8);
identity!(i16);
identity!(i32);
identity!(i64);
identity!(i128);
identity!(isize);
identity!(f32);
identity!(f64);
identity!(spirv_std::memory::Semantics);
identity!(spirv_std::ray_tracing::RayFlags);
identity!(spirv_std::indirect_command::DrawIndirectCommand);
identity!(spirv_std::indirect_command::DrawIndexedIndirectCommand);
identity!(spirv_std::indirect_command::DispatchIndirectCommand);
identity!(spirv_std::indirect_command::DrawMeshTasksIndirectCommandEXT);
identity!(spirv_std::indirect_command::TraceRaysIndirectCommandKHR);
// not pod
// identity!(spirv_std::indirect_command::TraceRaysIndirectCommand2KHR);
unsafe impl BufferStruct for bool {
type Buffer = u32;
#[inline]
fn write(from: Self) -> Self::Buffer {
from as u32
}
#[inline]
fn read(from: Self::Buffer) -> Self {
from != 0
}
}
unsafe impl<T: BufferStruct> BufferStruct for Wrapping<T>
where
// unfortunately has to be Pod, even though AnyBitPattern would be sufficient,
// due to bytemuck doing `impl<T: Pod> AnyBitPattern for T {}`
// see https://github.com/Lokathor/bytemuck/issues/164
T::Buffer: Pod,
{
type Buffer = Wrapping<T::Buffer>;
#[inline]
fn write(from: Self) -> Self::Buffer {
Wrapping(T::write(from.0))
}
#[inline]
fn read(from: Self::Buffer) -> Self {
Wrapping(T::read(from.0))
}
}
unsafe impl<T: BufferStruct + 'static> BufferStruct for PhantomData<T> {
type Buffer = PhantomData<T>;
#[inline]
fn write(_: Self) -> Self::Buffer {
PhantomData {}
}
#[inline]
fn read(_: Self::Buffer) -> Self {
PhantomData {}
}
}
/// Potential problem: you can't impl this for an array of BufferStruct, as it'll conflict with this impl due to the
/// blanket impl on all BufferStructPlain types.
unsafe impl<T: BufferStruct, const N: usize> BufferStruct for [T; N]
where
// rust-gpu does not like `[T; N].map()` nor `core::array::from_fn()` nor transmuting arrays with a const generic
// length, so for now we need to require T: Default and T::Transfer: Default for all arrays.
T: Default,
// unfortunately has to be Pod, even though AnyBitPattern would be sufficient,
// due to bytemuck doing `impl<T: Pod> AnyBitPattern for T {}`
// see https://github.com/Lokathor/bytemuck/issues/164
T::Buffer: Pod + Default,
{
type Buffer = [T::Buffer; N];
#[inline]
fn write(from: Self) -> Self::Buffer {
unsafe {
let mut ret = [T::Buffer::default(); N];
for i in 0..N {
*ret.index_unchecked_mut(i) = T::write(*from.index_unchecked(i));
}
ret
}
}
#[inline]
fn read(from: Self::Buffer) -> Self {
unsafe {
let mut ret = [T::default(); N];
for i in 0..N {
*ret.index_unchecked_mut(i) = T::read(*from.index_unchecked(i));
}
ret
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip_bool() {
for x in [false, true] {
assert_eq!(x, <bool as BufferStruct>::read(<bool as BufferStruct>::write(x)));
}
}
}
@@ -0,0 +1,10 @@
//! supporting infrastructure for shaders
pub mod buffer_struct;
pub mod __private {
pub use bytemuck;
pub use glam;
pub use num_enum;
pub use spirv_std;
}
@@ -33,6 +33,7 @@ base64 = { workspace = true }
bytemuck = { workspace = true }
image = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
+63 -10
View File
@@ -127,6 +127,14 @@ impl<P: core_types::CacheHash + Pixel> core_types::CacheHash for Image<P> {
}
}
#[derive(Debug, thiserror::Error)]
pub enum ImageError {
#[error("The {width}×{height} px image is too large")]
TooLarge { width: u32, height: u32 },
#[error("The file is not an image in a supported format, or it is damaged")]
Undecodable(#[source] ::image::ImageError),
}
impl<P: Pixel> Image<P> {
pub fn new(width: u32, height: u32, color: P) -> Self {
Self {
@@ -135,6 +143,18 @@ impl<P: Pixel> Image<P> {
data: vec![color; (width * height) as usize],
}
}
/// An image filled with `color`, failing where the pixel count overflows the `u32` pixel indices or can't be allocated.
pub fn try_new(width: u32, height: u32, color: P) -> Result<Self, ImageError> {
let too_large = || ImageError::TooLarge { width, height };
let count = width.checked_mul(height).ok_or_else(too_large)? as usize;
let mut data = Vec::new();
data.try_reserve_exact(count).map_err(|_| too_large())?;
data.resize(count, color);
Ok(Self { width, height, data })
}
}
impl Image<Color> {
@@ -144,8 +164,8 @@ impl Image<Color> {
Image { width, height, data }
}
/// Decodes an image file of any supported format.
pub fn from_encoded(data: &[u8]) -> Option<Self> {
/// Decodes an image file of any supported format, or gives the reason it can't be.
pub fn from_encoded(data: &[u8]) -> Result<Self, ImageError> {
let image = decode(data)?;
// Most files hold eight-bit samples, which decode through a table of all 256 values rather than a power function for each
@@ -159,7 +179,7 @@ impl Image<Color> {
.map(|&[red, green, blue, alpha]| SRGBA8::new(red, green, blue, alpha).into())
.collect();
return Some(Image {
return Ok(Image {
width: image.width(),
height: image.height(),
data,
@@ -187,7 +207,7 @@ impl Image<Color> {
})
.collect();
Some(Image {
Ok(Image {
width: image.width(),
height: image.height(),
data,
@@ -196,7 +216,7 @@ impl Image<Color> {
/// The pixel size of an image file, if it decodes in full as [`Image::from_encoded`] needs it to.
pub fn encoded_size(data: &[u8]) -> Option<(u32, u32)> {
decode(data).map(|image| (image.width(), image.height()))
decode(data).ok().map(|image| (image.width(), image.height()))
}
/// The image shrunk by half along each axis `times` times, averaging each block of pixels with their colors weighted by their alpha.
@@ -246,9 +266,17 @@ impl Image<Color> {
}
/// A TGA file has no signature to recognize it by, so a file of no recognized format is tried as one.
fn decode(data: &[u8]) -> Option<::image::DynamicImage> {
fn decode(data: &[u8]) -> Result<::image::DynamicImage, ImageError> {
let format = ::image::guess_format(data).unwrap_or(::image::ImageFormat::Tga);
::image::load_from_memory_with_format(data, format).ok()
::image::load_from_memory_with_format(data, format).map_err(|error| {
// The memory limit error carries no size, which the header gives
if let ::image::ImageError::Limits(_) = error
&& let Ok((width, height)) = ::image::ImageReader::with_format(std::io::Cursor::new(data), format).into_dimensions()
{
return ImageError::TooLarge { width, height };
}
ImageError::Undecodable(error)
})
}
use super::*;
@@ -389,12 +417,37 @@ mod test {
let mut encoded = Vec::new();
pixels.write_to(&mut std::io::Cursor::new(&mut encoded), format).unwrap();
let image = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{format:?} should decode"));
let image = Image::from_encoded(&encoded).unwrap_or_else(|error| panic!("{format:?} should decode: {error}"));
assert_eq!(Image::encoded_size(&encoded), Some((2, 1)), "{format:?}");
assert_eq!(image.to_flat_u8().0, pixels.as_raw().as_slice(), "{format:?}");
}
assert!(Image::from_encoded(b"not an image").is_none());
assert!(Image::from_encoded(b"not an image").is_err());
}
#[test]
fn a_file_that_does_not_decode_gives_its_reason() {
use super::*;
assert!(matches!(Image::from_encoded(b"not an image"), Err(ImageError::Undecodable(_))));
// A BMP header for a 32-bit image of 30000×30000 pixels, which is far beyond the decoder's memory limit
let mut file = b"BM".to_vec();
for field in [54_u32, 0, 54, 40, 30000, 30000] {
file.extend(field.to_le_bytes());
}
file.extend([1, 0, 32, 0]);
file.extend([0; 24]);
let error = Image::from_encoded(&file).unwrap_err();
assert!(matches!(error, ImageError::TooLarge { width: 30000, height: 30000 }), "{error:?}");
}
#[test]
fn an_image_too_large_for_its_pixel_indices_is_not_made() {
use super::*;
assert!(matches!(Image::try_new(65536, 65536, Color::BLACK), Err(ImageError::TooLarge { width: 65536, height: 65536 })));
assert_eq!(Image::try_new(3, 2, Color::BLACK).unwrap().data, vec![Color::BLACK; 6]);
}
#[test]
@@ -453,7 +506,7 @@ mod test {
file.extend([0, 255, 0, 0]);
assert!(::image::load_from_memory_with_format(&file, ::image::ImageFormat::Tga).is_ok());
assert!(Image::from_encoded(&file).is_none());
assert!(Image::from_encoded(&file).is_err());
}
#[test]
+2 -2
View File
@@ -2,10 +2,10 @@ pub mod image;
pub mod raster_types;
// Re-exports for convenience
pub use image::Image;
pub use image::{Image, ImageError};
pub use raster_types::*;
// Re-export color types from core-types
// Re-export color types from no-std-types
pub use core_types::color::*;
/// as to not yet rename all references
@@ -14,10 +14,6 @@ mod __private {
pub trait Storage: __private::Sealed + Clone + Debug + 'static {
fn is_empty(&self) -> bool;
/// The affine from the unit square of the pixels onto the region of the item's local space they cover, which the unit square is logically.
fn coverage(&self) -> DAffine2 {
DAffine2::IDENTITY
}
}
#[derive(Clone, Debug, PartialEq, Default)]
@@ -289,7 +285,6 @@ pub use gpu::{Texture, TextureWeakRef};
mod gpu {
use super::*;
use crate::raster_types::__private::Sealed;
use glam::UVec2;
use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Eq, Hash, DynAny)]
@@ -354,23 +349,15 @@ mod gpu {
}
}
#[derive(Clone, Debug, Default, PartialEq)]
#[derive(Clone, Debug, PartialEq, Hash)]
pub struct GPU {
texture: Option<Texture>,
coverage: DAffine2,
}
impl ::core::hash::Hash for GPU {
fn hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
self.texture.hash(state);
self.coverage.to_cols_array().map(f64::to_bits).hash(state);
}
pub texture: Texture,
}
impl core_types::CacheHash for GPU {
fn cache_hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
use ::core::hash::Hash;
self.hash(state);
self.texture.hash(state);
}
}
@@ -378,35 +365,17 @@ mod gpu {
impl Storage for Raster<GPU> {
fn is_empty(&self) -> bool {
let size = self.size();
size.x == 0 || size.y == 0
}
fn coverage(&self) -> DAffine2 {
self.coverage
self.texture.width() == 0 || self.texture.height() == 0
}
}
impl Raster<GPU> {
pub fn new_gpu(texture: impl Into<Texture>) -> Self {
Self::new(GPU {
texture: Some(texture.into()),
coverage: DAffine2::IDENTITY,
})
Self::new(GPU { texture: texture.into() })
}
/// The same pixels covering the region of the item's local space that `coverage` maps the unit square onto.
pub fn with_coverage(mut self, coverage: DAffine2) -> Self {
self.coverage = coverage;
self
}
pub fn texture(&self) -> Option<&Texture> {
self.texture.as_ref()
}
pub fn size(&self) -> UVec2 {
self.texture.as_ref().map_or(UVec2::ZERO, |texture| UVec2::new(texture.width(), texture.height()))
pub fn data(&self) -> &wgpu::Texture {
&self.texture
}
}
}
@@ -416,7 +385,7 @@ mod gpu {
use super::*;
use crate::raster_types::__private::Sealed;
#[derive(Clone, Debug, Default, PartialEq, Hash, core_types::CacheHash)]
#[derive(Clone, Debug, PartialEq, Hash, core_types::CacheHash)]
pub struct GPU;
impl Sealed for Raster<GPU> {}
@@ -460,9 +429,7 @@ where
}
let unit_rectangle = Quad::from_box([DVec2::ZERO, DVec2::ONE]);
let [start, end] = (transform * unit_rectangle).bounding_box();
let [covered_start, covered_end] = (transform * self.coverage() * unit_rectangle).bounding_box();
RenderBoundingBox::Rectangle([start.min(covered_start), end.max(covered_end)])
RenderBoundingBox::Rectangle((transform * unit_rectangle).bounding_box())
}
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
+11 -105
View File
@@ -23,7 +23,7 @@ use core_types::{
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2};
use graphene_resource::Resource;
use graphic_types::raster_types::{CPU, GPU, Raster, Storage, Texture};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::vector_types::gradient::{Gradient, GradientForm};
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint, TargetPath};
use graphic_types::vector_types::vector::misc::dvec2_to_point;
@@ -377,9 +377,6 @@ pub struct RenderParams {
pub canvas_image_scale: f64,
/// The nearest ancestor's appearance, cascading to items that lack their own.
pub inherited_appearance: Option<Appearance>,
/// Downloaded images of GPU raster textures, which SVG output embeds in place of the textures it can't reference. GPU rasters without one are not drawn.
#[cache_hash(skip)]
pub gpu_raster_downloads: Arc<HashMap<Texture, Raster<CPU>>>,
}
impl RenderParams {
@@ -778,9 +775,6 @@ pub trait Render: BoundingBox {
false
}
/// Recursively collects the textures of the GPU rasters this content draws, including those painting its appearances, so SVG output can download them first.
fn collect_gpu_textures(&self, _textures: &mut Vec<Texture>) {}
fn new_ids_from_hash(&mut self, _reference: Option<NodeId>) {}
}
@@ -1048,20 +1042,6 @@ fn add_graphic_item_outline_targets(item: ItemRef<'_, Graphic>, outlines: &mut V
outlines.extend(new_outlines);
}
/// Collects the textures of the GPU rasters painting an appearance's coverages.
fn collect_appearance_gpu_textures(appearance: Option<&Appearance>, textures: &mut Vec<Texture>) {
for paint in appearance.into_iter().flat_map(Appearance::covers_with_paints).filter_map(|(_, paint)| paint) {
paint.collect_gpu_textures(textures);
}
}
/// Collects the textures of the GPU rasters painting the appearances of a list's items.
fn collect_list_appearance_gpu_textures<T>(list: &List<T>, textures: &mut Vec<Texture>) {
for appearance in list.iter_attribute_values::<Appearance>(ATTR_APPEARANCE).into_iter().flatten() {
collect_appearance_gpu_textures(Some(appearance), textures);
}
}
impl Render for Graphic {
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
match self {
@@ -1069,14 +1049,14 @@ impl Render for Graphic {
Graphic::Graphic(item) => render_graphic_item_svg(ItemRef::Item(item), false, &mut None, render, render_params),
Graphic::Vector(item) => render_vector_item_svg(ItemRef::Item(item), false, &mut None, render, render_params),
Graphic::RasterCPU(item) => render_raster_cpu_item_svg(ItemRef::Item(item), render, render_params),
Graphic::RasterGPU(item) => render_raster_gpu_item_svg(ItemRef::Item(item), render, render_params),
Graphic::RasterGPU(_) => (),
Graphic::Color(item) => render_color_item_svg(ItemRef::Item(item), render, render_params),
Graphic::Gradient(item) => render_gradient_item_svg(ItemRef::Item(item), render, render_params),
Graphic::Text(item) => render_text_item_svg(ItemRef::Item(item), render, render_params),
Graphic::GraphicList(list) => list.render_svg(render, render_params),
Graphic::VectorList(list) => list.render_svg(render, render_params),
Graphic::RasterCPUList(list) => list.render_svg(render, render_params),
Graphic::RasterGPUList(list) => list.render_svg(render, render_params),
Graphic::RasterGPUList(_) => (),
Graphic::ColorList(list) => list.render_svg(render, render_params),
Graphic::GradientList(list) => list.render_svg(render, render_params),
Graphic::TextList(list) => list.render_svg(render, render_params),
@@ -1112,31 +1092,6 @@ impl Render for Graphic {
}
}
fn collect_gpu_textures(&self, textures: &mut Vec<Texture>) {
match self {
Graphic::Graphic(item) => {
item.element().collect_gpu_textures(textures);
collect_appearance_gpu_textures(item.attribute(ATTR_APPEARANCE), textures);
}
Graphic::Vector(item) => collect_appearance_gpu_textures(item.attribute(ATTR_APPEARANCE), textures),
Graphic::RasterGPU(item) => collect_raster_gpu_texture(item.element(), textures),
Graphic::GraphicList(list) => list.collect_gpu_textures(textures),
Graphic::VectorList(list) => list.collect_gpu_textures(textures),
Graphic::RasterGPUList(list) => list.collect_gpu_textures(textures),
Graphic::None(_)
| Graphic::NoneList(_)
| Graphic::RasterCPU(_)
| Graphic::Color(_)
| Graphic::Gradient(_)
| Graphic::Text(_)
| Graphic::RasterCPUList(_)
| Graphic::ColorList(_)
| Graphic::GradientList(_)
| Graphic::TextList(_)
| Graphic::StrokeList(_) => {}
}
}
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>, inherited_appearance: Option<&Appearance>) {
if let Some(element_id) = element_id {
// The footprint always lands; the transform (and for vectors the source layer) comes from the first item when one exists
@@ -1433,12 +1388,6 @@ impl Render for List<Artboard> {
}
}
fn collect_gpu_textures(&self, textures: &mut Vec<Texture>) {
for artboard in self.iter_element_values() {
artboard.as_graphic_list().collect_gpu_textures(textures);
}
}
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>, _inherited_appearance: Option<&Appearance>) {
for index in 0..self.len() {
let dimensions: DVec2 = self.attribute_cloned_or_default(ATTR_DIMENSIONS, index);
@@ -1490,13 +1439,6 @@ impl Render for List<Graphic> {
self.iter_element_values().any(|element| element.contains_artboard())
}
fn collect_gpu_textures(&self, textures: &mut Vec<Texture>) {
for element in self.iter_element_values() {
element.collect_gpu_textures(textures);
}
collect_list_appearance_gpu_textures(self, textures);
}
fn new_ids_from_hash(&mut self, _reference: Option<NodeId>) {
let (elements, layers) = self.element_and_attribute_slices_mut::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH);
for (element, layer) in elements.iter_mut().zip(layers.iter()) {
@@ -2300,10 +2242,6 @@ impl Render for List<Vector> {
}
}
fn collect_gpu_textures(&self, textures: &mut Vec<Texture>) {
collect_list_appearance_gpu_textures(self, textures);
}
fn new_ids_from_hash(&mut self, reference: Option<NodeId>) {
for index in 0..self.len() {
edit_list_row_geometry(self, index, |vector, paths| vector.vector_new_ids_from_hash(paths, reference.map(|id| id.0).unwrap_or_default()));
@@ -2419,22 +2357,8 @@ fn canvas_image_id(buffer_id: u64, halvings: u32) -> u64 {
/// Emits one item of CPU raster content as SVG, as a canvas placeholder or an embedded base64 image.
fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster<CPU>>, render: &mut SvgRender, render_params: &RenderParams) {
let Some(image) = item.element() else { return };
render_raster_image_svg(item, image, image.coverage(), render, render_params);
}
/// Emits one item of GPU raster content as SVG from its texture's downloaded image, exactly as CPU raster content.
fn render_raster_gpu_item_svg(item: ItemRef<'_, Raster<GPU>>, render: &mut SvgRender, render_params: &RenderParams) {
let Some(raster) = item.element() else { return };
let Some(image) = raster.texture().and_then(|texture| render_params.gpu_raster_downloads.get(texture)) else {
return;
};
render_raster_image_svg(item, image, raster.coverage(), render, render_params);
}
/// Emits a raster image as SVG, placed by the attributes of the item it's drawn for and the `coverage` of its pixels within it, and styled by those attributes.
fn render_raster_image_svg<T>(item: ItemRef<'_, T>, image: &Raster<CPU>, coverage: DAffine2, render: &mut SvgRender, render_params: &RenderParams) {
let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let transform = item_transform * coverage;
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.);
let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
@@ -2623,10 +2547,8 @@ impl Render for List<Raster<CPU>> {
}
impl Render for List<Raster<GPU>> {
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
for index in 0..self.len() {
render_raster_gpu_item_svg(ItemRef::ListItem(self, index), render, render_params);
}
fn render_svg(&self, _render: &mut SvgRender, _render_params: &RenderParams) {
log::warn!("tried to render texture as an svg");
}
fn render_to_vello(&self, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
@@ -2644,26 +2566,11 @@ impl Render for List<Raster<GPU>> {
add_unit_square_click_target(self.attribute_cloned_or_default(ATTR_TRANSFORM, index), click_targets);
}
}
fn collect_gpu_textures(&self, textures: &mut Vec<Texture>) {
for raster in self.iter_element_values() {
collect_raster_gpu_texture(raster, textures);
}
}
}
/// Collects a GPU raster's texture unless it's empty or already collected.
fn collect_raster_gpu_texture(raster: &Raster<GPU>, textures: &mut Vec<Texture>) {
if let Some(texture) = raster.texture()
&& !textures.contains(texture)
{
textures.push(texture.clone());
}
}
/// Draws one item of GPU raster content into the Vello scene.
fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster<GPU>>, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
let Some(texture) = item.element().and_then(|raster| raster.texture()) else { return };
let Some(raster) = item.element() else { return };
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.);
let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
@@ -2703,13 +2610,12 @@ fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster<GPU>>, scene: &mut V
return;
}
let width = texture.width();
let height = texture.height();
let width = raster.data().width();
let height = raster.data().height();
let sampler = peniko::ImageSampler::new().with_extend(peniko::Extend::Pad);
let coverage = item.element().map_or(DAffine2::IDENTITY, Storage::coverage);
let image_transform = transform * transform_attribute * coverage * DAffine2::from_scale(1. / DVec2::new(width as f64, height as f64));
scene.draw_texture(texture.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array()));
let image_transform = transform * transform_attribute * DAffine2::from_scale(1. / DVec2::new(width as f64, height as f64));
scene.draw_texture(raster.texture.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array()));
if layer {
scene.pop_layer()
@@ -40,6 +40,7 @@ rustc-hash = { workspace = true }
polycool = { workspace = true }
robust = { workspace = true }
tinyvec = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
@@ -81,9 +81,20 @@ pub fn tangent_on_bezpath(bezpath: &BezPath, t_value: TValue, segments_length: O
dvec2_to_point(pathseg_tangent(segment, t))
}
/// Computes sample locations along a bezpath, returning parametric `(segment_index, t)` pairs and whether the path was closed.
/// The failure of [`compute_sample_locations`]: the path would need more samples than the most it places on one subpath.
#[derive(Debug, thiserror::Error)]
pub enum SampleCountError {
#[error("The separation is too small for this path: it would need more than {limit} points")]
SeparationTooSmall { limit: usize },
#[error("The quantity is more than the maximum of {limit} points")]
QuantityTooLarge { limit: usize },
}
/// Computes sample locations along a bezpath, returning parametric `(segment_index, t)` pairs and whether the path was closed,
/// or `None` when there's nothing to sample.
/// The `bezpath` is used for euclidean-to-parametric conversion, and `segments_length` provides pre-calculated world-space segment lengths.
/// Callers can evaluate these locations on any bezpath with the same topology (e.g., an untransformed version).
#[allow(clippy::type_complexity)]
pub fn compute_sample_locations(
bezpath: &BezPath,
point_spacing_type: PointSpacingType,
@@ -92,7 +103,7 @@ pub fn compute_sample_locations(
stop_offset: f64,
adaptive_spacing: bool,
segments_length: &[f64],
) -> Option<(Vec<(usize, f64)>, bool)> {
) -> Result<Option<(Vec<(usize, f64)>, bool)>, SampleCountError> {
let was_closed = matches!(bezpath.elements().last(), Some(PathEl::ClosePath));
// Calculate the total length of the collected segments.
@@ -103,36 +114,44 @@ pub fn compute_sample_locations(
// Sanity check that the usable length is positive.
if used_length <= 0. {
return None;
return Ok(None);
}
const SAFETY_MAX_COUNT: f64 = 10_000. - 1.;
const MAX_POINTS: usize = 10_000;
// Determine the number of points to generate along the path.
let sample_count = match point_spacing_type {
PointSpacingType::Separation => {
let spacing = amount.min(used_length - f64::EPSILON);
if adaptive_spacing {
let count = if adaptive_spacing {
// Calculate point count to evenly distribute points while covering the entire path.
// With adaptive spacing, we widen or narrow the points as necessary to ensure the last point is always at the end of the path.
(used_length / spacing).round().min(SAFETY_MAX_COUNT)
(used_length / spacing).round()
} else {
// Calculate point count based on exact spacing, which may not cover the entire path.
// Without adaptive spacing, we just evenly space the points at the exact specified spacing, usually falling short before the end of the path.
let count = (used_length / spacing + f64::EPSILON).floor().min(SAFETY_MAX_COUNT);
if count != SAFETY_MAX_COUNT {
used_length -= used_length % spacing;
}
count
(used_length / spacing + f64::EPSILON).floor()
};
if count >= MAX_POINTS as f64 {
return Err(SampleCountError::SeparationTooSmall { limit: MAX_POINTS });
}
if !adaptive_spacing {
used_length -= used_length % spacing;
}
count
}
PointSpacingType::Quantity => {
let count = (amount - 1.).floor();
if count >= MAX_POINTS as f64 {
return Err(SampleCountError::QuantityTooLarge { limit: MAX_POINTS });
}
count.max(1.)
}
PointSpacingType::Quantity => (amount - 1.).floor().clamp(1., SAFETY_MAX_COUNT),
};
// Skip if there are no points to generate.
if sample_count < 1. {
return None;
return Ok(None);
}
// Decide how many loop-iterations: if closed, skip the last duplicate point
@@ -169,7 +188,7 @@ pub fn compute_sample_locations(
locations.push((next_segment_index, t));
}
Some((locations, was_closed))
Ok(Some((locations, was_closed)))
}
#[derive(Debug, Clone, Copy)]
@@ -277,7 +296,8 @@ pub(crate) fn pathseg_length_centroid_and_length(segment: PathSeg, accuracy: Opt
/// Finds the parametric `t` value on the given path segment corresponding to a fractional arc-length `distance` (0–1).
/// Delegates to kurbo's `inv_arclen` which uses the ITP method with incremental arc-length computation.
pub fn eval_pathseg_euclidean(segment: PathSeg, distance: f64, accuracy: f64) -> f64 {
segment.inv_arclen(distance.clamp(0., 1.) * segment.arclen(accuracy), accuracy)
let length = segment.arclen(accuracy);
segment.inv_arclen(distance.clamp(0., 1.) * length, accuracy.max(length * 1e-14))
}
/// Converts from a bezpath (composed of multiple segments) to a point along a certain segment represented.
@@ -385,6 +405,10 @@ pub fn poisson_disk_points(bezpath_index: usize, bezpaths: &[(BezPath, Rect)], s
let width = this_bbox.width();
let height = this_bbox.height();
if width.is_infinite() || height.is_infinite() {
return Vec::new();
}
poisson_disk_sample(offset, width, height, separation_disk_diameter, point_in_shape_checker, line_intersect_shape_checker, rng)
}
@@ -645,7 +669,7 @@ pub fn bezpath_area_centroid_and_area(bezpath: &BezPath, error: Option<f64>, min
/// The length centroid is the center of mass for the arc length of the solid shape's perimeter.
/// An infinitely thin wire forming the path's shape would balance at this point.
///
/// It will return `None` if no segment is present.
/// It will return `None` if no segment has any length.
/// - `accuracy` is used to approximate the curve.
/// - `always_closed` is to consider the path as closed always.
pub fn bezpath_length_centroid_and_length(bezpath: &BezPath, accuracy: Option<f64>, always_closed: bool) -> Option<(DVec2, f64)> {
@@ -654,6 +678,7 @@ pub fn bezpath_length_centroid_and_length(bezpath: &BezPath, accuracy: Option<f6
segments
.into_iter()
.map(|bezier| pathseg_length_centroid_and_length(bezier, accuracy))
.filter(|&(_, length)| length != 0.)
.map(|(centroid, length)| (centroid * length, length))
.reduce(|(centroid_part1, length1), (centroid_part2, length2)| (centroid_part1 + centroid_part2, length1 + length2))
.map(|(centroid_part, length)| (centroid_part / length, length))
@@ -698,4 +723,25 @@ mod tests {
assert_eq!(area, 200. * 100.);
assert_eq!(center, glam::DVec2::new(200., 150.));
}
#[test]
fn centroid_of_a_huge_curve() {
let mut bezpath = BezPath::new();
bezpath.move_to((0., 0.));
bezpath.curve_to((0.55e60, 0.), (1e60, 0.45e60), (1e60, 1e60));
bezpath.close_path();
assert!(super::bezpath_area_centroid_and_area(&bezpath, Some(1e-3), Some(1e-3)).is_some());
}
#[test]
fn length_centroid_skips_zero_length_segments() {
let mut bezpath = BezPath::new();
bezpath.move_to((0., 0.));
bezpath.line_to((10., 0.));
bezpath.curve_to((10., 0.), (10., 0.), (10., 0.));
let (centroid, length) = super::bezpath_length_centroid_and_length(&bezpath, None, false).unwrap();
assert_eq!((centroid, length), (glam::DVec2::new(5., 0.), 10.));
}
}
@@ -216,8 +216,11 @@ fn pathseg_self_intersection(segment: PathSeg, accuracy: Option<f64>) -> Vec<(f6
PathSeg::Cubic(cubic_bez) => cubic_bez,
};
let size = approx_bounding_box(segment).size();
let accuracy_for_size = DEFAULT_ACCURACY.max(size.width.max(size.height) * 1e-9);
// Get 2 copies of the reduced curves
let quads1 = cubic_bez.to_quads(DEFAULT_ACCURACY).map(|(t1, t2, quad_bez)| (t1, t2, PathSeg::Quad(quad_bez))).collect::<Vec<_>>();
let quads1 = cubic_bez.to_quads(accuracy_for_size).map(|(t1, t2, quad_bez)| (t1, t2, PathSeg::Quad(quad_bez))).collect::<Vec<_>>();
let quads2 = quads1.clone();
let num_curves = quads1.len();
@@ -1,21 +1,30 @@
use super::bezpath_algorithms::{clip_simple_bezpaths, miter_line_join, round_line_join};
use super::consts::MAX_COINCIDENT_POINT_DISTANCE;
use crate::vector::misc::point_to_dvec2;
use kurbo::{BezPath, Join, ParamCurve, PathEl, PathSeg};
use kurbo::{BezPath, Join, ParamCurve, PathEl, PathSeg, Rect, Shape};
/// Value to control smoothness and mathematical accuracy to offset a cubic Bezier.
const CUBIC_REGULARIZATION_ACCURACY: f64 = 0.5;
/// Squared version to avoid sqrt in distance checks.
const MAX_COINCIDENT_POINT_DISTANCE_SQUARED: f64 = MAX_COINCIDENT_POINT_DISTANCE * MAX_COINCIDENT_POINT_DISTANCE;
const MAX_FITTED_SEGMENTS: usize = 10000;
/// The coordinate magnitude from which lyon's curve intersection, used to clip the offset pieces, panics converting it to an `i64`.
const MAX_CLIPPED_COORDINATE: f64 = i64::MAX as f64;
/// The failure of [`offset_bezpath`].
#[derive(Debug, thiserror::Error)]
pub enum OffsetPathError {
#[error("The shape or offset distance is too large to offset")]
TooLarge,
}
/// Reduces the segments of the bezpath into simple subcurves, then offset each subcurve a set `distance` away.
/// The intersections of segments of the subpath are joined using the method specified by the `join` argument.
pub fn offset_bezpath(bezpath: &BezPath, distance: f64, join: Join, miter_limit: Option<f64>) -> BezPath {
pub fn offset_bezpath(bezpath: &BezPath, distance: f64, join: Join, miter_limit: Option<f64>) -> Result<BezPath, OffsetPathError> {
// An offset at a distance 0 from the curve is simply the same curve.
// An offset of a single point is not defined.
if distance == 0. || bezpath.get_seg(1).is_none() {
return bezpath.clone();
return Ok(bezpath.clone());
}
let mut bezpaths = bezpath
@@ -45,7 +54,12 @@ pub fn offset_bezpath(bezpath: &BezPath, distance: f64, join: Join, miter_limit:
.collect::<Vec<BezPath>>();
if bezpaths.is_empty() {
return BezPath::new();
return Ok(BezPath::new());
}
let too_large = |bounds: Rect| [bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().any(|coordinate| coordinate.abs() >= MAX_CLIPPED_COORDINATE);
if bezpaths.iter().any(|bezpath| too_large(bezpath.bounding_box())) {
return Err(OffsetPathError::TooLarge);
}
// Clip or join consecutive subpaths
@@ -152,5 +166,5 @@ pub fn offset_bezpath(bezpath: &BezPath, distance: f64, join: Join, miter_limit:
offset_bezpath.close_path();
}
offset_bezpath
Ok(offset_bezpath)
}
@@ -13,6 +13,19 @@ use std::f64::consts::TAU;
/// Constant from <https://pomax.github.io/bezierinfo/#circles_cubic>
const HANDLE_OFFSET_FACTOR: f64 = 0.551784777779014;
/// Relative growth per radian below which spiral arc lengths use a circle, since the closed forms divide by the growth.
const SPIRAL_CIRCLE_GROWTH: f64 = 1e-6;
/// The most anchors a polygon or star can have before allocating them overflows the address space.
const MAX_POLYGON_ANCHORS: u64 = (isize::MAX as usize / size_of::<Anchor>()) as u64;
/// The failure of [`regular_polygon_bezpath`] and [`star_polygon_bezpath`].
#[derive(Debug, thiserror::Error)]
pub enum PolygonError {
#[error("A shape with {0} sides is too large to fit in memory")]
TooManySides(u64),
}
/// An anchor point with its optional incoming and outgoing handle positions, in absolute coordinates.
#[derive(Clone)]
struct Anchor {
@@ -64,8 +77,8 @@ pub fn rounded_rectangle_bezpath(corner1: DVec2, corner2: DVec2, corner_radii: [
let handle_offset = radius * HANDLE_OFFSET_FACTOR;
vec![
Anchor::new(point1, None, Some(point1 + handle_offset * (corner - point1).normalize())),
Anchor::new(point2, Some(point2 + handle_offset * (corner - point2).normalize()), None),
Anchor::new(point1, None, Some(point1 + handle_offset * (corner - point1).normalize_or_zero())),
Anchor::new(point2, Some(point2 + handle_offset * (corner - point2).normalize_or_zero()), None),
]
};
@@ -162,7 +175,12 @@ pub fn arc_bezpath(radius: f64, start_angle: f64, sweep_angle: f64, arc_type: Ar
}
/// Constructs a regular polygon (ngon). Based on `sides` and `radius`, which is the distance from the center to any vertex.
pub fn regular_polygon_bezpath(center: DVec2, sides: u64, radius: f64) -> BezPath {
/// Fails when it has more sides than can be allocated.
pub fn regular_polygon_bezpath(center: DVec2, sides: u64, radius: f64) -> Result<BezPath, PolygonError> {
if sides > MAX_POLYGON_ANCHORS {
return Err(PolygonError::TooManySides(sides));
}
let sides = sides.max(3);
let angle_increment = TAU / (sides as f64);
let positions = (0..sides).map(|i| {
@@ -170,11 +188,16 @@ pub fn regular_polygon_bezpath(center: DVec2, sides: u64, radius: f64) -> BezPat
center + radius * DVec2::new(f64::cos(angle), f64::sin(angle))
});
polyline_bezpath(positions, true)
Ok(polyline_bezpath(positions, true))
}
/// Constructs a star polygon (n-star). See [`regular_polygon_bezpath`], but with interspersed vertices at an `inner_radius`.
pub fn star_polygon_bezpath(center: DVec2, sides: u64, radius: f64, inner_radius: f64) -> BezPath {
pub fn star_polygon_bezpath(center: DVec2, sides: u64, radius: f64, inner_radius: f64) -> Result<BezPath, PolygonError> {
// Each side has an outer and an inner anchor
if sides > MAX_POLYGON_ANCHORS / 2 {
return Err(PolygonError::TooManySides(sides));
}
let sides = sides.max(2);
let angle_increment = 0.5 * TAU / (sides as f64);
let positions = (0..sides * 2).map(|i| {
@@ -183,7 +206,7 @@ pub fn star_polygon_bezpath(center: DVec2, sides: u64, radius: f64, inner_radius
center + radius * DVec2::new(f64::cos(angle), f64::sin(angle))
});
polyline_bezpath(positions, true)
Ok(polyline_bezpath(positions, true))
}
/// Constructs a line from `point1` to `point2`.
@@ -224,8 +247,26 @@ pub fn arrow_bezpath(start: DVec2, end: DVec2, shaft_width: f64, head_width: f64
polyline_bezpath(positions, true)
}
/// The failure of [`spiral_bezpath`].
#[derive(Debug, thiserror::Error)]
pub enum SpiralError {
#[error("The angular resolution must be greater than 0")]
AngularResolutionNotPositive,
#[error("The number of turns must be finite")]
TurnsNotFinite,
#[error("The start angle is too large to step through at this angular resolution")]
AngleTooLarge,
}
/// Constructs a spiral winding from an inner radius `a` out to `outer_radius`, sampled every `delta_theta` radians.
pub fn spiral_bezpath(a: f64, outer_radius: f64, turns: f64, start_angle: f64, delta_theta: f64, spiral_type: SpiralType) -> BezPath {
pub fn spiral_bezpath(a: f64, outer_radius: f64, turns: f64, start_angle: f64, delta_theta: f64, spiral_type: SpiralType) -> Result<BezPath, SpiralError> {
if delta_theta.is_nan() || delta_theta <= 0. {
return Err(SpiralError::AngularResolutionNotPositive);
}
if turns == f64::INFINITY {
return Err(SpiralError::TurnsNotFinite);
}
let mut anchors = Vec::new();
let mut prev_in_handle = None;
let theta_end = turns * TAU + start_angle;
@@ -236,6 +277,10 @@ pub fn spiral_bezpath(a: f64, outer_radius: f64, turns: f64, start_angle: f64, d
let mut theta = start_angle;
while theta < theta_end {
let theta_next = f64::min(theta + delta_theta, theta_end);
// A step lost to the angle's float precision would never reach the end
if theta_next == theta {
return Err(SpiralError::AngleTooLarge);
}
let p0 = spiral_point(theta, a, b, spiral_type);
let p3 = spiral_point(theta_next, a, b, spiral_type);
@@ -260,7 +305,7 @@ pub fn spiral_bezpath(a: f64, outer_radius: f64, turns: f64, start_angle: f64, d
theta = theta_next;
}
bezpath_from_anchors(&anchors, false)
Ok(bezpath_from_anchors(&anchors, false))
}
pub fn calculate_growth_factor(a: f64, turns: f64, outer_radius: f64, spiral_type: SpiralType) -> f64 {
@@ -309,6 +354,9 @@ fn log_spiral_point(theta: f64, a: f64, b: f64) -> DVec2 {
/// Computes arc length along a logarithmic spiral between two angles.
fn log_spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64) -> f64 {
let factor = (1. + b * b).sqrt();
if b.abs() < SPIRAL_CIRCLE_GROWTH {
return a * (b * (theta_start + theta_end) / 2.).exp() * factor * (theta_end - theta_start);
}
(a / b) * factor * ((b * theta_end).exp() - (b * theta_start).exp())
}
@@ -337,6 +385,10 @@ fn archimedean_spiral_tangent(theta: f64, a: f64, b: f64) -> DVec2 {
/// Computes arc length along an Archimedean spiral between two angles.
fn archimedean_spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64) -> f64 {
let middle_radius = a + b * (theta_start + theta_end) / 2.;
if b.abs() <= middle_radius.abs() * SPIRAL_CIRCLE_GROWTH {
return middle_radius.abs() * (theta_end - theta_start);
}
archimedean_spiral_arc_length_origin(theta_end, a, b) - archimedean_spiral_arc_length_origin(theta_start, a, b)
}
@@ -59,56 +59,58 @@ impl WeldExt for Vector {
})
.collect::<Vec<_>>();
// Collect points and segments to delete at the end to avoid invalidating indices
// Each collapse set keeps its first point, which every other point in the set merges into
let mut collapse_group = FxHashMap::default();
let mut kept_points = Vec::with_capacity(collapse.len());
let mut points_to_delete = FxHashSet::default();
let mut segments_to_delete = FxHashSet::default();
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position) {
// Remove any segments where both endpoints are in the collapse set
for segment_index in 0..working.segment_ids.len() {
let start = working.point_ids[working.segment_start[segment_index]];
let end = working.point_ids[working.segment_end[segment_index]];
if collapse_set.contains(&start) && collapse_set.contains(&end) {
segments_to_delete.insert(working.segment_ids[segment_index]);
}
}
// Delete all points but the first, set its position to the average, and update segments
for (group, collapse_set) in collapse.iter().enumerate() {
let first_id = collapse_set.iter().copied().next().unwrap();
collapse_set.remove(&first_id);
let first_offset = indices.point_to_offset[&first_id];
kept_points.push((first_id, indices.point_to_offset[&first_id]));
// Look for segments with endpoints in `collapse_set` and replace them with the point we are collapsing to
for segment_index in 0..working.segment_ids.len() {
let start_id = working.point_ids[working.segment_start[segment_index]];
let end_id = working.point_ids[working.segment_end[segment_index]];
// Update Bezier handles for moved points
if start_id == first_id {
let point_position = working.point_positions[working.segment_start[segment_index]];
working.segment_handles[segment_index].move_start(average_pos - point_position);
}
if end_id == first_id {
let point_position = working.point_positions[working.segment_end[segment_index]];
working.segment_handles[segment_index].move_end(average_pos - point_position);
}
// Replace removed points with the collapsed point
if collapse_set.contains(&start_id) {
let point_position = working.point_positions[working.segment_start[segment_index]];
working.segment_start[segment_index] = first_offset;
working.segment_handles[segment_index].move_start(average_pos - point_position);
}
if collapse_set.contains(&end_id) {
let point_position = working.point_positions[working.segment_end[segment_index]];
working.segment_end[segment_index] = first_offset;
working.segment_handles[segment_index].move_end(average_pos - point_position);
for &id in collapse_set {
collapse_group.insert(id, group);
if id != first_id {
points_to_delete.insert(id);
}
}
}
// Update the position of the collapsed point
// Collect segments to delete at the end to avoid invalidating indices
let mut segments_to_delete = FxHashSet::default();
for segment_index in 0..working.segment_ids.len() {
let start_id = working.point_ids[working.segment_start[segment_index]];
let end_id = working.point_ids[working.segment_end[segment_index]];
let (start_group, end_group) = (collapse_group.get(&start_id).copied(), collapse_group.get(&end_id).copied());
// Remove any segments where both endpoints are in the same collapse set
if start_group.is_some() && start_group == end_group {
segments_to_delete.insert(working.segment_ids[segment_index]);
}
// Move the segment's ends in a collapse set, along with their handles, onto the point the set collapses to
if let Some(group) = start_group {
let point_position = working.point_positions[working.segment_start[segment_index]];
working.segment_handles[segment_index].move_start(average_position[group] - point_position);
let (first_id, first_offset) = kept_points[group];
if start_id != first_id {
working.segment_start[segment_index] = first_offset;
}
}
if let Some(group) = end_group {
let point_position = working.point_positions[working.segment_end[segment_index]];
working.segment_handles[segment_index].move_end(average_position[group] - point_position);
let (first_id, first_offset) = kept_points[group];
if end_id != first_id {
working.segment_end[segment_index] = first_offset;
}
}
}
// Update the positions of the collapsed points
for (&(_, first_offset), average_pos) in kept_points.iter().zip(average_position) {
working.point_positions[first_offset] = average_pos;
points_to_delete.extend(collapse_set)
}
// Drop the collapsed segments, then the merged-away points, remapping segment endpoints
@@ -404,13 +406,13 @@ fn weld_nearby_points(vector: &mut Vector, paths: &mut List<Path>, transform: DA
// Create a spatial grid with cell size of 'distance'
use std::collections::HashMap;
let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new();
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
// Add points to grid cells without collecting all positions first
for i in 0..point_count {
let pos = transform.transform_point2(working.point_positions[i]);
let grid_x = ((pos.x - min_x) / distance).floor() as i32;
let grid_y = ((pos.y - min_y) / distance).floor() as i32;
let grid_x = ((pos.x - min_x) / distance).floor() as i64;
let grid_y = ((pos.y - min_y) / distance).floor() as i64;
grid.entry((grid_x, grid_y)).or_default().push(i);
}
@@ -428,15 +430,16 @@ fn weld_nearby_points(vector: &mut Vector, paths: &mut List<Path>, transform: DA
}
let pos_i = transform.transform_point2(working.point_positions[i]);
let grid_x = ((pos_i.x - min_x) / distance).floor() as i32;
let grid_y = ((pos_i.y - min_y) / distance).floor() as i32;
let grid_x = ((pos_i.x - min_x) / distance).floor() as i64;
let grid_y = ((pos_i.y - min_y) / distance).floor() as i64;
let mut group = vec![i];
// Check only neighboring cells (3x3 grid around current cell)
for dx in -1..=1 {
for dy in -1..=1 {
let neighbor_cell = (grid_x + dx, grid_y + dy);
// The saturating cast puts infinite points in the grid's edge cells, which have no neighbors beyond
let Some(neighbor_cell) = grid_x.checked_add(dx).zip(grid_y.checked_add(dy)) else { continue };
if let Some(indices) = grid.get(&neighbor_cell) {
for &j in indices {
@@ -697,6 +700,19 @@ mod tests {
vector.0.iter_attribute_values::<PointId>(ATTR_ID).map(|ids| ids.map(|id| id.inner()).collect()).unwrap_or_default()
}
// A point too far off for the grid of cells to hold sits at its edge, which has no cells beyond it to check
#[test]
fn weld_all_beside_an_infinite_point() {
let mut vector = pool(&[(0., 0.), (0.05, 0.), (f64::INFINITY, 0.)]);
let mut paths = List::new();
push_path(&mut paths, CurveType::Linear, [0, 1, 2], []);
vector.weld_all(&mut paths, DAffine2::IDENTITY, 0.1);
assert_eq!(vector.0.len(), 2);
assert!(near(vector.0.element(0), (0.025, 0.)));
}
// Two lines meeting across a small gap join there, while two close points of another path stay apart since only one is an end
#[test]
fn flow_ends_join_without_touching_other_points() {
@@ -333,7 +333,7 @@ impl SegmentGraph {
let tangent = self.segment(side.segment_index, side.reversed).tangent_at_start();
tangent.y.atan2(tangent.x)
});
angle[0].partial_cmp(&angle[1]).unwrap_or(std::cmp::Ordering::Equal)
angle[0].total_cmp(&angle[1])
})
}
@@ -1519,4 +1519,20 @@ mod tests {
assert!(loop_area > 0., "the inner loop should wind positively after normalization");
assert_eq!(references(&paths), vec![vec![0, 1, 4, 3, 2, 1, 5]], "the path stays whole around its flipped loop");
}
// Sorting more than 20 segment ends around a junction by their angles mustn't panic where NaN geometry gives no angle
#[test]
fn faces_around_a_junction_with_nan_spokes() {
// The spokes are stored out of angle order, since the sort only notices the inconsistent comparisons when it has to reorder
let spokes = 24;
let ring = (0..spokes).map(|index| match index % 3 {
0 => DVec2::NAN,
_ => DVec2::from_angle((index * 7 % spokes) as f64 / spokes as f64 * std::f64::consts::TAU) * 10.,
});
let points: Vec<DVec2> = std::iter::once(DVec2::ZERO).chain(ring).collect();
let segments: Vec<(usize, usize)> = (1..=spokes).flat_map(|index| [(0, index), (index, index % spokes + 1)]).collect();
let (vector, paths) = build_vector(&points, &segments);
vector.construct_faces(&paths);
}
}
@@ -797,9 +797,11 @@ impl Vector {
pub fn concat(&mut self, paths: &mut List<Path>, additional: &Self, additional_paths: &List<Path>, transform_of_additional: DAffine2, collision_hash_seed: u64, taken_ids: &mut IdCollisionSet) {
let offset = self.0.len() as u32;
// If the pool lacks the ID column, appending IDs pads its points with a default one, which is then taken too
let first_untaken_point = if self.0.iter_attribute_values::<PointId>(ATTR_ID).is_some() { self.0.len() } else { 0 };
// Remap colliding stable IDs so both sides stay addressable after the merge.
// Appended IDs are only checked against the IDs taken before this call.
let mut appended_point_ids = Vec::new();
for index in 0..additional.0.len() {
let Some(&position) = additional.0.element(index) else { continue };
let mut item = Item::new_from_element(transform_of_additional.transform_point2(position));
@@ -811,7 +813,6 @@ impl Vector {
id
};
item.set_attribute(ATTR_ID, id);
appended_point_ids.push(id);
}
self.0.push(item);
@@ -837,7 +838,9 @@ impl Vector {
paths.push(item);
}
taken_ids.points.extend(appended_point_ids);
// Read back from the pool, since appending points without IDs to a pool with the column pads them with a default one
let appended_point_ids = self.0.iter_attribute_values::<PointId>(ATTR_ID).into_iter().flatten().skip(first_untaken_point);
taken_ids.points.extend(appended_point_ids.copied());
taken_ids.segments.extend(appended_segment_ids);
}
@@ -1038,6 +1041,36 @@ mod tests {
assert_eq!(vector.index_of_point_id(PointId::ZERO), Some(0));
}
#[test]
fn concat_with_tracked_ids_matches_collecting_them_anew() {
let triangle = BezPath::from_vec(vec![
PathEl::MoveTo((0., 0.).into()),
PathEl::LineTo((1., 0.).into()),
PathEl::LineTo((0., 1.).into()),
PathEl::ClosePath,
]);
let (triangle, triangle_paths) = Vector::from_bezpath(&triangle);
let (curve, curve_paths) = Vector::from_bezpath(&open_curve_bezpath());
let unnamed = Vector(List::new_from_element(DVec2::ONE));
let parts = [
(&unnamed, &List::new()),
(&triangle, &triangle_paths),
(&lone_anchor(DVec2::X), &List::new()),
(&curve, &curve_paths),
(&triangle, &triangle_paths),
];
let (mut each, mut each_paths) = (Vector::default(), List::new());
let (mut tracked, mut tracked_paths, mut ids) = (Vector::default(), List::new(), IdCollisionSet::default());
for (seed, (part, part_paths)) in parts.into_iter().enumerate() {
let mut collected = IdCollisionSet::of(&each, &each_paths);
each.concat(&mut each_paths, part, part_paths, DAffine2::IDENTITY, seed as u64, &mut collected);
tracked.concat(&mut tracked_paths, part, part_paths, DAffine2::IDENTITY, seed as u64, &mut ids);
}
assert_eq!((tracked, tracked_paths), (each, each_paths));
}
// Handles carry the unnamed filler, so a zero-named anchor behind them is still the one found by ID
#[test]
fn handles_do_not_shadow_a_zero_named_anchor() {
@@ -32,4 +32,4 @@ log = { workspace = true }
web-sys = { workspace = true }
vello_gpu = { workspace = true }
bytemuck = { workspace = true }
half = { workspace = true }
thiserror = { workspace = true }
+11 -37
View File
@@ -6,6 +6,7 @@ mod texture_cache;
pub mod texture_conversion;
mod vello_render;
use crate::shader_runtime::ShaderRuntime;
use crate::texture_cache::TextureCache;
use crate::vello_render::VelloRenderer;
pub use crate::vello_render::{MAX_LAYER_RENDER_SIZE, VelloCanvas};
@@ -21,11 +22,11 @@ pub use context::Context as WgpuContext;
pub use context::ContextBuilder as WgpuContextBuilder;
pub use pipeline::Pipeline as WgpuPipeline;
pub use pipeline::PipelineCache as WgpuPipelineCache;
pub use pipeline::PipelineError as WgpuPipelineError;
pub use raster_types::Texture;
pub use rendering::vello_scene_builder::VelloSceneBuilder;
pub use wgpu::Backends as WgpuBackends;
pub use wgpu::Features as WgpuFeatures;
pub use wgpu::TextureFormat as WgpuTextureFormat;
pub use wgpu_sync::CurrentSurfaceTexture as WgpuCurrentSurfaceTexture;
pub use wgpu_sync::Instance as WgpuInstance;
pub use wgpu_sync::Queue as WgpuQueue;
@@ -36,11 +37,6 @@ const TEXTURE_CACHE_SIZE: u64 = 1024 * 1024 * 1024; // 1GB
#[cfg(target_family = "wasm")]
const TEXTURE_CACHE_SIZE: u64 = 512 * 1024 * 1024; // 512MB
/// The preferred format of raster textures, holding linear-light straight-alpha values.
pub const RASTER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;
/// The raster texture format on adapters that can't render to [`RASTER_FORMAT`], or when `GRAPHITE_RASTER_FORMAT=f16` forces it.
pub const FALLBACK_RASTER_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
#[derive(dyn_any::DynAny, Clone)]
pub struct WgpuExecutor {
inner: Arc<WgpuExecutorInner>,
@@ -50,21 +46,16 @@ impl WgpuExecutor {
pub fn context(&self) -> &WgpuContext {
&self.inner.context
}
/// The format of every raster texture this executor creates, either [`RASTER_FORMAT`] or [`FALLBACK_RASTER_FORMAT`].
pub fn raster_format(&self) -> wgpu::TextureFormat {
self.inner.raster_format
}
}
#[derive(dyn_any::DynAny)]
pub struct WgpuExecutorInner {
context: WgpuContext,
texture_cache: std::sync::Mutex<TextureCache>,
raster_format: wgpu::TextureFormat,
vello_renderer: VelloRenderer,
/// The canvas the node graph renders documents on.
document_canvas: Mutex<VelloCanvas>,
shader_runtime: ShaderRuntime,
}
impl std::fmt::Debug for WgpuExecutor {
@@ -83,21 +74,12 @@ impl WgpuExecutor {
/// Renders the document scene `draw` draws, with its content placed by `view`, into a new texture of `size` with straight alpha.
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
pub fn render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
self.render_vello_with_format(size, view, draw, wgpu::TextureFormat::Rgba8Unorm)
}
/// Renders like [`Self::render_vello`], but into a new texture in [`Self::raster_format`] holding linear-light values, as a GPU raster's.
pub fn render_vello_raster(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
self.render_vello_with_format(size, view, draw, self.raster_format())
}
fn render_vello_with_format(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder), format: wgpu::TextureFormat) -> Result<Texture> {
let limit = self.context().device.limits().max_texture_dimension_2d;
if size.x > limit || size.y > limit {
anyhow::bail!("Render size {size} exceeds the GPU's texture size limit of {limit}");
}
let texture = self.request_texture_with_format(size, format);
let texture = self.request_texture(size);
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
@@ -190,32 +172,24 @@ impl WgpuExecutor {
}
pub fn with_context(context: WgpuContext) -> Option<Self> {
let raster_format = choose_raster_format(&context.adapter);
let vello_renderer = VelloRenderer::new(&context.device, raster_format);
let vello_renderer = VelloRenderer::new(&context.device);
let texture_cache = TextureCache::new(TEXTURE_CACHE_SIZE);
let shader_runtime = ShaderRuntime::default();
Some(Self {
inner: Arc::new(WgpuExecutorInner {
context,
texture_cache: texture_cache.into(),
raster_format,
vello_renderer,
document_canvas: Mutex::default(),
shader_runtime,
}),
})
}
}
fn choose_raster_format(adapter: &wgpu::Adapter) -> wgpu::TextureFormat {
if std::env::var("GRAPHITE_RASTER_FORMAT").is_ok_and(|format| format == "f16") {
return FALLBACK_RASTER_FORMAT;
}
if adapter.get_texture_format_features(RASTER_FORMAT).allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) {
RASTER_FORMAT
} else {
log::warn!("The GPU can't render to {RASTER_FORMAT:?}, so rasters fall back to {FALLBACK_RASTER_FORMAT:?}");
FALLBACK_RASTER_FORMAT
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("No GPU is available")]
pub struct NoGpuError;
@@ -25,24 +25,12 @@ impl PipelineCache {
self.pipeline.get_or_init(|| Box::new(P::create(executor)));
}
pub fn run<P: Pipeline>(&self, args: &P::Args<'_>) -> P::Out {
let executor = self.executor.get().expect("PipelineCache not initialized");
let entry = self.pipeline.get().expect("PipelineCache not initialized");
let pipeline = (**entry)
.downcast_ref::<P>()
.unwrap_or_else(|| panic!("PipelineCache type mismatch: run::<{}>() but init used a different pipeline type", std::any::type_name::<P>(),));
pipeline.run(executor, args)
}
/// The executor the cache was initialized with, or `None` when no GPU is available.
pub fn executor(&self) -> Option<&WgpuExecutor> {
self.executor.get()
}
/// Runs the pipeline, or returns `None` when it was never initialized because no GPU is available.
pub fn try_run<P: Pipeline>(&self, args: &P::Args<'_>) -> Option<P::Out> {
self.executor.get()?;
Some(self.run::<P>(args))
pub fn run<P: Pipeline>(&self, args: &P::Args<'_>) -> Result<P::Out, PipelineError> {
let (Some(executor), Some(entry)) = (self.executor.get(), self.pipeline.get()) else {
return Err(PipelineError::NotInitialized);
};
let pipeline = (**entry).downcast_ref::<P>().ok_or(PipelineError::TypeMismatch { expected: std::any::type_name::<P>() })?;
Ok(pipeline.run(executor, args))
}
}
@@ -51,3 +39,11 @@ impl std::fmt::Debug for PipelineCache {
f.debug_struct("PipelineCache").field("initialized", &self.pipeline.get().is_some()).finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum PipelineError {
#[error("The GPU pipeline was not set up")]
NotInitialized,
#[error("The GPU pipeline cache holds a pipeline other than `{expected}`")]
TypeMismatch { expected: &'static str },
}
@@ -1 +1,10 @@
pub mod raster_kernel_runtime;
use crate::shader_runtime::per_pixel_adjust_runtime::PerPixelAdjustShaderRuntime;
pub mod per_pixel_adjust_runtime;
pub const FULLSCREEN_VERTEX_SHADER_NAME: &str = "fullscreen_vertex_fullscreen_vertex";
#[derive(Default)]
pub struct ShaderRuntime {
per_pixel_adjust: PerPixelAdjustShaderRuntime,
}
@@ -0,0 +1,234 @@
use crate::shader_runtime::FULLSCREEN_VERTEX_SHADER_NAME;
use crate::{Buffer, WgpuContext, WgpuExecutor};
use core_types::list::{Item, List};
use core_types::shaders::buffer_struct::BufferStruct;
use glam::UVec2;
use raster_types::{GPU, Raster};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Mutex;
use wgpu::util::BufferInitDescriptor;
use wgpu::{
BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingType, BufferBinding, BufferBindingType, BufferUsages, ColorTargetState, Face,
FragmentState, FrontFace, LoadOp, Operations, PipelineLayoutDescriptor, PolygonMode, PrimitiveState, PrimitiveTopology, RenderPassColorAttachment, RenderPassDescriptor, RenderPipelineDescriptor,
ShaderModuleDescriptor, ShaderSource, ShaderStages, StoreOp, TextureFormat, TextureSampleType, TextureViewDescriptor, TextureViewDimension, VertexState,
};
pub struct PerPixelAdjustShaderRuntime {
// TODO: PerPixelAdjustGraphicsPipeline already contains the key as `name`
pipeline_cache: Mutex<HashMap<String, PerPixelAdjustGraphicsPipeline>>,
}
impl Default for PerPixelAdjustShaderRuntime {
fn default() -> Self {
Self::new()
}
}
impl PerPixelAdjustShaderRuntime {
pub fn new() -> Self {
Self {
pipeline_cache: Mutex::new(HashMap::new()),
}
}
}
impl WgpuExecutor {
pub fn run_per_pixel_adjust<T: BufferStruct>(&self, shaders: &Shaders<'_>, textures: List<Raster<GPU>>, args: Option<&T>) -> List<Raster<GPU>> {
let mut cache = self.inner.shader_runtime.per_pixel_adjust.pipeline_cache.lock().unwrap();
let pipeline = cache
.entry(shaders.fragment_shader_name.to_owned())
.or_insert_with(|| PerPixelAdjustGraphicsPipeline::new(self.context(), shaders));
let arg_buffer = args.map(|args| {
self.create_buffer_init(&BufferInitDescriptor {
label: Some(&format!("{} arg buffer", pipeline.name.as_str())),
usage: BufferUsages::STORAGE,
contents: bytemuck::bytes_of(&T::write(*args)),
})
});
pipeline.dispatch(self, textures, arg_buffer)
}
}
pub struct Shaders<'a> {
pub wgsl_shader: &'a str,
pub fragment_shader_name: &'a str,
pub has_uniform: bool,
}
pub struct PerPixelAdjustGraphicsPipeline {
name: String,
has_uniform: bool,
pipeline: wgpu::RenderPipeline,
}
impl PerPixelAdjustGraphicsPipeline {
pub fn new(context: &WgpuContext, info: &Shaders) -> Self {
let device = &context.device;
let name = info.fragment_shader_name.to_owned();
let fragment_name = &name;
let fragment_name = &fragment_name[(fragment_name.find("::").unwrap() + 2)..];
let fragment_name = fragment_name.replace("::", "_");
let shader_module = device.create_shader_module(ShaderModuleDescriptor {
label: Some(&format!("PerPixelAdjust {name} wgsl shader")),
source: ShaderSource::Wgsl(Cow::Borrowed(info.wgsl_shader)),
});
let entries: &[_] = if info.has_uniform {
&[
BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
ty: BindingType::Buffer {
ty: BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::FRAGMENT,
ty: BindingType::Texture {
sample_type: TextureSampleType::Float { filterable: false },
view_dimension: TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
]
} else {
&[BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::FRAGMENT,
ty: BindingType::Texture {
sample_type: TextureSampleType::Float { filterable: false },
view_dimension: TextureViewDimension::D2,
multisampled: false,
},
count: None,
}]
};
let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
label: Some(&format!("PerPixelAdjust {name} PipelineLayout")),
bind_group_layouts: &[Some(&device.create_bind_group_layout(&BindGroupLayoutDescriptor {
label: Some(&format!("PerPixelAdjust {name} BindGroupLayout 0")),
entries,
}))],
..Default::default()
});
let pipeline = device.create_render_pipeline(&RenderPipelineDescriptor {
label: Some(&format!("PerPixelAdjust {name} Pipeline")),
layout: Some(&pipeline_layout),
vertex: VertexState {
module: &shader_module,
entry_point: Some(FULLSCREEN_VERTEX_SHADER_NAME),
compilation_options: Default::default(),
buffers: &[],
},
primitive: PrimitiveState {
topology: PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: FrontFace::Ccw,
cull_mode: Some(Face::Back),
unclipped_depth: false,
polygon_mode: PolygonMode::Fill,
conservative: false,
},
depth_stencil: None,
multisample: Default::default(),
multiview_mask: None,
fragment: Some(FragmentState {
module: &shader_module,
entry_point: Some(&fragment_name),
compilation_options: Default::default(),
targets: &[Some(ColorTargetState {
format: TextureFormat::Rgba8UnormSrgb,
blend: None,
write_mask: Default::default(),
})],
}),
cache: None,
});
Self {
pipeline,
name,
has_uniform: info.has_uniform,
}
}
pub fn dispatch(&self, executor: &WgpuExecutor, textures: List<Raster<GPU>>, arg_buffer: Option<Buffer>) -> List<Raster<GPU>> {
assert_eq!(self.has_uniform, arg_buffer.is_some());
let device = &executor.context().device;
let name = self.name.as_str();
let mut cmd = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some(&format!("{name} cmd encoder")),
});
let out = (0..textures.len())
.map(|index| {
let element = textures.element(index).unwrap();
let tex_in = &element.texture;
let view_in = tex_in.create_view(&TextureViewDescriptor::default());
let format = tex_in.format();
let entries: &[_] = if let Some(arg_buffer) = arg_buffer.as_ref() {
&[
BindGroupEntry {
binding: 0,
resource: BindingResource::Buffer(BufferBinding {
buffer: arg_buffer,
offset: 0,
size: None,
}),
},
BindGroupEntry {
binding: 1,
resource: BindingResource::TextureView(&view_in),
},
]
} else {
&[BindGroupEntry {
binding: 0,
resource: BindingResource::TextureView(&view_in),
}]
};
let bind_group = device.create_bind_group(&BindGroupDescriptor {
label: Some(&format!("{name} bind group")),
// `get_bind_group_layout` allocates unnecessary memory, we could create it manually to not do that
layout: &self.pipeline.get_bind_group_layout(0),
entries,
});
let tex_out = executor.request_texture_with_format(UVec2::new(tex_in.width(), tex_in.height()), format);
let view_out = tex_out.create_view(&TextureViewDescriptor::default());
let mut rp = cmd.begin_render_pass(&RenderPassDescriptor {
label: Some(&format!("{name} render pipeline")),
color_attachments: &[Some(RenderPassColorAttachment {
view: &view_out,
resolve_target: None,
ops: Operations {
// should be dont_care but wgpu doesn't expose that
load: LoadOp::Clear(wgpu::Color::BLACK),
store: StoreOp::Store,
},
depth_slice: None,
})],
..Default::default()
});
rp.set_pipeline(&self.pipeline);
rp.set_bind_group(0, Some(&bind_group), &[]);
rp.draw(0..3, 0..1);
let attributes = textures.clone_item_attributes(index);
Item::from_parts(Raster::new_gpu(tex_out), attributes)
})
.collect::<List<_>>();
executor.context().queue.submit([cmd.finish()]);
out
}
}
@@ -1,10 +0,0 @@
@vertex
fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
let corner = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u));
return vec4<f32>(corner * 2. - 1., 0., 1.);
}
@fragment
fn fragment(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
return kernel(vec2<i32>(position.xy));
}
@@ -1,34 +0,0 @@
@group(0) @binding(BINDING) var INPUT_texture: texture_2d<f32>;
fn INPUT_size() -> vec2<i32> {
return vec2<i32>(kernel_frame[PLACEMENT].zw);
}
fn INPUT_load(coord: vec2<i32>) -> vec4<f32> {
return textureLoad(INPUT_texture, clamp(coord, vec2<i32>(0), INPUT_size() - 1), 0);
}
fn INPUT_premultiplied(texel: vec2<i32>) -> vec4<f32> {
if any(texel < vec2<i32>(0)) || any(texel >= INPUT_size()) {
return vec4<f32>(0.);
}
let color = textureLoad(INPUT_texture, texel, 0);
return vec4<f32>(color.rgb * color.a, color.a);
}
fn INPUT_at(coord: vec2<i32>) -> vec4<f32> {
let axes = kernel_frame[AXES];
let center = vec2<f32>(coord) + 0.5;
let texel = axes.xy * center.x + axes.zw * center.y + kernel_frame[PLACEMENT].xy - 0.5;
let base = floor(texel);
let t = texel - base;
let corner = vec2<i32>(base);
let top = mix(INPUT_premultiplied(corner), INPUT_premultiplied(corner + vec2<i32>(1, 0)), t.x);
let bottom = mix(INPUT_premultiplied(corner + vec2<i32>(0, 1)), INPUT_premultiplied(corner + vec2<i32>(1, 1)), t.x);
let premultiplied = mix(top, bottom, t.y);
if premultiplied.a <= 0. {
return vec4<f32>(0.);
}
return vec4<f32>(premultiplied.rgb / premultiplied.a, premultiplied.a);
}
@@ -1,3 +0,0 @@
fn INPUT_sample(texel: vec2<f32>) -> vec4<f32> {
return textureSampleLevel(INPUT_texture, raster_kernel_sampler, texel / vec2<f32>(INPUT_size()), 0.);
}
@@ -1,390 +0,0 @@
use crate::{WgpuExecutor, WgpuPipeline};
use core_types::Color;
use glam::{DAffine2, UVec2};
use raster_types::{GPU, Raster};
use std::any::TypeId;
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, VecDeque};
use std::hash::{Hash, Hasher};
use std::sync::Mutex;
use wgpu::util::BufferInitDescriptor;
/// An input raster of a kernel, with the affine mapping output pixel coordinates to the input's texel coordinates.
pub struct RasterKernelInput<'a> {
pub raster: &'a Raster<GPU>,
pub output_to_texel: DAffine2,
}
/// 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] },
}
impl RasterKernelLookup<'_> {
fn data(&self) -> &[Color] {
match self {
Self::Lut1d(data) | Self::Lut3d { data, .. } => data,
}
}
fn extent(&self) -> wgpu::Extent3d {
match self {
Self::Lut1d(data) => wgpu::Extent3d {
width: data.len() as u32,
height: 1,
depth_or_array_layers: 1,
},
Self::Lut3d { size, .. } => wgpu::Extent3d {
width: *size,
height: *size,
depth_or_array_layers: *size,
},
}
}
fn dimension(&self) -> (wgpu::TextureDimension, wgpu::TextureViewDimension) {
match self {
Self::Lut1d(_) => (wgpu::TextureDimension::D2, wgpu::TextureViewDimension::D2),
Self::Lut3d { .. } => (wgpu::TextureDimension::D3, wgpu::TextureViewDimension::D3),
}
}
fn content_hash(&self) -> u64 {
let mut hasher = DefaultHasher::new();
let extent = self.extent();
(extent.width, extent.height, extent.depth_or_array_layers, matches!(self, Self::Lut3d { .. })).hash(&mut hasher);
bytemuck::cast_slice::<Color, u8>(self.data()).hash(&mut hasher);
hasher.finish()
}
}
/// One run of a raster kernel, writing a texture of `output_size` in `output_format`.
///
/// `wgsl` must define `fn kernel(coord: vec2<i32>) -> vec4<f32>`, and reads its parameters from `uniform_params`, the 32-bit `params` packed into `vec4<u32>` slots.
/// It 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.
/// With `filtered`, it may also call `input_i_sample(texel)`, sampling the input bilinearly at texel coordinates, whose texel centers lie at +0.5, clamped to its edge,
/// which requires every input to be in a filterable format such as `Rgba16Float` rather than [`crate::RASTER_FORMAT`].
/// It declares the texture of each of the `lookups` itself, the `k`th at binding `2 + inputs + k`.
/// An empty input reads as transparent with a size of zero, and an empty `output_size` gives the empty raster without running the kernel.
/// Every run of the same `kernel` must have the same number of inputs, the same kinds of lookups, and the same `filtered`.
pub struct RasterKernelArgs<'a> {
pub kernel: TypeId,
pub label: &'static str,
pub wgsl: fn() -> String,
pub params: Vec<u32>,
pub inputs: Vec<RasterKernelInput<'a>>,
pub lookups: Vec<RasterKernelLookup<'a>>,
pub filtered: bool,
pub output_size: UVec2,
pub output_format: wgpu::TextureFormat,
}
struct KernelPipeline {
bind_group_layout: wgpu::BindGroupLayout,
pipeline: wgpu::RenderPipeline,
}
/// The number of lookup textures kept uploaded, the most recently used first, so a kernel run again with the same table skips the upload.
const LOOKUP_CACHE_SIZE: usize = 16;
pub struct RasterKernelRuntime {
pipelines: Mutex<HashMap<(TypeId, wgpu::TextureFormat), KernelPipeline>>,
lookups: Mutex<VecDeque<(u64, wgpu::Texture)>>,
sampler: wgpu::Sampler,
empty_input: wgpu::Texture,
}
impl RasterKernelRuntime {
fn lookup_texture(&self, executor: &WgpuExecutor, lookup: &RasterKernelLookup<'_>) -> wgpu::Texture {
let hash = lookup.content_hash();
let mut lookups = self.lookups.lock().unwrap();
if let Some(index) = lookups.iter().position(|(cached, _)| *cached == hash) {
let entry = lookups.remove(index).unwrap();
let texture = entry.1.clone();
lookups.push_front(entry);
return texture;
}
let size = lookup.extent();
let texture = executor.context().device.create_texture(&wgpu::TextureDescriptor {
label: Some("raster_kernel_lookup"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: lookup.dimension().0,
format: wgpu::TextureFormat::Rgba32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
executor.context().queue.write_texture(
texture.as_image_copy(),
bytemuck::cast_slice(lookup.data()),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(16 * size.width),
rows_per_image: Some(size.height),
},
size,
);
lookups.push_front((hash, texture.clone()));
lookups.truncate(LOOKUP_CACHE_SIZE);
texture
}
}
impl WgpuPipeline for RasterKernelRuntime {
type Args<'a> = RasterKernelArgs<'a>;
type Out = Raster<GPU>;
fn create(executor: &WgpuExecutor) -> Self {
let sampler = executor.context().device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("raster_kernel_sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let empty_input = executor.context().device.create_texture(&wgpu::TextureDescriptor {
label: Some("raster_kernel_empty_input"),
size: wgpu::Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
Self {
pipelines: Mutex::default(),
lookups: Mutex::default(),
sampler,
empty_input,
}
}
fn run(&self, executor: &WgpuExecutor, args: &RasterKernelArgs<'_>) -> Raster<GPU> {
if args.output_size.x == 0 || args.output_size.y == 0 {
return Raster::default();
}
let device = &executor.context().device;
let param_slots = slots(args.params.len());
let mut pipelines = self.pipelines.lock().unwrap();
let kernel_pipeline = pipelines.entry((args.kernel, args.output_format)).or_insert_with(|| create_pipeline(device, args, param_slots));
let mut params = args.params.clone();
params.resize(param_slots * 4, 0);
let params = executor.create_buffer_init(&BufferInitDescriptor {
label: Some(args.label),
contents: bytemuck::cast_slice(&params),
usage: wgpu::BufferUsages::UNIFORM,
});
let frame = executor.create_buffer_init(&BufferInitDescriptor {
label: Some(args.label),
contents: bytemuck::cast_slice(&frame_data(args)),
usage: wgpu::BufferUsages::UNIFORM,
});
let input_views = args
.inputs
.iter()
.map(|input| input.raster.texture().map_or(&self.empty_input, |texture| texture).create_view(&wgpu::TextureViewDescriptor::default()))
.collect::<Vec<_>>();
let lookup_views = args
.lookups
.iter()
.map(|lookup| self.lookup_texture(executor, lookup).create_view(&wgpu::TextureViewDescriptor::default()))
.collect::<Vec<_>>();
let mut entries = vec![
wgpu::BindGroupEntry {
binding: 0,
resource: params.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: frame.as_entire_binding(),
},
];
entries.extend(input_views.iter().enumerate().map(|(index, view)| wgpu::BindGroupEntry {
binding: 2 + index as u32,
resource: wgpu::BindingResource::TextureView(view),
}));
entries.extend(lookup_views.iter().enumerate().map(|(index, view)| wgpu::BindGroupEntry {
binding: (2 + args.inputs.len() + index) as u32,
resource: wgpu::BindingResource::TextureView(view),
}));
if args.filtered {
entries.push(wgpu::BindGroupEntry {
binding: sampler_binding(args),
resource: wgpu::BindingResource::Sampler(&self.sampler),
});
}
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some(args.label),
layout: &kernel_pipeline.bind_group_layout,
entries: &entries,
});
let output = executor.request_texture_with_format(args.output_size, args.output_format);
let output_view = output.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some(args.label) });
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some(args.label),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &output_view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
..Default::default()
});
pass.set_pipeline(&kernel_pipeline.pipeline);
pass.set_bind_group(0, &bind_group, &[]);
pass.draw(0..3, 0..1);
}
executor.context().queue.submit([encoder.finish()]);
Raster::new_gpu(output)
}
}
fn create_pipeline(device: &wgpu::Device, args: &RasterKernelArgs<'_>, param_slots: usize) -> KernelPipeline {
let uniform = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let texture = |binding, view_dimension, filterable| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable },
view_dimension,
multisampled: false,
},
count: None,
};
let mut entries = vec![uniform(0), uniform(1)];
entries.extend((0..args.inputs.len()).map(|index| texture(2 + index as u32, wgpu::TextureViewDimension::D2, args.filtered)));
entries.extend(
args.lookups
.iter()
.enumerate()
.map(|(index, lookup)| texture((2 + args.inputs.len() + index) as u32, lookup.dimension().1, false)),
);
if args.filtered {
entries.push(wgpu::BindGroupLayoutEntry {
binding: sampler_binding(args),
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
});
}
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some(args.label),
entries: &entries,
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some(args.label),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let source = format!("{}\n{}\n\n{}", bindings_wgsl(param_slots, args), (args.wgsl)(), include_str!("raster_kernel_entry.wgsl"));
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(args.label),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(args.label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &module,
entry_point: Some("vertex"),
compilation_options: Default::default(),
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fragment"),
compilation_options: Default::default(),
targets: &[Some(args.output_format.into())],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
KernelPipeline { bind_group_layout, pipeline }
}
/// The frame uniform: the output size, then for each input its affine's matrix columns, translation, and size.
fn frame_data(args: &RasterKernelArgs<'_>) -> Vec<f32> {
let mut data = vec![args.output_size.x as f32, args.output_size.y as f32, 0., 0.];
for input in &args.inputs {
let affine = input.output_to_texel;
let size = input.raster.size();
data.extend([affine.matrix2.x_axis.x, affine.matrix2.x_axis.y, affine.matrix2.y_axis.x, affine.matrix2.y_axis.y].map(|value| value as f32));
data.extend([affine.translation.x as f32, affine.translation.y as f32, size.x as f32, size.y as f32]);
}
data
}
/// The binding of the sampler of a `filtered` kernel's inputs, after its lookups.
fn sampler_binding(args: &RasterKernelArgs<'_>) -> u32 {
(2 + args.inputs.len() + args.lookups.len()) as u32
}
fn bindings_wgsl(param_slots: usize, args: &RasterKernelArgs<'_>) -> String {
let inputs = args.inputs.len();
let frame_slots = 1 + 2 * inputs;
let mut source = format!(
"@group(0) @binding(0) var<uniform> uniform_params: array<vec4<u32>, {param_slots}>;\n@group(0) @binding(1) var<uniform> kernel_frame: array<vec4<f32>, {frame_slots}>;\n\nfn output_size() -> vec2<i32> {{\n\treturn vec2<i32>(kernel_frame[0].xy);\n}}\n"
);
if args.filtered {
source += &format!("\n@group(0) @binding({}) var raster_kernel_sampler: sampler;\n", sampler_binding(args));
}
for index in 0..inputs {
let mut input = include_str!("raster_kernel_input.wgsl").to_string();
if args.filtered {
input += include_str!("raster_kernel_input_sample.wgsl");
}
source += &input
.replace("INPUT", &format!("input_{index}"))
.replace("BINDING", &(2 + index).to_string())
.replace("AXES", &(1 + 2 * index).to_string())
.replace("PLACEMENT", &(2 + 2 * index).to_string());
}
source
}
/// The `vec4<u32>` slot count holding `params` 32-bit values, at least one since WGSL arrays can't be empty.
fn slots(params: usize) -> usize {
params.div_ceil(4).max(1)
}
@@ -4,32 +4,39 @@ use core_types::color::SRGBA8;
use core_types::list::{Item, List};
use core_types::ops::{Convert, ConvertAsync};
use core_types::transform::Footprint;
use half::f16;
use raster_types::Image;
use raster_types::{CPU, GPU, Raster, Storage};
use wgpu::Extent3d;
use raster_types::{CPU, GPU, Raster, Texture};
use wgpu::{Extent3d, TextureFormat};
/// Uploads CPU image data to a GPU texture
fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raster<CPU>) -> Raster<GPU> {
if image.is_empty() {
return Raster::default();
fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raster<CPU>) -> Texture {
let texture = executor.request_texture_with_format(glam::UVec2::new(image.width, image.height), TextureFormat::Rgba8UnormSrgb);
if image.width == 0 || image.height == 0 {
queue.write_texture(
texture.as_image_copy(),
bytemuck::bytes_of(&SRGBA8::TRANSPARENT),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4),
rows_per_image: Some(1),
},
Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
);
return texture;
}
let format = executor.raster_format();
let texture = executor.request_texture_with_format(glam::UVec2::new(image.width, image.height), format);
let half_floats: Vec<[f16; 4]>;
let (bytes, bytes_per_pixel) = if format == crate::FALLBACK_RASTER_FORMAT {
half_floats = image.data.iter().map(|color| color.to_vec4().to_array().map(f16::from_f32)).collect();
(bytemuck::cast_slice(half_floats.as_slice()), 8)
} else {
(bytemuck::cast_slice(image.data.as_slice()), 16)
};
let rgba8_data: Vec<SRGBA8> = image.data.iter().map(|x| (*x).into()).collect();
queue.write_texture(
texture.as_image_copy(),
bytes,
bytemuck::cast_slice(rgba8_data.as_slice()),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(bytes_per_pixel * image.width),
bytes_per_row: Some(4 * image.width),
rows_per_image: Some(image.height),
},
Extent3d {
@@ -38,35 +45,29 @@ fn upload_to_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Raste
depth_or_array_layers: 1,
},
);
Raster::new_gpu(texture)
texture
}
/// Converts a Raster<GPU> texture to Raster<CPU> by downloading the underlying texture data.
///
/// Assumptions:
/// - 2D texture, mip level 0
/// - 4 bytes-per-pixel RGBA8, or `RASTER_FORMAT` or `FALLBACK_RASTER_FORMAT`
/// - 4 bytes-per-pixel RGBA8
/// - Texture has COPY_SRC usage
struct RasterGpuToRasterCpuConverter {
buffer: Buffer,
width: u32,
height: u32,
format: wgpu::TextureFormat,
unpadded_bytes_per_row: u32,
padded_bytes_per_row: u32,
_source: raster_types::Texture,
}
impl RasterGpuToRasterCpuConverter {
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Option<Self> {
let texture = data_gpu.texture()?;
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
let texture = data_gpu.data();
let width = texture.width();
let height = texture.height();
let format = texture.format();
let bytes_per_pixel = match format {
crate::RASTER_FORMAT => 16,
crate::FALLBACK_RASTER_FORMAT => 8,
_ => 4,
};
let bytes_per_pixel = 4; // RGBA8
let unpadded_bytes_per_row = width * bytes_per_pixel;
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
@@ -101,16 +102,15 @@ impl RasterGpuToRasterCpuConverter {
},
);
Some(Self {
Self {
buffer,
width,
height,
format,
unpadded_bytes_per_row,
padded_bytes_per_row,
// Keep source texture alive
_source: texture.clone(),
})
_source: data_gpu.texture.clone(),
}
}
async fn convert(self, device: &wgpu::Device) -> Result<Raster<CPU>, wgpu::BufferAsyncError> {
@@ -154,20 +154,8 @@ impl RasterGpuToRasterCpuConverter {
for row in 0..self.height as usize {
let start = row * row_stride;
let row_slice = &view[start..start + row_bytes];
match self.format {
crate::RASTER_FORMAT => cpu_data.extend(bytemuck::pod_collect_to_vec::<u8, Color>(row_slice)),
crate::FALLBACK_RASTER_FORMAT => {
let pixels = bytemuck::pod_collect_to_vec::<u8, [f16; 4]>(row_slice);
cpu_data.extend(pixels.iter().map(|pixel| {
let [red, green, blue, alpha] = pixel.map(f16::to_f32);
Color::from_rgbaf32_unchecked(red, green, blue, alpha)
}));
}
_ => {
for px in row_slice.chunks_exact(4) {
cpu_data.push(SRGBA8::new(px[0], px[1], px[2], px[3]).into());
}
}
for px in row_slice.chunks_exact(4) {
cpu_data.push(SRGBA8::new(px[0], px[1], px[2], px[3]).into());
}
}
@@ -238,7 +226,9 @@ impl Convert<List<Raster<GPU>>, WgpuExecutor> for List<Raster<CPU>> {
.into_iter()
.map(|row| {
let (image, attributes) = row.into_parts();
Item::from_parts(upload_to_texture(&executor, &queue, &image), attributes)
let texture = upload_to_texture(&executor, &queue, &image);
Item::from_parts(Raster::new_gpu(texture), attributes)
})
.collect();
@@ -251,10 +241,10 @@ impl Convert<List<Raster<GPU>>, WgpuExecutor> for List<Raster<CPU>> {
impl Convert<Raster<GPU>, WgpuExecutor> for Raster<CPU> {
fn convert(self, _: Footprint, executor: WgpuExecutor) -> Raster<GPU> {
let queue = executor.context().queue.lock();
let raster = upload_to_texture(&executor, &queue, &self);
let texture = upload_to_texture(&executor, &queue, &self);
queue.submit([]);
raster
Raster::new_gpu(texture)
}
}
@@ -288,12 +278,7 @@ impl ConvertAsync<List<Raster<CPU>>, WgpuExecutor> for List<Raster<GPU>> {
let mut map_futures = Vec::new();
for converter in converters {
map_futures.push(async move {
match converter {
Some(converter) => converter.convert(device).await,
None => Ok(Raster::default()),
}
});
map_futures.push(converter.convert(device));
}
let map_results = futures::future::try_join_all(map_futures)
@@ -326,7 +311,6 @@ impl ConvertAsync<Raster<CPU>, WgpuExecutor> for Raster<GPU> {
queue.submit([encoder.finish()]);
let Some(converter) = converter else { return Raster::default() };
converter.convert(device).await.expect("Failed to download texture data")
}
}
@@ -29,16 +29,6 @@ fn unpremultiply(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f3
return vec4<f32>(color.rgb / color.a, color.a);
}
@fragment
fn unpremultiply_to_linear(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let color = textureLoad(source, vec2<i32>(position.xy), 0);
if color.a <= 0. {
return vec4<f32>(0.);
}
return vec4<f32>(srgb_to_linear(color.rgb / color.a), color.a);
}
@fragment
fn premultiply(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
var color = textureLoad(source, vec2<i32>(position.xy), 0);
@@ -54,9 +44,3 @@ fn linear_to_srgb(linear: vec3<f32>) -> vec3<f32> {
let high = 1.055 * pow(linear, vec3<f32>(1. / 2.4)) - 0.055;
return select(high, low, linear <= vec3<f32>(0.0031308));
}
fn srgb_to_linear(srgb: vec3<f32>) -> vec3<f32> {
let low = srgb / 12.92;
let high = pow((srgb + 0.055) / 1.055, vec3<f32>(2.4));
return select(high, low, srgb <= vec3<f32>(0.04045));
}
@@ -42,7 +42,7 @@ pub struct VelloCanvas {
}
impl VelloRenderer {
pub(crate) fn new(device: &wgpu::Device, raster_format: wgpu::TextureFormat) -> Self {
pub(crate) fn new(device: &wgpu::Device) -> Self {
let render_target_config = RenderTargetConfig {
format: TEXTURE_FORMAT,
width: 1,
@@ -59,11 +59,11 @@ impl VelloRenderer {
Self {
gpu: Mutex::new(Renderer::new_with(device, &render_target_config, settings)),
alpha_conversion: AlphaConversion::new(device, raster_format),
alpha_conversion: AlphaConversion::new(device),
}
}
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target`, a texture of `size` with straight alpha that is either `Rgba8Unorm` holding sRGB values or the executor's raster format holding linear-light values.
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target` (an `Rgba8Unorm` texture of `size` with straight alpha).
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
#[expect(clippy::too_many_arguments)]
pub(crate) fn render(
@@ -135,12 +135,10 @@ impl VelloRenderer {
[(UVec2::ZERO, UVec2::new(size.x, top)), (UVec2::new(0, top), UVec2::new(size.x, size.y - top))]
};
let halves = halves.map(|(offset, half_size)| {
// In the target's own format, so the half can be copied into it
let half_target = create_texture_with_format(
let half_target = create_texture(
device,
"vello_gpu_split_target",
half_size,
target.format(),
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
);
let half_view = Affine::translate((-(offset.x as f64), -(offset.y as f64))) * view;
@@ -269,7 +267,7 @@ impl VelloRenderer {
if rendered.is_ok() {
let target_view = target.create_view(&wgpu::TextureViewDescriptor::default());
self.alpha_conversion.unpremultiply(device, &mut encoder, &premultiplied_view, &target_view, target.format());
self.alpha_conversion.unpremultiply(device, &mut encoder, &premultiplied_view, &target_view);
}
// Submitted even after a failure, since it also prepares the textures of the scene's images
@@ -363,8 +361,7 @@ impl ImageTextures {
if let SceneImage::Texture(source) = image {
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
let loads_linear_light = source.format().is_srgb() || matches!(source.format(), crate::RASTER_FORMAT | crate::FALLBACK_RASTER_FORMAT);
alpha_conversion.premultiply(device, encoder, &source_view, loads_linear_light, &view);
alpha_conversion.premultiply(device, encoder, &source_view, source.format().is_srgb(), &view);
}
Some(view)
@@ -485,10 +482,6 @@ fn clear_texture(encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView) {
}
fn create_texture(device: &wgpu::Device, label: &str, size: UVec2, usage: wgpu::TextureUsages) -> wgpu::Texture {
create_texture_with_format(device, label, size, TEXTURE_FORMAT, usage)
}
fn create_texture_with_format(device: &wgpu::Device, label: &str, size: UVec2, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
@@ -499,7 +492,7 @@ fn create_texture_with_format(device: &wgpu::Device, label: &str, size: UVec2, f
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
format: TEXTURE_FORMAT,
usage,
view_formats: &[],
})
@@ -509,8 +502,6 @@ fn create_texture_with_format(device: &wgpu::Device, label: &str, size: UVec2, f
struct AlphaConversion {
bind_group_layout: wgpu::BindGroupLayout,
unpremultiply_pipeline: wgpu::RenderPipeline,
/// Unpremultiplies into a linear-light target in the executor's raster format.
unpremultiply_to_linear_pipeline: wgpu::RenderPipeline,
premultiply_pipeline: wgpu::RenderPipeline,
/// The parameters for a source whose format stores linear values.
linear_source_parameters: wgpu::Buffer,
@@ -519,7 +510,7 @@ struct AlphaConversion {
}
impl AlphaConversion {
fn new(device: &wgpu::Device, raster_format: wgpu::TextureFormat) -> Self {
fn new(device: &wgpu::Device) -> Self {
use wgpu::util::DeviceExt;
let shader = device.create_shader_module(wgpu::include_wgsl!("vello_alpha.wgsl"));
@@ -555,7 +546,7 @@ impl AlphaConversion {
immediate_size: 0,
});
let create_pipeline = |label: &str, entry_point: &str, format: wgpu::TextureFormat| {
let create_pipeline = |label: &str, entry_point: &str| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
@@ -570,7 +561,7 @@ impl AlphaConversion {
entry_point: Some(entry_point),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
format: TEXTURE_FORMAT,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
@@ -595,22 +586,16 @@ impl AlphaConversion {
};
Self {
unpremultiply_pipeline: create_pipeline("vello_unpremultiply_pipeline", "unpremultiply", TEXTURE_FORMAT),
unpremultiply_to_linear_pipeline: create_pipeline("vello_unpremultiply_to_linear_pipeline", "unpremultiply_to_linear", raster_format),
premultiply_pipeline: create_pipeline("vello_premultiply_pipeline", "premultiply", TEXTURE_FORMAT),
unpremultiply_pipeline: create_pipeline("vello_unpremultiply_pipeline", "unpremultiply"),
premultiply_pipeline: create_pipeline("vello_premultiply_pipeline", "premultiply"),
linear_source_parameters: create_parameters("vello_alpha_linear_source", 0),
srgb_source_parameters: create_parameters("vello_alpha_srgb_source", 1),
bind_group_layout,
}
}
fn unpremultiply(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: &wgpu::TextureView, target: &wgpu::TextureView, target_format: wgpu::TextureFormat) {
let pipeline = if target_format == TEXTURE_FORMAT {
&self.unpremultiply_pipeline
} else {
&self.unpremultiply_to_linear_pipeline
};
self.run(device, encoder, pipeline, &self.linear_source_parameters, source, target);
fn unpremultiply(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: &wgpu::TextureView, target: &wgpu::TextureView) {
self.run(device, encoder, &self.unpremultiply_pipeline, &self.linear_source_parameters, source, target);
}
fn premultiply(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, source: &wgpu::TextureView, source_is_srgb: bool, target: &wgpu::TextureView) {
+1
View File
@@ -30,3 +30,4 @@ proc-macro-error2 = "2"
[dev-dependencies]
core-types = { workspace = true }
no-std-types = { workspace = true }
Loaded 100 of 203 files, more files were not shown because too many files have changed in this diff. Show more