mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b8040dab5 | ||
|
|
4b90f41d69 | ||
|
|
892ad740e3 | ||
|
|
0d4f64d326 | ||
|
|
3e58246c0b | ||
|
|
6264e7396a | ||
|
|
9bf8f2469d | ||
|
|
e6cb938ff9 | ||
|
|
95e9c2852e | ||
|
|
06d83843fa | ||
|
|
28e0112504 | ||
|
|
11d097f103 | ||
|
|
78e3166d22 | ||
|
|
661f37fa17 | ||
|
|
aa7ebfc18c | ||
|
|
2be0d1889b | ||
|
|
3b7d46836d | ||
|
|
8f0ef2da8b | ||
|
|
b88eee543a | ||
|
|
e01f602b13 | ||
|
|
8fd36852c1 | ||
|
|
1bfbd8f4f8 | ||
|
|
c698fb157d | ||
|
|
48ee95a802 | ||
|
|
f3edba1603 | ||
|
|
7bb28460cc | ||
|
|
f8c3984b6c | ||
|
|
9ca321fdcf | ||
|
|
d53c990f72 | ||
|
|
ecaa5bb906 | ||
|
|
fc488dd91f | ||
|
|
a12cbea9fb | ||
|
|
7b0298fe96 | ||
|
|
ceb39a2c5b | ||
|
|
b9e0df685f | ||
|
|
135b05bacf | ||
|
|
43316436c2 | ||
|
|
d555a4b3f1 | ||
|
|
b39ec01d7d | ||
|
|
09099bf033 | ||
|
|
ef3b45ae79 | ||
|
|
b574a6c9f3 | ||
|
|
d90cc62bc1 | ||
|
|
82c08464d1 | ||
|
|
a2e62ed47e | ||
|
|
9939966b0e |
No files matched your search
+26
-11
@@ -47,20 +47,24 @@ on:
|
||||
jobs:
|
||||
web:
|
||||
if: github.event_name == 'push' || inputs.web
|
||||
runs-on: [self-hosted, target/wasm]
|
||||
# Fork code always runs on GitHub's own runners, while the `LINUX_RUNNER` repo variable can point the rest at another provider
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
|
||||
permissions:
|
||||
contents: write
|
||||
deployments: write
|
||||
pull-requests: write
|
||||
env:
|
||||
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_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`
|
||||
RUSTC_WRAPPER: sccache
|
||||
SCCACHE_GHA_ENABLED: "true"
|
||||
# Only master pushes write to the compilation cache, so unmerged code can't plant entries that later master builds reuse
|
||||
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `check.yml` (sccache), `.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`
|
||||
SCCACHE_VERSION: "v0.19.0"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
@@ -82,7 +86,12 @@ jobs:
|
||||
rustflags: ""
|
||||
target: wasm32-unknown-unknown
|
||||
|
||||
- name: 🚧 Install wasm-bindgen-cli and Binaryen wasm-opt
|
||||
- name: 📦 Install sccache
|
||||
uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
|
||||
with:
|
||||
version: ${{ env.SCCACHE_VERSION }}
|
||||
|
||||
- name: 🚧 Install wasm-bindgen-cli, Binaryen wasm-opt, and cargo-about
|
||||
run: |
|
||||
# Extracts into a temporary folder first so a cancelled download can't leave a truncated binary that later runs mistake for a finished install
|
||||
install_release_archive() {
|
||||
@@ -107,6 +116,12 @@ jobs:
|
||||
fi
|
||||
echo "$BINARYEN_DIR/bin" >> "$GITHUB_PATH"
|
||||
|
||||
CARGO_ABOUT_DIR="$HOME/.cache/cargo-about-$CARGO_ABOUT_VERSION"
|
||||
if [ ! -x "$CARGO_ABOUT_DIR/cargo-about" ]; then
|
||||
install_release_archive "https://github.com/EmbarkStudios/cargo-about/releases/download/$CARGO_ABOUT_VERSION/cargo-about-$CARGO_ABOUT_VERSION-x86_64-unknown-linux-musl.tar.gz" "$CARGO_ABOUT_DIR"
|
||||
fi
|
||||
echo "$CARGO_ABOUT_DIR" >> "$GITHUB_PATH"
|
||||
|
||||
- name: 🔀 Choose production deployment environment and insert template
|
||||
id: production-env
|
||||
if: github.event_name == 'push'
|
||||
@@ -127,7 +142,7 @@ jobs:
|
||||
NODE_ENV: production
|
||||
# Split the Wasm binary to fit Cloudflare Pages' file size limit (see `wasmSplitting` in `frontend/vite.config.ts`)
|
||||
SPLIT_WASM: "1"
|
||||
run: mold -run cargo run build web${{ inputs.debug && ' debug' || '' }}
|
||||
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
|
||||
|
||||
- name: 📤 Publish to Cloudflare Pages
|
||||
if: inputs.merge_queue == false
|
||||
@@ -299,7 +314,7 @@ jobs:
|
||||
cd frontend
|
||||
npm run check
|
||||
|
||||
# Runs on a GitHub-hosted runner to keep the self-hosted one free for web builds
|
||||
# A job of its own so its native compile doesn't delay the web build and deploy
|
||||
code-docs:
|
||||
if: github.event_name == 'push' && github.ref != 'refs/tags/latest-stable'
|
||||
runs-on: ubuntu-latest
|
||||
@@ -325,7 +340,7 @@ jobs:
|
||||
|
||||
windows:
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.windows
|
||||
runs-on: windows-latest
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'windows-latest' || vars.WINDOWS_RUNNER || 'windows-latest' }}
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
@@ -535,7 +550,7 @@ jobs:
|
||||
|
||||
mac:
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.mac
|
||||
runs-on: macos-latest
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'macos-latest' || vars.MACOS_RUNNER || 'macos-latest' }}
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
@@ -741,7 +756,7 @@ jobs:
|
||||
|
||||
linux:
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
@@ -3,10 +3,14 @@ name: "Check"
|
||||
on:
|
||||
pull_request: {}
|
||||
merge_group: {}
|
||||
# Checking each master commit also fills the compilation cache, which only master pushes may write to
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
# Cancel a PR's in-progress checks once a newer commit is pushed to it (merge queue refs are unique per entry, so those never cancel each other)
|
||||
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
@@ -111,7 +115,8 @@ jobs:
|
||||
needs: skip-check
|
||||
# Always called with the skip decision passed in, since a skipped caller job reports only as `build` and leaves the required `build / web` check missing.
|
||||
# Like the jobs below, the checks still run if `skip-check` itself fails, since a skipped job counts as passing for required checks.
|
||||
if: ${{ !cancelled() }}
|
||||
# Master pushes are left out because `build.yml` builds and deploys those itself.
|
||||
if: ${{ !cancelled() && github.event_name != 'push' }}
|
||||
uses: ./.github/workflows/build.yml
|
||||
# The called workflow's jobs can only narrow these, so this grants the union of what they request
|
||||
permissions:
|
||||
@@ -125,18 +130,22 @@ jobs:
|
||||
web: ${{ needs.skip-check.outputs.skip != 'true' }}
|
||||
merge_queue: ${{ github.event_name == 'merge_group' }}
|
||||
|
||||
# Run the Rust tests on the self-hosted native runner
|
||||
# Run the Rust tests
|
||||
test:
|
||||
needs: skip-check
|
||||
if: ${{ !cancelled() && needs.skip-check.outputs.skip != 'true' }}
|
||||
runs-on: [self-hosted, target/native]
|
||||
# Fork PRs always run on GitHub's own runners, while the `LINUX_RUNNER` repo variable can point the rest at another provider
|
||||
runs-on: ${{ github.event.pull_request.head.repo.fork && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
|
||||
permissions:
|
||||
contents: read
|
||||
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_DIR: /var/lib/github-actions/.cache/sccache
|
||||
RUSTC_WRAPPER: sccache
|
||||
SCCACHE_GHA_ENABLED: "true"
|
||||
# Only master pushes write to the compilation cache, so unmerged code can't plant entries that later master builds reuse
|
||||
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
|
||||
# NOTICE: keep in sync with the web job in `build.yml`
|
||||
SCCACHE_VERSION: "v0.19.0"
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
@@ -149,6 +158,11 @@ jobs:
|
||||
cache: false
|
||||
rustflags: ""
|
||||
|
||||
- name: 📦 Install sccache
|
||||
uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
|
||||
with:
|
||||
version: ${{ env.SCCACHE_VERSION }}
|
||||
|
||||
- name: 🦀 Fetch Rust dependencies
|
||||
run: cargo fetch --locked
|
||||
|
||||
@@ -156,7 +170,7 @@ jobs:
|
||||
env:
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
run: mold -run cargo test --all-features
|
||||
run: cargo test --all-features
|
||||
|
||||
# Rust format check on GitHub runner
|
||||
rust-fmt:
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
Usage: $0 <owner> <repo> <branch> <target-path> <artifact-file> <commit-message> <github-token>
|
||||
|
||||
Arguments:
|
||||
owner : GitHub user or organization of the target repo
|
||||
repo : Target repo name
|
||||
branch : Branch name (e.g. main)
|
||||
target-path : Full path (including folders + filename) in the target repo where to upload
|
||||
artifact-file : Local file path to upload
|
||||
commit-message : Commit message for creating/updating the file
|
||||
github-token : GitHub token (PAT or equivalent) with write access to the target repo
|
||||
|
||||
This will perform a GitHub API PUT to /repos/{owner}/{repo}/contents/{target-path}.
|
||||
If a file already exists at that path, it will auto-detect the SHA and update; otherwise it will create a new one.
|
||||
EOF
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [ $# -ne 7 ]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
OWNER="$1"
|
||||
REPO="$2"
|
||||
BRANCH="$3"
|
||||
TARGET_PATH="$4"
|
||||
ARTIFACT_PATH="$5"
|
||||
COMMIT_MSG="$6"
|
||||
TOKEN="$7"
|
||||
|
||||
if [ ! -f "$ARTIFACT_PATH" ]; then
|
||||
echo "Error: artifact file not found: $ARTIFACT_PATH" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LOCAL_SHA=$(git hash-object "$ARTIFACT_PATH")
|
||||
echo "Local blob SHA: $LOCAL_SHA"
|
||||
|
||||
GET_URL="https://api.github.com/repos/${OWNER}/${REPO}/contents/${TARGET_PATH}?ref=${BRANCH}"
|
||||
GET_RESPONSE=$(curl -s -H "Authorization: token ${TOKEN}" "$GET_URL")
|
||||
|
||||
REMOTE_SHA=$(echo "$GET_RESPONSE" | jq -r .sha 2>/dev/null || echo "")
|
||||
|
||||
if [ "$REMOTE_SHA" != "null" ] && [ -n "$REMOTE_SHA" ]; then
|
||||
echo "Remote blob SHA: $REMOTE_SHA"
|
||||
if [ "$LOCAL_SHA" = "$REMOTE_SHA" ]; then
|
||||
echo "The remote file is identical. Skipping upload."
|
||||
exit 0
|
||||
else
|
||||
echo "Remote file differs. Preparing to upload."
|
||||
fi
|
||||
else
|
||||
echo "No existing remote file or no SHA found. Creating."
|
||||
fi
|
||||
|
||||
CONTENT_TMP_BASE64=$(mktemp)
|
||||
if base64 --help 2>&1 | grep -q -- "-w"; then
|
||||
base64 -w 0 "$ARTIFACT_PATH" > "$CONTENT_TMP_BASE64"
|
||||
else
|
||||
base64 "$ARTIFACT_PATH" | tr -d '\n' > "$CONTENT_TMP_BASE64"
|
||||
fi
|
||||
|
||||
PAYLOAD_TMP=$(mktemp)
|
||||
jq -n \
|
||||
--arg message "$COMMIT_MSG" \
|
||||
--arg branch "$BRANCH" \
|
||||
--arg sha "$REMOTE_SHA" \
|
||||
--rawfile content "$CONTENT_TMP_BASE64" \
|
||||
'{
|
||||
message: $message,
|
||||
content: $content,
|
||||
branch: $branch
|
||||
} + (if ($sha != "" and $sha != "null") then { sha: $sha } else {} end)' \
|
||||
> "$PAYLOAD_TMP"
|
||||
|
||||
UPLOAD_RESPONSE=$(curl -s -X PUT \
|
||||
-H "Authorization: token ${TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @"$PAYLOAD_TMP" \
|
||||
"https://api.github.com/repos/${OWNER}/${REPO}/contents/${TARGET_PATH}")
|
||||
|
||||
echo "Upload Response:"
|
||||
echo "$UPLOAD_RESPONSE"
|
||||
|
||||
rm -f "$CONTENT_TMP_BASE64" "$PAYLOAD_TMP"
|
||||
Generated
+35
-29
@@ -2063,6 +2063,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
@@ -2150,6 +2151,7 @@ dependencies = [
|
||||
"rand",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -2162,10 +2164,13 @@ dependencies = [
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"node-macro",
|
||||
"num_enum",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
@@ -2278,7 +2283,6 @@ dependencies = [
|
||||
"base64",
|
||||
"dirs",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"graphite-editor",
|
||||
"graphite-wasm-wrapper",
|
||||
"image",
|
||||
@@ -3500,10 +3504,10 @@ dependencies = [
|
||||
"glam",
|
||||
"graphene-core",
|
||||
"graphic-types",
|
||||
"log",
|
||||
"math-parser",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"thiserror 2.0.18",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -3712,7 +3716,6 @@ dependencies = [
|
||||
"proc-macro-error2",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strum",
|
||||
"syn 2.0.106",
|
||||
]
|
||||
|
||||
@@ -4109,6 +4112,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"smallvec",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.18",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -4619,6 +4623,18 @@ version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d6831663a5098ea164f89cff59c6284e95f4e3c76ce9848d4529f5ccca9bde"
|
||||
|
||||
[[package]]
|
||||
name = "raster-kernels"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"thiserror 2.0.18",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raster-nodes"
|
||||
version = "0.0.0"
|
||||
@@ -4632,11 +4648,13 @@ dependencies = [
|
||||
"graphene-core",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"kurbo",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"num_enum",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
@@ -4658,6 +4676,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
"wgpu",
|
||||
@@ -4825,6 +4844,7 @@ dependencies = [
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"text-nodes",
|
||||
@@ -5617,27 +5637,6 @@ version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "strum"
|
||||
version = "0.27.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
|
||||
dependencies = [
|
||||
"strum_macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strum_macros"
|
||||
version = "0.27.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.106",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
@@ -5784,13 +5783,13 @@ dependencies = [
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"ipsum",
|
||||
"log",
|
||||
"node-macro",
|
||||
"parley",
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"thiserror 2.0.18",
|
||||
"titlecase",
|
||||
"tsify",
|
||||
"unicode-segmentation",
|
||||
@@ -6190,6 +6189,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"rand",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -6451,6 +6451,7 @@ dependencies = [
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.1",
|
||||
"serde",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
@@ -6480,6 +6481,7 @@ dependencies = [
|
||||
"rustc-hash 2.1.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
"tinyvec",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
@@ -6488,7 +6490,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -6503,7 +6505,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -6517,7 +6519,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
@@ -6968,11 +6970,15 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-application-io",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"thiserror 2.0.18",
|
||||
"vello_gpu",
|
||||
"web-sys",
|
||||
"wgpu",
|
||||
|
||||
+4
-5
@@ -84,6 +84,7 @@ core-types = { path = "node-graph/libraries/core-types" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
|
||||
brush-types = { path = "node-graph/libraries/brush-types" }
|
||||
rendering = { path = "node-graph/libraries/rendering" }
|
||||
brush-nodes = { path = "node-graph/nodes/brush" }
|
||||
@@ -241,7 +242,6 @@ tinyvec = { version = "1", features = ["std"] }
|
||||
criterion = { version = "0.7", features = ["html_reports"] }
|
||||
gungraun = { version = "0.18" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "156"
|
||||
cef-dll-sys = "156"
|
||||
@@ -252,7 +252,6 @@ rfd = "0.17"
|
||||
open = "5.3"
|
||||
spin = "0.10"
|
||||
clap = "4.5"
|
||||
|
||||
qrcodegen = "1.8"
|
||||
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
|
||||
scraper = "0.25"
|
||||
@@ -282,6 +281,6 @@ debug = true
|
||||
[patch.crates-io]
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
+4
-1
@@ -111,7 +111,10 @@ impl App {
|
||||
loop {
|
||||
let texture = async_runtime.block_on(node_runtime.run());
|
||||
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
|
||||
let _ = start_render_receiver.recv_timeout(Duration::from_millis(10));
|
||||
let timeout = node_runtime.until_next_frame().unwrap_or(Duration::from_millis(10));
|
||||
if start_render_receiver.recv_timeout(timeout).is_err() {
|
||||
node_runtime.begin_frame();
|
||||
}
|
||||
if exiting_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub(crate) struct RenderState {
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_scene: Option<VelloSceneBuilder>,
|
||||
overlays_scene: Option<VelloSceneBuilder<'static>>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_canvas: VelloCanvas,
|
||||
surface_outdated: bool,
|
||||
@@ -220,7 +220,7 @@ impl RenderState {
|
||||
self.viewport_offset = offset;
|
||||
}
|
||||
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder<'static>) {
|
||||
self.surface_outdated = true;
|
||||
self.overlays_scene = Some(scene);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ gpu = ["graphite-editor/gpu"]
|
||||
# Local dependencies
|
||||
graphite-editor = { workspace = true }
|
||||
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
|
||||
graphene-std = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use graphite_editor::node_graph_executor::NodeRuntime;
|
||||
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
@@ -63,7 +64,7 @@ impl DesktopWrapper {
|
||||
.with_resource_storage(resource_storage)
|
||||
.with_document_store(document_store),
|
||||
)
|
||||
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
|
||||
.with_runtime(RuntimeBuilder::new(Arc::new(Instant::now())).with_wake(runtime_wake).with_application_io(application_io))
|
||||
.with_spawner(spawner)
|
||||
.with_random_seed(random_seed)
|
||||
.build();
|
||||
|
||||
@@ -40,7 +40,7 @@ pub enum DesktopFrontendMessage {
|
||||
WindowUpdateDirectInput {
|
||||
enabled: bool,
|
||||
},
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder>),
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder<'static>>),
|
||||
PersistenceUpdatePreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@ use graphene_resource::{LoadResource, Resource, ResourceHash};
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::session_state::SessionState;
|
||||
use crate::{Gdd, MANIFEST_CODEC, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
|
||||
|
||||
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
|
||||
/// [`crate::manifest::PayloadCodecs`]); export does not re-encode.
|
||||
@@ -158,6 +158,14 @@ impl<L: Layout> Gdd<L> {
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
sink.write_entry(&io::path_for(self.layout.session_basename(), codecs.session), &codecs.session.write_single(&session_state)?)?;
|
||||
// The facts name revs, so a copy without the history carries none.
|
||||
if options.include_history && !self.metadata.is_empty() {
|
||||
let mut lines = Vec::new();
|
||||
for fact in self.metadata.facts() {
|
||||
METADATA_CODEC.append(&mut lines, fact)?;
|
||||
}
|
||||
sink.write_entry(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &lines)?;
|
||||
}
|
||||
|
||||
let working_copy_hashes: std::collections::HashSet<ResourceHash> = self.resource_hashes().await?.into_iter().collect();
|
||||
|
||||
|
||||
@@ -35,6 +35,15 @@ pub async fn iter<T: DeserializeOwned>(container: &AnyContainer, basename: &str,
|
||||
Ok(codec.iter::<T>(bytes.as_slice()).collect::<Result<Vec<_>, _>>()?)
|
||||
}
|
||||
|
||||
/// Same as [`iter`] but skips the values that fail to decode.
|
||||
pub async fn iter_lenient<T: DeserializeOwned>(container: &AnyContainer, basename: &str, codec: Codec) -> Result<Vec<T>, ReadError> {
|
||||
let bytes = read_bytes(container, basename, codec).await?;
|
||||
let values = codec
|
||||
.iter::<T>(bytes.as_slice())
|
||||
.filter_map(|value| value.inspect_err(|error| log::warn!("Skipping an unreadable entry of {basename}: {error}")).ok());
|
||||
Ok(values.collect())
|
||||
}
|
||||
|
||||
/// Whether `{basename}.{ext}` exists for the given codec.
|
||||
pub async fn exists(container: &AnyContainer, basename: &str, codec: Codec) -> bool {
|
||||
container.exists(&path_for(basename, codec)).await
|
||||
|
||||
@@ -12,6 +12,7 @@ pub trait Layout {
|
||||
fn registry_basename(&self) -> &str;
|
||||
fn history_basename(&self) -> &str;
|
||||
fn hot_log_basename(&self) -> &str;
|
||||
fn metadata_basename(&self) -> &str;
|
||||
fn resources_dir(&self) -> &str;
|
||||
fn resource_path(&self, hash: &ResourceHash) -> String;
|
||||
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
|
||||
@@ -39,6 +40,9 @@ impl Layout for GddV1Layout {
|
||||
fn hot_log_basename(&self) -> &str {
|
||||
"hot-log"
|
||||
}
|
||||
fn metadata_basename(&self) -> &str {
|
||||
"metadata"
|
||||
}
|
||||
fn resources_dir(&self) -> &str {
|
||||
"resources"
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ use document_container::backends::folder::FolderBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::{CommitError, NodeMetadataSource};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
|
||||
use document_graph_storage::{Delta, HistoryMetadata, HotOp, PeerId, Registry, Session, UserId};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::ResourceHash;
|
||||
@@ -52,6 +52,8 @@ pub const MANIFEST_CODEC: Codec = Codec::Json;
|
||||
/// want a diffable on-disk representation. Recorded in the manifest at create time and read back on
|
||||
/// open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
|
||||
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
|
||||
/// One fact per line, so recording one only appends.
|
||||
pub const METADATA_CODEC: Codec = Codec::JsonLines;
|
||||
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::Postcard;
|
||||
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::PostcardFrames;
|
||||
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
|
||||
@@ -75,6 +77,8 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
|
||||
/// and synchronous.
|
||||
pub(crate) manifest: Manifest,
|
||||
/// See [`HistoryMetadata`].
|
||||
pub(crate) metadata: HistoryMetadata,
|
||||
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
|
||||
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
|
||||
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
|
||||
@@ -136,6 +140,10 @@ impl<L: Layout> Gdd<L> {
|
||||
true => io::read_single(&working, layout.session_basename(), codecs.session).await?,
|
||||
false => SessionState::default(),
|
||||
};
|
||||
let metadata = match io::exists(&working, layout.metadata_basename(), METADATA_CODEC).await {
|
||||
true => HistoryMetadata::fold(io::iter_lenient(&working, layout.metadata_basename(), METADATA_CODEC).await?),
|
||||
false => HistoryMetadata::default(),
|
||||
};
|
||||
|
||||
let has_registry = io::exists(&working, layout.registry_basename(), codecs.registry).await;
|
||||
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
|
||||
@@ -173,6 +181,7 @@ impl<L: Layout> Gdd<L> {
|
||||
layout,
|
||||
manifest,
|
||||
view_settings: session_state.view_settings,
|
||||
metadata,
|
||||
network_view_settings: session_state.network_view_settings,
|
||||
})
|
||||
}
|
||||
@@ -199,6 +208,7 @@ impl<L: Layout> Gdd<L> {
|
||||
layout,
|
||||
manifest,
|
||||
view_settings: std::collections::BTreeMap::new(),
|
||||
metadata: HistoryMetadata::default(),
|
||||
network_view_settings: std::collections::BTreeMap::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use document_container::AsyncContainer;
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::NodeMetadataSource;
|
||||
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
|
||||
use document_graph_storage::{HistoryMetadata, HotOp, Rev, Subject, TimeStamp, Value, WallStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::manifest::Manifest;
|
||||
use crate::session_state::SessionState;
|
||||
use crate::{Gdd, MANIFEST_CODEC, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
|
||||
@@ -182,6 +182,25 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn metadata(&self) -> &HistoryMetadata {
|
||||
&self.metadata
|
||||
}
|
||||
|
||||
/// State a fact at wall time `wall_ms`, taken on only once it is on disk. Returns whether it changed anything.
|
||||
pub fn record(&mut self, subject: Subject, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
|
||||
let stamp = WallStamp {
|
||||
ms: wall_ms as u64,
|
||||
peer: self.session.peer(),
|
||||
};
|
||||
let Some(fact) = self.metadata.statement(subject, key, value, stamp) else { return Ok(false) };
|
||||
// The leading newline keeps the fact off a tail a crash left unterminated. Reading skips the blank lines this leaves.
|
||||
let mut line = vec![b'\n'];
|
||||
METADATA_CODEC.append(&mut line, &fact)?;
|
||||
self.working.append_non_blocking(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &line)?;
|
||||
self.metadata.absorb(fact);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
|
||||
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
|
||||
fn rewrite_history(&mut self) -> Result<(), Error> {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use document_format::{GddV1, GddV1Layout, Layout};
|
||||
use document_graph_storage::{PeerId, Rev, Subject, UserId, rev_attr, user_attr};
|
||||
|
||||
const NOW_MS: f64 = 1_700_000_000_000.;
|
||||
const ADA: Subject = Subject::User(UserId(10));
|
||||
|
||||
fn document_naming_ada() -> GddV1 {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 1, "editor".into(), "stdlib".into()).expect("create");
|
||||
assert!(gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
|
||||
gdd
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recorded_facts_survive_a_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document_naming_ada();
|
||||
assert!(!gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"), "the same name is no change");
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
gdd.record(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record");
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"));
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "conversion", feature = "zip"))]
|
||||
#[test]
|
||||
fn an_export_carries_the_metadata_only_with_the_history() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = document_naming_ada();
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
for include_history in [true, false] {
|
||||
let options = document_format::ExportOptions {
|
||||
include_history,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
|
||||
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), include_history.then_some("Ada"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
|
||||
futures::executor::block_on(async {
|
||||
let (working, layout) = document_naming_ada().into_storage();
|
||||
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
|
||||
working.append_non_blocking(&path, b"{\"subject\":{\"User\":").expect("append");
|
||||
|
||||
let mut reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
reopened.record(Subject::User(UserId(11)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
assert_eq!(reopened.metadata().user_name(UserId(11)), Some("Bea"));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
//! What people say about a document's history, kept beside it rather than in it: user names, step labels
|
||||
//! and tags. None of it is folded into the document, so moving the head never changes it and stating it
|
||||
//! never rewrites a delta.
|
||||
|
||||
use crate::ids::{PeerId, Rev, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// When a fact was stated and by whom: milliseconds since the Unix epoch, the peer breaking ties.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct WallStamp {
|
||||
pub ms: u64,
|
||||
pub peer: PeerId,
|
||||
}
|
||||
|
||||
/// What a fact is about. A rev stands for the interaction it closes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum Subject {
|
||||
User(UserId),
|
||||
Rev(Rev),
|
||||
}
|
||||
|
||||
/// One statement about a subject, and one line of the metadata file.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MetadataFact {
|
||||
pub subject: Subject,
|
||||
pub key: String,
|
||||
pub value: serde_json::Value,
|
||||
pub stamp: WallStamp,
|
||||
}
|
||||
|
||||
/// The attribute keys the editor writes for a user.
|
||||
pub mod user_attr {
|
||||
/// The display name the user chose. Absent or empty means unnamed.
|
||||
pub const NAME: &str = "name";
|
||||
}
|
||||
|
||||
/// The attribute keys the editor writes for a rev.
|
||||
pub mod rev_attr {
|
||||
/// The name a person gave the interaction. Absent or empty means unnamed.
|
||||
pub const LABEL: &str = "label";
|
||||
/// Prefixes each tag's name to form its key. The value is `true` while the tag stands and `false` once removed.
|
||||
pub const TAG_PREFIX: &str = "tag:";
|
||||
}
|
||||
|
||||
/// The standing fact for each subject and key. Folding the same facts in any order gives the same record.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct HistoryMetadata {
|
||||
facts: BTreeMap<Subject, BTreeMap<String, MetadataFact>>,
|
||||
}
|
||||
|
||||
impl HistoryMetadata {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.facts.is_empty()
|
||||
}
|
||||
|
||||
pub fn fold(facts: impl IntoIterator<Item = MetadataFact>) -> Self {
|
||||
let mut record = Self::default();
|
||||
for fact in facts {
|
||||
record.absorb(fact);
|
||||
}
|
||||
record
|
||||
}
|
||||
|
||||
pub fn facts(&self) -> impl Iterator<Item = &MetadataFact> {
|
||||
self.facts.values().flat_map(BTreeMap::values)
|
||||
}
|
||||
|
||||
fn standing(&self, subject: Subject, key: &str) -> Option<&MetadataFact> {
|
||||
self.facts.get(&subject)?.get(key)
|
||||
}
|
||||
|
||||
fn text(&self, subject: Subject, key: &str) -> Option<&str> {
|
||||
self.standing(subject, key)?.value.as_str().filter(|text| !text.is_empty())
|
||||
}
|
||||
|
||||
pub fn user_name(&self, user: UserId) -> Option<&str> {
|
||||
self.text(Subject::User(user), user_attr::NAME)
|
||||
}
|
||||
|
||||
pub fn rev_label(&self, rev: Rev) -> Option<&str> {
|
||||
self.text(Subject::Rev(rev), rev_attr::LABEL)
|
||||
}
|
||||
|
||||
/// The tags standing on `rev`, in name order.
|
||||
pub fn rev_tags(&self, rev: Rev) -> Vec<&str> {
|
||||
let Some(attributes) = self.facts.get(&Subject::Rev(rev)) else { return Vec::new() };
|
||||
attributes
|
||||
.values()
|
||||
.filter(|fact| fact.value == true)
|
||||
.filter_map(|fact| fact.key.strip_prefix(rev_attr::TAG_PREFIX))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The fact that would state `value`, stamped after the one it replaces so a clock behind a peer's still wins.
|
||||
/// `None` when the value already stands, or when the standing stamp is at the end of time and can't be outdone.
|
||||
pub fn statement(&self, subject: Subject, key: &str, value: serde_json::Value, mut stamp: WallStamp) -> Option<MetadataFact> {
|
||||
if let Some(standing) = self.standing(subject, key) {
|
||||
if standing.value == value {
|
||||
return None;
|
||||
}
|
||||
if stamp <= standing.stamp {
|
||||
stamp.ms = standing.stamp.ms.checked_add(1)?;
|
||||
}
|
||||
}
|
||||
let key = key.to_string();
|
||||
Some(MetadataFact { subject, key, value, stamp })
|
||||
}
|
||||
|
||||
/// Take on a fact unless the standing one has a later stamp, or the same stamp and a value that encodes no lower.
|
||||
pub fn absorb(&mut self, fact: MetadataFact) {
|
||||
let attributes = self.facts.entry(fact.subject).or_default();
|
||||
let stands = |mine: &MetadataFact| mine.stamp.cmp(&fact.stamp).then_with(|| mine.value.to_string().cmp(&fact.value.to_string())).is_ge();
|
||||
if !attributes.get(&fact.key).is_some_and(stands) {
|
||||
attributes.insert(fact.key.clone(), fact);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ADA: Subject = Subject::User(UserId(1));
|
||||
|
||||
fn stamp(ms: u64) -> WallStamp {
|
||||
WallStamp { ms, peer: PeerId(1) }
|
||||
}
|
||||
|
||||
fn fact(subject: Subject, key: &str, value: impl Into<serde_json::Value>, ms: u64) -> MetadataFact {
|
||||
MetadataFact {
|
||||
subject,
|
||||
key: key.into(),
|
||||
value: value.into(),
|
||||
stamp: stamp(ms),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn facts_settle_alike_whatever_order_they_meet_in() {
|
||||
let name = |value, ms| fact(ADA, user_attr::NAME, value, ms);
|
||||
let later = HistoryMetadata::fold([name("Bea", 20), name("Ada", 10)]);
|
||||
assert_eq!(later, HistoryMetadata::fold([name("Ada", 10), name("Bea", 20)]));
|
||||
assert_eq!(later.user_name(UserId(1)), Some("Bea"));
|
||||
assert_eq!(HistoryMetadata::fold([name("Ada", 10), name("Bea", 10)]), HistoryMetadata::fold([name("Bea", 10), name("Ada", 10)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_behind_a_peers_still_gets_its_say() {
|
||||
let record = HistoryMetadata::fold([fact(ADA, user_attr::NAME, "Ada", 100)]);
|
||||
let stated = record.statement(ADA, user_attr::NAME, "Countess".into(), stamp(5)).expect("a change");
|
||||
assert_eq!(stated.stamp.ms, 101);
|
||||
assert!(record.statement(ADA, user_attr::NAME, "Ada".into(), stamp(500)).is_none(), "the same value is no change");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_names_and_removed_tags_do_not_read_back() {
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
let subject = Subject::Rev(step);
|
||||
let record = HistoryMetadata::fold([fact(ADA, user_attr::NAME, "", 1), fact(subject, "tag:v1", true, 1), fact(subject, "tag:draft", false, 1)]);
|
||||
assert_eq!(record.user_name(UserId(1)), None);
|
||||
assert_eq!(record.rev_tags(step), vec!["v1"]);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ pub mod crdt;
|
||||
pub mod delta;
|
||||
pub mod document;
|
||||
pub mod history;
|
||||
mod history_metadata;
|
||||
pub mod ids;
|
||||
pub mod model;
|
||||
mod prior;
|
||||
@@ -25,6 +26,7 @@ pub use attributes::*;
|
||||
pub use crdt::*;
|
||||
pub use document::*;
|
||||
pub use history::History;
|
||||
pub use history_metadata::{HistoryMetadata, MetadataFact, Subject, WallStamp, rev_attr, user_attr};
|
||||
pub use ids::*;
|
||||
pub use model::*;
|
||||
pub use prior::{NetworkField, NodeField, Prior};
|
||||
|
||||
+28
-11
@@ -2,7 +2,7 @@ use crate::application::{Editor, Environment};
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
|
||||
use crate::task::{Spawn, Spawner};
|
||||
use crate::task::{Clock, Scheduling, Spawn, Spawner};
|
||||
use document_container::store::DocumentStore;
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
@@ -96,6 +96,8 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
let RuntimeBuilder {
|
||||
wake: runtime_wake,
|
||||
mut application_io,
|
||||
scheduling,
|
||||
clock,
|
||||
} = runtime;
|
||||
|
||||
graphene_std::uuid::set_uuid_seed(random_seed);
|
||||
@@ -107,7 +109,8 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
node_runtime.replace_application_io(application_io);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
|
||||
node_runtime.set_scheduling(scheduling);
|
||||
|
||||
(Editor { dispatcher }, node_runtime)
|
||||
}
|
||||
@@ -184,17 +187,18 @@ impl<W, E, R> EditorBuilder<W, E, R, ()> {
|
||||
pub struct RuntimeBuilder<W = (), A = ()> {
|
||||
wake: W,
|
||||
application_io: A,
|
||||
clock: Arc<dyn Clock>,
|
||||
scheduling: Scheduling,
|
||||
}
|
||||
|
||||
impl RuntimeBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self { wake: (), application_io: () }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RuntimeBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
pub fn new(clock: Arc<dyn Clock>) -> Self {
|
||||
Self {
|
||||
wake: (),
|
||||
application_io: (),
|
||||
clock,
|
||||
scheduling: Scheduling::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,12 +208,25 @@ impl<A> RuntimeBuilder<(), A> {
|
||||
RuntimeBuilder {
|
||||
wake: Arc::new(wake),
|
||||
application_io: self.application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W> RuntimeBuilder<W, ()> {
|
||||
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
|
||||
RuntimeBuilder { wake: self.wake, application_io }
|
||||
RuntimeBuilder {
|
||||
wake: self.wake,
|
||||
application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, A> RuntimeBuilder<W, A> {
|
||||
pub fn with_scheduling(self, scheduling: Scheduling) -> Self {
|
||||
Self { scheduling, ..self }
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -32,7 +32,7 @@ use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Graphic};
|
||||
use graphene_std::{Appearance, Artboard, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
@@ -776,6 +776,45 @@ impl TableItemLayout for Coverage {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effects {
|
||||
fn type_name() -> &'static str {
|
||||
"Effects"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effects".to_string()
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
// Label the spreadsheet's element button with the inner list's identifier, like Appearance
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effect {
|
||||
fn type_name() -> &'static str {
|
||||
"Effect"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effect".to_string()
|
||||
}
|
||||
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for TransferCurve {
|
||||
fn type_name() -> &'static str {
|
||||
"TransferCurve"
|
||||
@@ -1203,6 +1242,10 @@ macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
Cover,
|
||||
BevelDirection,
|
||||
BevelStyle,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
@@ -1373,6 +1416,12 @@ macro_rules! known_item_types {
|
||||
Appearance,
|
||||
Coverage,
|
||||
Cover,
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
|
||||
@@ -315,6 +315,9 @@ pub enum DocumentMessage {
|
||||
UpdateAppearanceAttributes {
|
||||
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
|
||||
},
|
||||
UpdateEffectsReach {
|
||||
effects_reach: HashMap<NodeId, f64>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
UngroupLayer {
|
||||
|
||||
@@ -1877,6 +1877,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||
}
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
||||
let layer_effects_reach = effects_reach
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
|
||||
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
||||
.collect();
|
||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
|
||||
@@ -759,20 +759,26 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
|
||||
/// from the default (`Linear`).
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||
let [start, end] = match gradient_form {
|
||||
GradientForm::Linear => LINEAR_DIALS,
|
||||
GradientForm::Radial => RADIAL_DIALS,
|
||||
};
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
}
|
||||
|
||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||
|
||||
@@ -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."),
|
||||
@@ -837,6 +834,7 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
||||
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
||||
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
||||
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
|
||||
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
|
||||
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, Graphic, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
@@ -438,6 +439,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -2997,6 +3001,79 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
|
||||
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
||||
}
|
||||
|
||||
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::math_nodes::gradient_curvature::*;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
|
||||
let curvatures = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
|
||||
Some(&TaggedValue::Number(value)) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
|
||||
// Each form's button sets both curvatures to the form's own, and stands out while they're exactly those
|
||||
let mut form = vec![
|
||||
TextLabel::new("Form")
|
||||
.tooltip_label("Form")
|
||||
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
|
||||
.widget_instance(),
|
||||
];
|
||||
add_blank_assist(&mut form);
|
||||
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
for (label, [start, end], tooltip) in [
|
||||
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
|
||||
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
|
||||
] {
|
||||
form.push(
|
||||
TextButton::new(label)
|
||||
.tooltip_description(tooltip)
|
||||
.emphasized(curvatures == Some([start, end]))
|
||||
.disabled(curvatures.is_none())
|
||||
.on_update(move |_: &TextButton| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: StartCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(start).into(),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: EndCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(end).into(),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
// The same sliders the curvatures would get without this panel
|
||||
let options = ParameterOptions {
|
||||
soft_min: Some(-1.),
|
||||
soft_max: Some(1.),
|
||||
slider: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
|
||||
|
||||
let mut layout = vec![LayoutGroup::row(form)];
|
||||
layout.extend(curvature(StartCurvatureInput::INDEX));
|
||||
layout.extend(curvature(EndCurvatureInput::INDEX));
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
|
||||
@@ -270,7 +270,7 @@ impl OverlayContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_scene(self) -> VelloSceneBuilder {
|
||||
pub fn take_scene(self) -> VelloSceneBuilder<'static> {
|
||||
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
|
||||
let empty_scene = overlay_scene(&internal.viewport);
|
||||
std::mem::replace(&mut internal.scene, empty_scene)
|
||||
@@ -486,13 +486,13 @@ pub enum DrawHandles {
|
||||
}
|
||||
|
||||
pub(super) struct OverlayContextInternal {
|
||||
scene: VelloSceneBuilder,
|
||||
scene: VelloSceneBuilder<'static>,
|
||||
viewport: ViewportMessageHandler,
|
||||
visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
|
||||
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder {
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static> {
|
||||
// The smallest texture size limit WebGL2 guarantees, which only matters for the overlays' tiny pattern images
|
||||
const MAX_TEXTURE_SIZE: u32 = 2048;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -51,6 +51,8 @@ pub struct DocumentMetadata {
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
|
||||
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
|
||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
|
||||
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
|
||||
/// Transform from document space to viewport space.
|
||||
pub document_to_viewport: DAffine2,
|
||||
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
||||
@@ -347,21 +349,22 @@ 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).
|
||||
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
if let Some(item) = self.layer_vector_data.get(&layer) {
|
||||
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a
|
||||
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
||||
let stroke = self
|
||||
.layer_appearance_attributes
|
||||
.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())
|
||||
});
|
||||
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||
|
||||
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
||||
Some([min - reach, max + reach])
|
||||
}
|
||||
|
||||
/// Get the bounding box of the click target of the specified layer in viewport space
|
||||
@@ -717,6 +720,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_and_effects(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);
|
||||
}
|
||||
}
|
||||
@@ -970,11 +970,11 @@ impl NodeNetworkInterface {
|
||||
Some(transformed.bounding_box())
|
||||
}
|
||||
|
||||
/// Calculates the document bounds in document space, expanding vector layer bounds to include the rendered
|
||||
/// stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the document bounds in document space, expanding layer bounds to include the rendered stroke width and
|
||||
/// effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
self.document_metadata.document_bounds(include_artboards, true, || {
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke(layer))
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -991,17 +991,17 @@ impl NodeNetworkInterface {
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Calculates the selected layer bounds in document space, expanding vector layer bounds to include the
|
||||
/// rendered stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the selected layer bounds in document space, expanding layer bounds to include the rendered stroke width
|
||||
/// and effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke_and_effects");
|
||||
return None;
|
||||
};
|
||||
selected_nodes
|
||||
.selected_layers(&self.document_metadata)
|
||||
.filter(|&layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
|
||||
+16
@@ -737,6 +737,22 @@ mod tests {
|
||||
assert!(!type_feeds_input(&item!(f64), &item!(Graphic), paint_conversions), "a number has no conversion into a graphic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cpu_raster_feeds_an_input_that_only_takes_gpu_rasters() {
|
||||
use graphene_std::raster_nodes::dehaze::dehaze::ImageFrameInput;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
|
||||
let dehaze_image = input_conversions(&ImageFrameInput::NODE_IDENTIFIER).get(ImageFrameInput::INDEX).copied().flatten();
|
||||
|
||||
assert!(
|
||||
type_feeds_input(&item!(Raster<CPU>), &item!(Raster<GPU>), dehaze_image),
|
||||
"a CPU raster should upload through the input adapter"
|
||||
);
|
||||
assert!(type_feeds_input(&list!(Raster<CPU>), &list!(Raster<GPU>), dehaze_image), "a list of CPU rasters should too");
|
||||
assert!(type_feeds_input(&item!(Raster<GPU>), &item!(Raster<GPU>), dehaze_image), "a GPU raster should pass through");
|
||||
assert!(!type_feeds_input(&item!(Raster<GPU>), &item!(Raster<CPU>), None), "nothing downloads a GPU raster implicitly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_promote_onto_list_inputs() {
|
||||
let paint_conversions = input_conversions(&PaintInput::NODE_IDENTIFIER).get(PaintInput::INDEX).copied().flatten();
|
||||
|
||||
@@ -200,4 +200,9 @@ impl NodeNetworkInterface {
|
||||
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
|
||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||
}
|
||||
|
||||
/// Update how far each layer's effects paint past its content.
|
||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
|
||||
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
||||
}
|
||||
}
|
||||
@@ -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.);
|
||||
|
||||
+86
-14
@@ -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,12 +16,11 @@ 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;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -300,10 +299,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
aliases: &["math_nodes::GradientTypeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
aliases: &["math_nodes::SpreadMethodNode"],
|
||||
@@ -498,7 +493,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 {
|
||||
@@ -514,8 +508,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::filter::blur::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
node: graphene_std::raster_nodes::effects::blur::IDENTIFIER,
|
||||
aliases: &["raster_nodes::filter::BlurNode", "graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
|
||||
@@ -524,7 +518,7 @@ 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",
|
||||
"raster_nodes::adjustments::BrightnessContrastClassicNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -533,15 +527,11 @@ 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",
|
||||
],
|
||||
},
|
||||
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::color_balance::IDENTIFIER,
|
||||
aliases: &["raster_nodes::adjustments::color_balance_shader_node::ColorBalanceShaderNodeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::ColorOverlayNode",
|
||||
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
|
||||
@@ -549,7 +539,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::adjustments::ColorOverlayNode",
|
||||
"raster_nodes::generate_curves::ColorOverlayNode",
|
||||
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
"raster_nodes::blending_nodes::color_overlay_shader_node::ColorOverlayShaderNodeNode",
|
||||
"raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -570,7 +560,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 +568,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 +587,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 +612,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 +620,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 +629,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 +637,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 +647,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 +661,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 +669,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 +677,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",
|
||||
],
|
||||
},
|
||||
// ================================
|
||||
@@ -1226,11 +1195,49 @@ fn is_monitored_transform_subgraph(node: &DocumentNode) -> bool {
|
||||
monitor_reads_first_import && transform_reads_monitor_and_other_imports && exports_transform
|
||||
}
|
||||
|
||||
/// The CPU node a removed GPU twin was generated from, as named in its era, like `raster_nodes::adjustments::InvertNode` for `raster_nodes::adjustments::invert_shader_node::InvertShaderNodeNode`.
|
||||
fn cpu_node_of_gpu_twin(identifier: &str) -> Option<String> {
|
||||
let identifier = identifier.split('<').next()?;
|
||||
let (module_path, struct_name) = identifier.rsplit_once("::")?;
|
||||
let (parent_module_path, twin_module) = module_path.rsplit_once("::")?;
|
||||
let cpu_struct_name = struct_name.strip_suffix("ShaderNodeNode")?;
|
||||
|
||||
twin_module.ends_with("_shader_node").then(|| format!("{parent_module_path}::{cpu_struct_name}Node"))
|
||||
}
|
||||
|
||||
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
|
||||
document.network_interface.migrate_path_modify_node();
|
||||
document.network_interface.migrate_rewired_previews();
|
||||
document.network_interface.normalize_stored_types();
|
||||
|
||||
// The removed GPU twins become their CPU nodes minus the trailing executor input, so the renames below carry them forward like their era's CPU nodes
|
||||
let gpu_twins = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
|
||||
let kept_input_count = node.inputs.len().saturating_sub(1);
|
||||
Some((*node_id, path, cpu_node_of_gpu_twin(identifier.as_str())?, node.inputs[..kept_input_count].to_vec()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for (node_id, network_path, cpu_identifier, inputs) in gpu_twins {
|
||||
let input_metadata = document
|
||||
.network_interface
|
||||
.node_metadata(&node_id, &network_path)
|
||||
.map(|metadata| metadata.persistent_metadata.input_metadata.iter().take(inputs.len()).cloned().collect())
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut node_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::with_owned_string(cpu_identifier)),
|
||||
inputs,
|
||||
input_metadata,
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_implementation(&node_id, &network_path, &mut node_template);
|
||||
document.network_interface.replace_inputs(&node_id, &network_path, &mut node_template);
|
||||
}
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
|
||||
// Apply string and node replacements to each node
|
||||
@@ -1263,6 +1270,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), under.clone(), &network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), over.clone(), &network_path);
|
||||
}
|
||||
|
||||
if *new == graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1625,6 +1636,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take the presets of the form it set
|
||||
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
|
||||
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
|
||||
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path) in &gradient_form_nodes {
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
reset_default_display_name(document, node_id, network_path, "Gradient Form");
|
||||
|
||||
if let Some(input) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
|
||||
}
|
||||
|
||||
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::GradientForm(GradientForm::Radial)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
|
||||
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
|
||||
_ => {
|
||||
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
|
||||
graphene_std::renderer::dial_gradient::LINEAR_DIALS
|
||||
}
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
|
||||
}
|
||||
|
||||
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
|
||||
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
|
||||
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
||||
@@ -1849,35 +1903,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.
|
||||
@@ -2415,7 +2440,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
|
||||
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
|
||||
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
|
||||
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
|
||||
];
|
||||
for (parameter, fallback) in conversions {
|
||||
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
|
||||
@@ -3506,6 +3530,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
|
||||
@@ -3543,18 +3579,16 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
photo_filter::IDENTIFIER,
|
||||
color_lookup::IDENTIFIER,
|
||||
image_to_channels::IDENTIFIER,
|
||||
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||
graphene_std::raster_nodes::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::effects::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,
|
||||
]
|
||||
@@ -3674,11 +3708,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 +3770,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,12 +3914,13 @@ 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 removed Upload Texture node, in its proto node or older wrapper network form, degrades to a passthrough of its content
|
||||
let is_upload_texture = match document.network_interface.reference(node_id, network_path) {
|
||||
Some(DefinitionIdentifier::Network(name)) => name == "Upload Texture",
|
||||
Some(DefinitionIdentifier::ProtoNode(identifier)) => identifier.as_str().ends_with("::UploadTextureNode"),
|
||||
None => false,
|
||||
};
|
||||
if is_upload_texture {
|
||||
let mut node_template = resolve_proto_node_type(graphene_std::ops::passthrough::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)?;
|
||||
@@ -4105,6 +4140,88 @@ mod tests {
|
||||
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_twins_name_the_cpu_nodes_they_came_from() {
|
||||
assert_eq!(
|
||||
cpu_node_of_gpu_twin("raster_nodes::adjustments::desaturate_shader_node::DesaturateShaderNodeNode").as_deref(),
|
||||
Some(graphene_std::raster_nodes::adjustments::desaturate::IDENTIFIER.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
cpu_node_of_gpu_twin("graphene_raster_nodes::blending_nodes::color_overlay_shader_node::ColorOverlayShaderNodeNode").as_deref(),
|
||||
Some("graphene_raster_nodes::blending_nodes::ColorOverlayNode")
|
||||
);
|
||||
assert_eq!(cpu_node_of_gpu_twin(graphene_std::raster_nodes::adjustments::invert::IDENTIFIER.as_str()), None);
|
||||
}
|
||||
|
||||
// Upload Texture opens as a passthrough, and GPU twins open as the CPU nodes they were generated from, keeping their wires but not their executor input
|
||||
#[test]
|
||||
fn gpu_twins_and_upload_texture_open_as_cpu_nodes() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::raster_nodes::adjustments::desaturate;
|
||||
|
||||
let executor = || NodeInput::scope("graphene_std::platform_application_io::WgpuExecutorNode");
|
||||
let legacy_node = |identifier: &'static str, inputs: Vec<NodeInput>| NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
input_metadata: inputs.iter().map(|_| ("Value", "").into()).collect(),
|
||||
inputs,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let desaturate_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(desaturate::IDENTIFIER))
|
||||
.expect("the Desaturate definition should exist")
|
||||
.default_node_template();
|
||||
let content = NodeInput::value(TaggedValue::Color(Color::RED), false);
|
||||
let method = desaturate_template.inputs[1].clone();
|
||||
let brightness = NodeInput::value(TaggedValue::Number(25.), false);
|
||||
let contrast = NodeInput::value(TaggedValue::Number(-10.), false);
|
||||
|
||||
// Uploaded content feeds a Desaturate GPU twin, which feeds a Brightness/Contrast Classic GPU twin saved under the `raster_nodes` crate name
|
||||
let saved_nodes = [
|
||||
legacy_node("graphene_std::platform_application_io::UploadTextureNode", vec![content.clone(), executor()]),
|
||||
legacy_node(
|
||||
"raster_nodes::adjustments::desaturate_shader_node::DesaturateShaderNodeNode",
|
||||
vec![NodeInput::node(NodeId(0), 0), method.clone(), executor()],
|
||||
),
|
||||
legacy_node(
|
||||
"raster_nodes::adjustments::brightness_contrast_classic_shader_node::BrightnessContrastClassicShaderNodeNode",
|
||||
vec![NodeInput::node(NodeId(1), 0), brightness.clone(), contrast.clone(), executor()],
|
||||
),
|
||||
];
|
||||
let nodes = saved_nodes
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, node_template)| (NodeId(index as u64), node_template))
|
||||
.collect::<Vec<_>>();
|
||||
let unchanged_ids = nodes.iter().map(|(node_id, _)| (*node_id, *node_id)).collect();
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node_group(nodes, unchanged_ids, &[]);
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let node = |index: u64| opened.network_interface.document_node(&NodeId(index), &[]).expect("the node should still exist");
|
||||
|
||||
let upload_texture = node(0);
|
||||
assert_eq!(upload_texture.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||
assert_eq!(upload_texture.inputs, [content]);
|
||||
|
||||
let desaturate_node = node(1);
|
||||
assert_eq!(desaturate_node.implementation, DocumentNodeImplementation::ProtoNode(desaturate::IDENTIFIER));
|
||||
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
|
||||
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method, pipeline]);
|
||||
|
||||
let brightness_contrast = node(2);
|
||||
assert_eq!(
|
||||
brightness_contrast.implementation,
|
||||
DocumentNodeImplementation::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER)
|
||||
);
|
||||
assert_eq!(brightness_contrast.inputs[..3], [NodeInput::node(NodeId(1), 0), brightness, contrast]);
|
||||
assert_eq!(
|
||||
brightness_contrast.inputs[3],
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
"the Classic twin should turn on the Use Classic toggle"
|
||||
);
|
||||
}
|
||||
|
||||
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
|
||||
#[test]
|
||||
fn every_into_group_alias_resets_the_merge_definition() {
|
||||
@@ -4567,7 +4684,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"),
|
||||
@@ -4603,46 +4720,51 @@ mod tests {
|
||||
}
|
||||
|
||||
#[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, &[]);
|
||||
fn gradient_form_nodes_become_gradient_curvature_presets() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
migrate(&mut document);
|
||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
||||
for (identifier, form, dials) in [
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
|
||||
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
|
||||
] {
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let placeholder = || NodeInput::value(TaggedValue::None, false);
|
||||
document.network_interface.insert_node(
|
||||
source_id,
|
||||
NodeTemplate {
|
||||
inputs: vec![placeholder()],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.insert_node(
|
||||
form_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![placeholder(); 2],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), false), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let 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");
|
||||
}
|
||||
let node = &document.network_interface.document_network().nodes[&form_id];
|
||||
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
|
||||
|
||||
#[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");
|
||||
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(
|
||||
[curvature(1), curvature(2)],
|
||||
dials.map(|dial| Some(TaggedValue::Number(dial))),
|
||||
"{form:?} should become its curvature presets"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -342,7 +342,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
|
||||
// A generator discards its primary input, so the chain ends at whichever one is reached
|
||||
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
|
||||
let setters = [
|
||||
graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -413,7 +413,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
||||
|
||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
|
||||
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
||||
let mut gradient_form: Option<GradientForm> = None;
|
||||
@@ -430,11 +430,14 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
|
||||
if reference == transform_reference {
|
||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||
} else if reference == gradient_form_reference
|
||||
&& gradient_form.is_none()
|
||||
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||
{
|
||||
gradient_form = Some(*value);
|
||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
||||
// Curvatures other than the radial form's are drawn with the linear form's controls
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::Number(value)) => value,
|
||||
_ => 0.,
|
||||
};
|
||||
let is_radial = [curvature(1), curvature(2)] == graphene_std::renderer::dial_gradient::RADIAL_DIALS;
|
||||
gradient_form = Some(if is_radial { GradientForm::Radial } else { GradientForm::Linear });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3366,7 +3369,7 @@ mod test_gradient {
|
||||
.await;
|
||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
||||
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
editor
|
||||
@@ -3375,7 +3378,7 @@ mod test_gradient {
|
||||
})
|
||||
.await;
|
||||
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let form_node_id = {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
network_interface
|
||||
@@ -3384,10 +3387,10 @@ mod test_gradient {
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
||||
.expect("Gradient Form node should have been inserted")
|
||||
.expect("Gradient Curvature node should have been inserted")
|
||||
};
|
||||
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
|
||||
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
||||
|
||||
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
||||
|
||||
@@ -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();
|
||||
@@ -371,11 +383,11 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
|
||||
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
|
||||
// `AllArtwork` and `Selection` expand vector layer bounds by the rendered stroke width so strokes
|
||||
// drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
// `AllArtwork` and `Selection` expand layer bounds by the rendered stroke width and effects reach so strokes
|
||||
// and shadows drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
let bounds = match export_config.bounds {
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke(true, &[]),
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke_and_effects(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke_and_effects(true, &[]),
|
||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
||||
}
|
||||
.ok_or_else(|| "No bounding box".to_string())?;
|
||||
@@ -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");
|
||||
@@ -920,6 +959,7 @@ impl NodeGraphExecutor {
|
||||
clip_targets,
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
effects_reach,
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
@@ -936,6 +976,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
@@ -1197,3 +1238,82 @@ mod test {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod raster_input_adapter_tests {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId};
|
||||
use graphene_std::Effects;
|
||||
use graphene_std::list::{ATTR_EFFECTS, Item};
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
use graphene_std::raster_nodes::adjustments::invert;
|
||||
use graphene_std::raster_nodes::dehaze::dehaze;
|
||||
use graphene_std::raster_nodes::filter::median_filter;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::transform::Footprint;
|
||||
|
||||
/// A document whose image feeds `nodes` in turn, ending in the export, with each node's ID.
|
||||
async fn image_through(editor: &mut EditorTestUtils, color: Color, nodes: &[ProtoNodeIdentifier]) -> Vec<NodeId> {
|
||||
editor.new_document().await;
|
||||
editor.create_raster_image(Image::new(4, 4, color), None).await;
|
||||
let image = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
||||
.map(|(id, _)| *id)
|
||||
.expect("the pasted image should be an Image node");
|
||||
|
||||
let mut ids = Vec::new();
|
||||
let mut previous = OutputConnector::node(image, 0);
|
||||
for (index, identifier) in nodes.iter().enumerate() {
|
||||
let id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(identifier.clone()), (index as i32 + 1) * 10, 0).await;
|
||||
let input = InputConnector::node_at_index(id, 0);
|
||||
editor.active_document_mut().network_interface.create_wire(&previous, &input, &[]);
|
||||
previous = OutputConnector::node(id, 0);
|
||||
ids.push(id);
|
||||
}
|
||||
editor.active_document_mut().network_interface.create_wire(&previous, &InputConnector::Export(0), &[]);
|
||||
ids
|
||||
}
|
||||
|
||||
async fn read(editor: &EditorTestUtils, raster: Raster<GPU>) -> Raster<CPU> {
|
||||
let executor = editor.gpu_executor();
|
||||
raster.convert(Footprint::DEFAULT, executor).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_images_stamped_effects_are_carried_out_before_the_gpu_only_node_it_feeds() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
image_through(&mut editor, Color::WHITE, &[invert::IDENTIFIER, median_filter::IDENTIFIER, invert::IDENTIFIER]).await;
|
||||
|
||||
let instrumented = editor.eval_graph_until_finished().await.expect("the CPU raster should reach Median through its input adapter");
|
||||
let reached_median: Item<Raster<CPU>> = instrumented
|
||||
.grab_all_input::<median_filter::ImageFrameInput, Item<Raster<CPU>>>(&editor.runtime)
|
||||
.next()
|
||||
.expect("the image should arrive at Median as a CPU raster");
|
||||
assert!(reached_median.attribute::<Effects>(ATTR_EFFECTS).is_some(), "the first Invert should only stamp the image");
|
||||
|
||||
// Median at its default radius passes its input through, so its output shows what the adapter gave it
|
||||
let output = instrumented
|
||||
.grab_all_input::<invert::InputInput, Item<Raster<GPU>>>(&editor.runtime)
|
||||
.next()
|
||||
.expect("Median should output a GPU raster");
|
||||
assert!(output.attribute::<Effects>(ATTR_EFFECTS).is_none(), "no stamp should be left to apply after Median");
|
||||
let raster = read(&editor, output.into_element()).await;
|
||||
assert!(raster.data[0].r() < 0.01, "the white image should be black by the time Median reads it, not {:?}", raster.data[0]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_image_feeding_dehaze_compiles_and_renders_without_a_migration() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
image_through(&mut editor, Color::from_rgbaf32_unchecked(0.5, 0.6, 0.7, 1.), &[dehaze::IDENTIFIER]).await;
|
||||
|
||||
// A compile error or a failed render fails this
|
||||
editor.eval_graph_uninstrumented().await.expect("the image should reach Dehaze through its input adapter");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::*;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
|
||||
use crate::task::{Spawn, Spawner, Task};
|
||||
use crate::task::{Scheduling, Spawn, Spawner, Task};
|
||||
use glam::{DVec2, UVec2};
|
||||
use graph_craft::application_io::resource::ResourceRegistry;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
@@ -18,15 +18,15 @@ use graphene_std::ops::ConvertAsync;
|
||||
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
|
||||
use graphene_std::raster_types::Raster;
|
||||
use graphene_std::runtime::AsyncRuntime;
|
||||
use graphene_std::runtime::{AsyncRuntime, Clock};
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
|
||||
use graphene_std::{Context, ContextFeatures, ContextOverrides, NodeError, OwnedContextImpl, Poll};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
use std::time::Duration;
|
||||
use thumbnails::Thumbnails;
|
||||
|
||||
mod thumbnails;
|
||||
@@ -42,12 +42,15 @@ pub struct NodeRuntime {
|
||||
receiver: Receiver<GraphRuntimeRequest>,
|
||||
sender: Sender<NodeGraphUpdate>,
|
||||
editor_wake: Wake,
|
||||
dirty: Arc<AtomicBool>,
|
||||
/// A re-evaluation waiting for the next frame, or for the end of an export.
|
||||
rerun: bool,
|
||||
pending: Option<ExecutionRequest>,
|
||||
pending_export: Option<ExecutionRequest>,
|
||||
/// The network the executor last compiled successfully, with previews applied.
|
||||
old_graph: Option<NodeNetwork>,
|
||||
async_runtime: Option<AsyncRuntime>,
|
||||
scheduling: Scheduling,
|
||||
frame_start: Duration,
|
||||
|
||||
editor_api: Arc<PlatformEditorApi>,
|
||||
resources: ResourceRegistry,
|
||||
@@ -125,12 +128,14 @@ impl NodeRuntime {
|
||||
receiver,
|
||||
sender,
|
||||
editor_wake,
|
||||
dirty: Default::default(),
|
||||
rerun: false,
|
||||
pending: None,
|
||||
pending_export: None,
|
||||
old_graph: None,
|
||||
resources: ResourceRegistry::default(),
|
||||
async_runtime: None,
|
||||
scheduling: Scheduling::default(),
|
||||
frame_start: Duration::ZERO,
|
||||
|
||||
editor_api: PlatformEditorApi {
|
||||
#[cfg(not(test))]
|
||||
@@ -216,8 +221,13 @@ impl NodeRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
if self.dirty.swap(false, Ordering::Acquire) && execution.is_none() {
|
||||
execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest);
|
||||
let rerun = std::mem::take(&mut self.rerun) | self.async_runtime().take_bumped();
|
||||
if rerun && execution.is_none() {
|
||||
if self.frame_has_budget() {
|
||||
execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest);
|
||||
} else {
|
||||
self.rerun = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Eydropper should use the same time and pointer to not invalidate the cache
|
||||
@@ -312,7 +322,7 @@ impl NodeRuntime {
|
||||
self.pending_export = Some(request);
|
||||
return None;
|
||||
}
|
||||
(true, _) => self.dirty.store(true, Ordering::Release),
|
||||
(true, _) => self.rerun = true,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -567,33 +577,54 @@ impl NodeRuntime {
|
||||
.into();
|
||||
}
|
||||
|
||||
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake) {
|
||||
let spawn = NodeTaskExecutor {
|
||||
spawner,
|
||||
dirty: self.dirty.clone(),
|
||||
wake,
|
||||
};
|
||||
self.async_runtime = Some(AsyncRuntime::new(Arc::new(spawn)));
|
||||
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake, clock: Arc<dyn Clock>) {
|
||||
self.async_runtime = Some(AsyncRuntime::new(Arc::new(NodeTaskExecutor { spawner, wake }), clock));
|
||||
self.begin_frame();
|
||||
}
|
||||
|
||||
fn async_runtime(&self) -> &AsyncRuntime {
|
||||
pub fn set_scheduling(&mut self, scheduling: Scheduling) {
|
||||
self.scheduling = scheduling;
|
||||
}
|
||||
|
||||
/// Called by the host once the previous output was presented.
|
||||
pub fn begin_frame(&mut self) {
|
||||
self.frame_start = self.async_runtime().clock().now();
|
||||
}
|
||||
|
||||
/// How long a deferred re-evaluation waits for the next frame.
|
||||
pub fn until_next_frame(&self) -> Option<Duration> {
|
||||
let budget = self.frame_budget()?;
|
||||
let elapsed = self.frame_elapsed().as_nanos() % budget.as_nanos();
|
||||
self.rerun.then(|| budget - Duration::from_nanos(elapsed as u64))
|
||||
}
|
||||
|
||||
fn frame_elapsed(&self) -> Duration {
|
||||
self.async_runtime().clock().now().saturating_sub(self.frame_start)
|
||||
}
|
||||
|
||||
fn frame_budget(&self) -> Option<Duration> {
|
||||
self.scheduling.frame_budget.filter(|budget| !budget.is_zero())
|
||||
}
|
||||
|
||||
fn frame_has_budget(&self) -> bool {
|
||||
self.frame_budget().is_none_or(|budget| self.frame_elapsed() < budget)
|
||||
}
|
||||
|
||||
pub(crate) fn async_runtime(&self) -> &AsyncRuntime {
|
||||
self.async_runtime.as_ref().expect("the task executor is installed before the first graph update")
|
||||
}
|
||||
}
|
||||
|
||||
struct NodeTaskExecutor {
|
||||
spawner: Spawner,
|
||||
dirty: Arc<AtomicBool>,
|
||||
wake: Wake,
|
||||
}
|
||||
|
||||
impl Spawn for NodeTaskExecutor {
|
||||
fn spawn(&self, task: Task) {
|
||||
let dirty = self.dirty.clone();
|
||||
let wake = self.wake.clone();
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
task.await;
|
||||
dirty.store(true, Ordering::Release);
|
||||
wake();
|
||||
}));
|
||||
}
|
||||
@@ -702,7 +733,10 @@ impl InspectState {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::{EditorTestUtils, FakeClock};
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graphene_std::SourceId;
|
||||
use graphene_std::runtime::Runtime;
|
||||
|
||||
#[test]
|
||||
fn a_preview_replaces_the_export_of_the_graph_being_compiled() {
|
||||
@@ -727,4 +761,66 @@ mod tests {
|
||||
|
||||
assert_eq!(network.exports.first().and_then(|export| export.as_node()), Some(previewed_node));
|
||||
}
|
||||
|
||||
const SOURCE: SourceId = SourceId(1);
|
||||
|
||||
async fn editor(clock: &Arc<FakeClock>) -> EditorTestUtils {
|
||||
let mut editor = EditorTestUtils::create_with(Scheduling::default(), clock.clone());
|
||||
editor.new_document().await;
|
||||
// SVG Preview renders through the SVG pipeline, which sends each evaluation's artwork to the frontend where it can be seen
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.runtime.async_runtime().retain_sources(&[SOURCE]);
|
||||
editor.runtime.begin_frame();
|
||||
editor
|
||||
}
|
||||
|
||||
fn finish_task(editor: &EditorTestUtils) {
|
||||
editor.runtime.async_runtime().spawn(SOURCE, Box::pin(async {}));
|
||||
}
|
||||
|
||||
async fn evaluates(editor: &mut EditorTestUtils) -> bool {
|
||||
editor.runtime.run().await;
|
||||
let messages = editor.editor.handle_message(Message::Wake);
|
||||
messages.iter().any(|message| matches!(message, FrontendMessage::UpdateDocumentArtwork { .. }))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reevaluations_past_the_frame_budget_wait_for_the_next_frame() {
|
||||
let clock = Arc::new(FakeClock::default());
|
||||
let mut editor = editor(&clock).await;
|
||||
|
||||
finish_task(&editor);
|
||||
finish_task(&editor);
|
||||
assert!(evaluates(&mut editor).await);
|
||||
assert!(!evaluates(&mut editor).await, "two finished tasks re-evaluated twice");
|
||||
|
||||
clock.advance(Duration::from_millis(20));
|
||||
finish_task(&editor);
|
||||
assert!(!evaluates(&mut editor).await);
|
||||
assert_eq!(editor.runtime.until_next_frame(), Some(Duration::from_millis(12)));
|
||||
|
||||
editor.runtime.begin_frame();
|
||||
assert!(evaluates(&mut editor).await);
|
||||
assert_eq!(editor.runtime.until_next_frame(), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn explicit_requests_ignore_the_frame_budget() {
|
||||
let clock = Arc::new(FakeClock::default());
|
||||
let mut editor = editor(&clock).await;
|
||||
|
||||
clock.advance(Duration::from_millis(100));
|
||||
finish_task(&editor);
|
||||
let portfolio = &mut editor.editor.dispatcher.message_handlers.portfolio_message_handler;
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let document = portfolio.documents.get_mut(&document_id).unwrap();
|
||||
portfolio
|
||||
.executor
|
||||
.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO)
|
||||
.unwrap();
|
||||
|
||||
assert!(evaluates(&mut editor).await);
|
||||
assert!(!evaluates(&mut editor).await, "the finished task re-evaluated after the explicit request");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
pub use graphene_std::runtime::{Spawn, Task};
|
||||
pub use graphene_std::runtime::{Clock, Scheduling, Spawn, Task};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type Spawner = Arc<dyn Spawn + Send + Sync>;
|
||||
+89
-12
@@ -9,17 +9,19 @@ 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::task::{Spawn, Task};
|
||||
use crate::node_graph_executor::{EvaluationErrors, NodeRuntime};
|
||||
use crate::task::{Scheduling, Spawn, Task};
|
||||
use crate::test_utils::test_prelude::LayerNodeIdentifier;
|
||||
use document_container::store::MemoryStore;
|
||||
use glam::{DVec2, UVec2};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::application_io::{ApplicationIo, PlatformApplicationIo};
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::runtime::Clock;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::sync::{Arc, LazyLock, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
/// A set of utility functions to make the writing of editor test more declarative
|
||||
pub struct EditorTestUtils {
|
||||
@@ -30,6 +32,10 @@ pub struct EditorTestUtils {
|
||||
|
||||
impl EditorTestUtils {
|
||||
pub fn create() -> Self {
|
||||
Self::create_with(Scheduling::UNLIMITED, Arc::new(FakeClock::default()))
|
||||
}
|
||||
|
||||
pub fn create_with(scheduling: Scheduling, clock: Arc<dyn Clock>) -> Self {
|
||||
init_test_logger();
|
||||
|
||||
let woken = Arc::new(AtomicBool::new(false));
|
||||
@@ -42,7 +48,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(clock).with_wake(|| {}).with_application_io(gpu_application_io()).with_scheduling(scheduling))
|
||||
.with_spawner(BlockingSpawner)
|
||||
.with_random_seed(0)
|
||||
.build();
|
||||
@@ -57,6 +63,11 @@ impl EditorTestUtils {
|
||||
editor
|
||||
}
|
||||
|
||||
/// The GPU executor the graph runs on.
|
||||
pub fn gpu_executor(&self) -> <PlatformApplicationIo as ApplicationIo>::Executor {
|
||||
gpu_application_io().gpu_executor().cloned().expect("tests render on the GPU")
|
||||
}
|
||||
|
||||
pub fn dispatch(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
|
||||
let mut responses = self.editor.handle_message(message);
|
||||
while self.woken.swap(false, Ordering::Relaxed) {
|
||||
@@ -68,7 +79,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 +87,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 {
|
||||
@@ -96,8 +113,35 @@ impl EditorTestUtils {
|
||||
Ok(instrumented)
|
||||
}
|
||||
|
||||
/// Compiles and runs the graph without the monitors of [`Instrumented`], which can't wrap the runtime handle that asynchronous nodes take.
|
||||
pub async fn eval_graph_uninstrumented(&mut self) -> Result<(), String> {
|
||||
let portfolio = &mut self.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).unwrap();
|
||||
|
||||
if let Err(e) = executor.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, Default::default()) {
|
||||
return Err(format!("submit_node_graph_evaluation failed\n\n{e}"));
|
||||
}
|
||||
self.finish_evaluation().await
|
||||
}
|
||||
|
||||
/// Waits for the submitted evaluation and processes its results, failing if the graph didn't render.
|
||||
async fn finish_evaluation(&mut self) -> Result<(), String> {
|
||||
self.runtime.run().await;
|
||||
|
||||
let frontend_messages = self.dispatch(Message::Wake);
|
||||
if frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
|
||||
return Err("Graph should render".to_string());
|
||||
}
|
||||
for message in frontend_messages {
|
||||
message.check_node_graph_error();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
|
||||
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, 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 +151,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 +460,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) };
|
||||
}
|
||||
@@ -480,6 +541,22 @@ pub fn capture_logged_errors<T>(operation: impl FnOnce() -> T) -> (T, Vec<String
|
||||
(result, errors)
|
||||
}
|
||||
|
||||
/// A clock that only moves when advanced.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FakeClock(Mutex<Duration>);
|
||||
|
||||
impl FakeClock {
|
||||
pub fn advance(&self, by: Duration) {
|
||||
*self.0.lock().unwrap_or_else(PoisonError::into_inner) += by;
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for FakeClock {
|
||||
fn now(&self) -> Duration {
|
||||
*self.0.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
struct BlockingSpawner;
|
||||
impl Spawn for BlockingSpawner {
|
||||
fn spawn(&self, task: Task) {
|
||||
@@ -501,7 +578,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;
|
||||
|
||||
@@ -540,9 +540,10 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||
> .text-label:only-child {
|
||||
// A label with no expose button before it lines up with the parameter names that follow one
|
||||
> .text-label:first-child {
|
||||
margin-left: calc(20px + 8px + 8px);
|
||||
--wire-indent: 20px;
|
||||
}
|
||||
|
||||
> .separator.horizontal.unrelated {
|
||||
|
||||
@@ -36,7 +36,7 @@ serde-wasm-bindgen = { workspace = true }
|
||||
js-sys = { workspace = true }
|
||||
wasm-bindgen-futures = { workspace = true }
|
||||
wgpu = { workspace = true, optional = true }
|
||||
web-sys = { workspace = true }
|
||||
web-sys = { workspace = true, features = ["Performance"] }
|
||||
serde_json = { workspace = true }
|
||||
spin = { workspace = true, optional = true }
|
||||
tsify = { workspace = true }
|
||||
|
||||
@@ -81,7 +81,11 @@ impl EditorWrapper {
|
||||
.with_resource_storage(storage)
|
||||
.with_document_store(document_store),
|
||||
)
|
||||
.with_runtime(RuntimeBuilder::new().with_wake(crate::helpers::wake_runtime).with_application_io(application_io))
|
||||
.with_runtime(
|
||||
RuntimeBuilder::new(std::sync::Arc::new(crate::helpers::PerformanceClock))
|
||||
.with_wake(crate::helpers::wake_runtime)
|
||||
.with_application_io(application_io),
|
||||
)
|
||||
.with_spawner(crate::helpers::WasmSpawner)
|
||||
.with_random_seed(uuid_random_seed)
|
||||
.build();
|
||||
@@ -193,7 +197,14 @@ impl EditorWrapper {
|
||||
|
||||
*g.borrow_mut() = Some(Closure::new(move |_timestamp| {
|
||||
#[cfg(not(feature = "native"))]
|
||||
wasm_bindgen_futures::spawn_local(run_node_runtime());
|
||||
{
|
||||
if let Some(mut runtime) = crate::NODE_RUNTIME.try_lock()
|
||||
&& let Some(runtime) = runtime.as_mut()
|
||||
{
|
||||
runtime.begin_frame();
|
||||
}
|
||||
wasm_bindgen_futures::spawn_local(run_node_runtime());
|
||||
}
|
||||
|
||||
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
|
||||
wrapper(|wrapper| {
|
||||
|
||||
@@ -7,7 +7,7 @@ use editor::messages::input_mapper::utility_types::keyboard::Key;
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
use editor::messages::prelude::*;
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
use editor::task::{Spawn, Task};
|
||||
use editor::task::{Clock, Spawn, Task};
|
||||
use js_sys::{Object, Reflect};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
@@ -70,6 +70,16 @@ impl Spawn for WasmSpawner {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
pub(crate) struct PerformanceClock;
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
impl Clock for PerformanceClock {
|
||||
fn now(&self) -> Duration {
|
||||
let performance = window().and_then(|window| window.performance()).expect("the editor runs in a window with `performance`");
|
||||
Duration::from_secs_f64(performance.now() / 1000.)
|
||||
}
|
||||
}
|
||||
|
||||
/// Web editor wake: queues a microtask that dispatches [`Message::Wake`].
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
pub(crate) fn wake_editor() {
|
||||
|
||||
@@ -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,7 +145,7 @@ 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 we have one input of the type value, set it as the construction args
|
||||
if let &[NodeInput::Value { ref tagged_value, .. }] = self.inputs.as_slice() {
|
||||
construction_args = ConstructionArgs::Value(tagged_value.clone());
|
||||
}
|
||||
@@ -286,9 +286,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 +301,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`.
|
||||
@@ -313,13 +313,11 @@ pub enum DocumentNodeImplementation {
|
||||
///
|
||||
/// This is explained in more detail here: <https://www.youtube.com/watch?v=72KJa3jQClo>
|
||||
///
|
||||
/// Currently we use it for GPU execution, where a node has to get "extracted" to its source code representation and stored as a value that can be given to the GpuCompiler node at runtime
|
||||
/// (to become a compute shader). Future use could involve the addition of an InjectNode to convert the source code form back into an executable node, enabling metaprogramming in the node graph.
|
||||
/// Future use could involve the addition of an InjectNode to convert the source code form back into an executable node, enabling metaprogramming in the node graph.
|
||||
/// We would use an assortment of nodes that operate on Graphene source code (just data, no different from any other data flowing through the graph) to make graph transformations.
|
||||
///
|
||||
/// We use this for dealing with macros in a syntactic way of modifying the node graph from within the graph itself. Just like we often deal with lambdas to represent a whole group of
|
||||
/// operations/code/logic, this allows us to basically deal with a lambda at a meta/source-code level, because we need to pass the GPU SPIR-V compiler the source code for a lambda,
|
||||
/// not the executable logic of a lambda.
|
||||
/// operations/code/logic, this allows us to basically deal with a lambda at a meta/source-code level, rather than its executable logic.
|
||||
///
|
||||
/// This is analogous to how Rust macros operate at the level of source code, not executable code. When we speak of source code, that represents Graphene's source code in the form of a
|
||||
/// DocumentNode network, not the text form of Rust's source code. (Analogous to the token stream/AST of a Rust macro.)
|
||||
@@ -550,21 +548,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 +579,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 +601,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 +925,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`.
|
||||
@@ -1418,7 +1419,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 +1460,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 +1471,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 +2101,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 +2110,7 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
const ADD: DefinitionId = DefinitionId(1);
|
||||
const ADD: NetworkId = NetworkId(1);
|
||||
|
||||
fn two_add_instances() -> NodeNetwork {
|
||||
network_with(
|
||||
@@ -2123,7 +2136,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 +2149,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 +2191,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);
|
||||
}
|
||||
}
|
||||
@@ -579,6 +579,9 @@ tagged_value! {
|
||||
TonalRange(raster_nodes::adjustments::TonalRange),
|
||||
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
|
||||
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
|
||||
GlowSource(graphic_types::GlowSource),
|
||||
BevelStyle(graphic_types::BevelStyle),
|
||||
BevelDirection(graphic_types::BevelDirection),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -708,6 +711,25 @@ impl TaggedValue {
|
||||
None
|
||||
}
|
||||
|
||||
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
||||
let mut choices = input.split("::");
|
||||
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
||||
if first == "StrokeAlign" {
|
||||
return Some(match second {
|
||||
"Center" => vector::style::StrokeAlign::Center,
|
||||
"Inside" => vector::style::StrokeAlign::Inside,
|
||||
"Outside" => vector::style::StrokeAlign::Outside,
|
||||
_ => {
|
||||
log::error!("Invalid StrokeAlign default type variant: {input}");
|
||||
return None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
log::error!("Invalid StrokeAlign default type: {input}");
|
||||
None
|
||||
}
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
@@ -726,6 +748,7 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
_ => return None,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
|
||||
application_io: Some(application_io_for_api),
|
||||
});
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(std::time::Instant::now()));
|
||||
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref(), runtime.handle())?;
|
||||
|
||||
match app.command {
|
||||
@@ -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?;
|
||||
|
||||
@@ -3,14 +3,14 @@ use criterion::measurement::Measurement;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_craft::util::{DEMO_ART, compile, load_from_name};
|
||||
use graphene_std::application_io::EditorApi;
|
||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||
use graphene_std::runtime::{AsyncRuntime, Clock, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
|
||||
pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
let network = load_from_name(name);
|
||||
let editor_api = std::sync::Arc::new(EditorApi::default());
|
||||
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
||||
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner), std::sync::Arc::new(NoClock)).handle());
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
@@ -33,3 +33,10 @@ struct DummySpawner;
|
||||
impl Spawn for DummySpawner {
|
||||
fn spawn(&self, _task: Task) {}
|
||||
}
|
||||
|
||||
struct NoClock;
|
||||
impl Clock for NoClock {
|
||||
fn now(&self) -> std::time::Duration {
|
||||
std::time::Duration::ZERO
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -27,6 +27,7 @@ use graphene_std::vector::misc::{
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, GlowSource};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -88,6 +89,7 @@ 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>]),
|
||||
@@ -136,6 +138,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")]
|
||||
@@ -331,6 +334,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
@@ -377,8 +383,28 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// The nested-generic `Box<VectorModification>` registers directly rather than through the shared callback, since the
|
||||
// extra macro layer mangles the `stringify!` whitespace in its adapter identifier; its cache chain is likewise direct below
|
||||
node_types.extend(rank_adapter_nodes!(Box<VectorModification>));
|
||||
// A GPU raster's input adapter also takes the pipeline to upload a CPU raster wire with, so its rows don't come from `rank_adapter_nodes`
|
||||
#[cfg(feature = "gpu")]
|
||||
node_types.extend(rank_adapter_nodes!(Raster<GPU>));
|
||||
{
|
||||
use graphene_std::raster_nodes::effects::{PassRasterNode, UploadItemNode, UploadListNode};
|
||||
use wgpu_executor::WgpuPipelineCache;
|
||||
|
||||
macro_rules! gpu_raster_input_adapter {
|
||||
($path:ty, $from:ty) => {
|
||||
async_node!(
|
||||
identifier: ProtoNodeIdentifier::new("input_adapter<Raster<GPU>>"),
|
||||
$path,
|
||||
input: Context,
|
||||
fn_params: [Context => $from, Context => Item<WgpuPipelineCache>]
|
||||
)
|
||||
};
|
||||
}
|
||||
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, Item<Raster<GPU>>));
|
||||
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, List<Raster<GPU>>));
|
||||
node_types.push(gpu_raster_input_adapter!(UploadItemNode<_, _>, Item<Raster<CPU>>));
|
||||
node_types.push(gpu_raster_input_adapter!(UploadListNode<_, _>, List<Raster<CPU>>));
|
||||
node_types.push(item_to_list_node!(element: Raster<GPU>));
|
||||
}
|
||||
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
||||
macro_rules! list_dyn_rows {
|
||||
($($element:ty),* $(,)?) => {{
|
||||
|
||||
@@ -58,7 +58,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(1), 0)],
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
|
||||
compile_metadata: Some(graphene_std::NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
@@ -69,7 +69,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
|
||||
compile_metadata: Some(graphene_std::NodeCompileMetadata {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
|
||||
@@ -240,7 +240,7 @@ 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)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable, dyn_any::DynAny, graphene_hash::CacheHash)]
|
||||
pub struct Color {
|
||||
red: f32,
|
||||
green: f32,
|
||||
|
||||
@@ -32,9 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
|
||||
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING,
|
||||
ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
|
||||
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
|
||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use num_traits;
|
||||
|
||||
@@ -61,6 +61,11 @@ pub const ATTR_CLIP: &str = "clip";
|
||||
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
||||
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||
/// Gradient's `f64` curvature dial for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
|
||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, the form decides it.
|
||||
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
|
||||
/// Gradient's `f64` curvature dial for the contour through its end, like `gradient_start_curvature` with the ends swapped.
|
||||
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
|
||||
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||
@@ -80,6 +85,9 @@ pub const ATTR_POSITION: &str = "position";
|
||||
pub const ATTR_MIDPOINT: &str = "midpoint";
|
||||
/// Item's ordered list of paint passes, of type `Appearance`. Earlier coverages paint first, compositing below later ones.
|
||||
pub const ATTR_APPEARANCE: &str = "appearance";
|
||||
/// Item's ordered list of effects, of type `Effects`, which the renderer applies in turn to the pixels the item renders to.
|
||||
/// Unlike the appearance, it doesn't cascade to descendants.
|
||||
pub const ATTR_EFFECTS: &str = "effects";
|
||||
// TODO: Add a "fill_rule" attribute as a sibling of "paint" on the coverage list (uniform across covers) once a FillRule type ships
|
||||
/// Coverage's `Graphic` paint (implicit default `Graphic::None`, painting nothing), on the
|
||||
/// `List<Coverage>` inside an `Appearance`.
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
use crate::poll::Poll;
|
||||
use crate::uuid::NodeId;
|
||||
use dyn_any::WasmNotSend;
|
||||
use futures::future::{AbortHandle, Abortable};
|
||||
pub use futures::future::AbortHandle;
|
||||
use futures::future::Abortable;
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
use std::task::{Context, Waker};
|
||||
use std::time::Duration;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type Task = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
|
||||
@@ -18,6 +21,36 @@ pub trait Spawn {
|
||||
fn spawn(&self, task: Task);
|
||||
}
|
||||
|
||||
/// Monotonic time since an arbitrary origin.
|
||||
pub trait Clock: Send + Sync {
|
||||
fn now(&self) -> Duration;
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Clock for std::time::Instant {
|
||||
fn now(&self) -> Duration {
|
||||
self.elapsed()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Scheduling {
|
||||
/// How far into a frame a re-evaluation caused by finished tasks may start. `None` never defers it.
|
||||
pub frame_budget: Option<Duration>,
|
||||
}
|
||||
|
||||
impl Scheduling {
|
||||
pub const UNLIMITED: Self = Self { frame_budget: None };
|
||||
}
|
||||
|
||||
impl Default for Scheduling {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
frame_budget: Some(Duration::from_millis(16)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, graphene_hash::CacheHash, dyn_any::DynAny)]
|
||||
pub struct SourceId(pub u64);
|
||||
|
||||
@@ -33,15 +66,22 @@ impl SourceId {
|
||||
pub type Generations = Arc<[(SourceId, u64)]>;
|
||||
|
||||
pub trait Runtime {
|
||||
fn spawn(&self, source: SourceId, task: Task);
|
||||
/// Bumps the generation of `source` once `task` finishes, unless it was aborted or the source was removed first.
|
||||
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle;
|
||||
}
|
||||
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
pub struct RuntimeHandle(Arc<RuntimeInner>);
|
||||
|
||||
impl RuntimeHandle {
|
||||
pub fn clock(&self) -> &dyn Clock {
|
||||
&*self.0.clock
|
||||
}
|
||||
}
|
||||
|
||||
impl Runtime for RuntimeHandle {
|
||||
fn spawn(&self, source: SourceId, task: Task) {
|
||||
self.0.spawn(source, task);
|
||||
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle {
|
||||
self.0.spawn(source, task)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,28 +104,43 @@ impl graphene_hash::CacheHash for RuntimeHandle {
|
||||
pub struct AsyncRuntime(Arc<RuntimeInner>);
|
||||
|
||||
impl AsyncRuntime {
|
||||
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>) -> Self {
|
||||
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>, clock: Arc<dyn Clock>) -> Self {
|
||||
Self(Arc::new(RuntimeInner {
|
||||
generations: Mutex::default(),
|
||||
sources: Mutex::default(),
|
||||
next_task: AtomicU64::new(0),
|
||||
bumped: AtomicBool::new(false),
|
||||
spawner,
|
||||
clock,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Aborts the unfinished tasks of removed sources.
|
||||
pub fn retain_sources(&self, live: &[SourceId]) {
|
||||
let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
generations.retain(|source, _| live.contains(source));
|
||||
let mut sources = self.0.lock();
|
||||
for (_, state) in sources.extract_if(|source, _| !live.contains(source)) {
|
||||
state.tasks.values().for_each(AbortHandle::abort);
|
||||
}
|
||||
for source in live {
|
||||
generations.entry(*source).or_insert(0);
|
||||
sources.entry(*source).or_default();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Generations {
|
||||
let generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect();
|
||||
let sources = self.0.lock();
|
||||
let mut snapshot: Vec<_> = sources.iter().map(|(source, state)| (*source, state.generation)).collect();
|
||||
snapshot.sort_unstable();
|
||||
snapshot.into()
|
||||
}
|
||||
|
||||
/// Whether any generation was bumped since the last call.
|
||||
pub fn take_bumped(&self) -> bool {
|
||||
self.0.bumped.swap(false, Ordering::AcqRel)
|
||||
}
|
||||
|
||||
pub fn clock(&self) -> &dyn Clock {
|
||||
&*self.0.clock
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn handle(&self) -> RuntimeHandle {
|
||||
RuntimeHandle(Arc::clone(&self.0))
|
||||
@@ -93,25 +148,50 @@ impl AsyncRuntime {
|
||||
}
|
||||
|
||||
impl Runtime for AsyncRuntime {
|
||||
fn spawn(&self, source: SourceId, task: Task) {
|
||||
self.0.spawn(source, task);
|
||||
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle {
|
||||
self.0.spawn(source, task)
|
||||
}
|
||||
}
|
||||
|
||||
/// A live source's generation and its unfinished tasks.
|
||||
#[derive(Default)]
|
||||
struct SourceState {
|
||||
generation: u64,
|
||||
tasks: HashMap<u64, AbortHandle>,
|
||||
}
|
||||
|
||||
struct RuntimeInner {
|
||||
generations: Mutex<HashMap<SourceId, u64>>,
|
||||
sources: Mutex<HashMap<SourceId, SourceState>>,
|
||||
next_task: AtomicU64,
|
||||
bumped: AtomicBool,
|
||||
spawner: Arc<dyn Spawn + Send + Sync>,
|
||||
clock: Arc<dyn Clock>,
|
||||
}
|
||||
|
||||
impl RuntimeInner {
|
||||
fn spawn(self: &Arc<Self>, source: SourceId, task: Task) {
|
||||
fn lock(&self) -> MutexGuard<'_, HashMap<SourceId, SourceState>> {
|
||||
self.sources.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn spawn(self: &Arc<Self>, source: SourceId, task: Task) -> AbortHandle {
|
||||
let (handle, registration) = AbortHandle::new_pair();
|
||||
let id = self.next_task.fetch_add(1, Ordering::Relaxed);
|
||||
if let Some(state) = self.lock().get_mut(&source) {
|
||||
state.tasks.insert(id, handle.clone());
|
||||
}
|
||||
|
||||
let inner = Arc::clone(self);
|
||||
self.spawner.spawn(Box::pin(async move {
|
||||
task.await;
|
||||
if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) {
|
||||
*generation += 1;
|
||||
let finished = Abortable::new(task, registration).await.is_ok();
|
||||
if let Some(state) = inner.lock().get_mut(&source)
|
||||
&& state.tasks.remove(&id).is_some()
|
||||
&& finished
|
||||
{
|
||||
state.generation += 1;
|
||||
inner.bumped.store(true, Ordering::Release);
|
||||
}
|
||||
}));
|
||||
handle
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,14 +247,12 @@ impl<T: Clone + WasmNotSend + 'static> Slots<T> {
|
||||
return state;
|
||||
}
|
||||
|
||||
let (handle, registration) = AbortHandle::new_pair();
|
||||
let slots = Arc::downgrade(&self.0);
|
||||
runtime.spawn(
|
||||
let handle = runtime.spawn(
|
||||
source,
|
||||
Box::pin(async move {
|
||||
if let Ok(state) = Abortable::new(future, registration).await
|
||||
&& let Some(slots) = slots.upgrade()
|
||||
{
|
||||
let state = future.await;
|
||||
if let Some(slots) = slots.upgrade() {
|
||||
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state));
|
||||
}
|
||||
}),
|
||||
@@ -193,7 +271,14 @@ impl<T: Clone + WasmNotSend + 'static> Slots<T> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
struct NoClock;
|
||||
|
||||
impl Clock for NoClock {
|
||||
fn now(&self) -> Duration {
|
||||
Duration::ZERO
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_once(task: &mut Task) -> bool {
|
||||
task.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_ready()
|
||||
@@ -246,7 +331,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_completion_bumps_its_generation() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
|
||||
runtime.handle().spawn(SOURCE, Box::pin(YieldOnce(false)));
|
||||
@@ -259,7 +344,7 @@ mod tests {
|
||||
#[test]
|
||||
fn retaining_sources_keeps_live_generations() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
|
||||
spawner.drain();
|
||||
@@ -274,7 +359,7 @@ mod tests {
|
||||
#[test]
|
||||
fn an_inline_completion_and_a_dropped_source_bump_nothing() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
|
||||
let slots = Slots::default();
|
||||
@@ -291,7 +376,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_slot_serves_the_placeholder_until_the_response_lands() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
let fetch = || async {
|
||||
@@ -308,7 +393,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_blocking_spawner_lands_the_slot_in_the_same_resolve() {
|
||||
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner));
|
||||
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner), Arc::new(NoClock));
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
let fetch = || async {
|
||||
@@ -323,7 +408,7 @@ mod tests {
|
||||
#[test]
|
||||
fn a_clone_keeps_the_task_running() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
let slots = Slots::default();
|
||||
let fetch = || async {
|
||||
YieldOnce(false).await;
|
||||
@@ -340,7 +425,7 @@ mod tests {
|
||||
#[test]
|
||||
fn dropping_the_last_clone_aborts_the_task() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
let slots = Slots::default();
|
||||
let finished = Arc::new(AtomicBool::new(false));
|
||||
let fetch = || {
|
||||
@@ -357,4 +442,32 @@ mod tests {
|
||||
assert_eq!(spawner.drain(), 1);
|
||||
assert!(!finished.load(Ordering::Relaxed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finished_tasks_bump_once() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
|
||||
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
|
||||
|
||||
assert_eq!(spawner.drain(), 2);
|
||||
assert!(runtime.take_bumped());
|
||||
assert!(!runtime.take_bumped());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aborted_tasks_bump_nothing() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
|
||||
runtime.retain_sources(&[SOURCE, SourceId(9)]);
|
||||
runtime.spawn(SOURCE, Box::pin(std::future::pending())).abort();
|
||||
let removed = runtime.spawn(SourceId(9), Box::pin(std::future::pending()));
|
||||
runtime.retain_sources(&[SOURCE]);
|
||||
|
||||
assert!(removed.is_aborted());
|
||||
assert_eq!(spawner.drain(), 2);
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
|
||||
assert!(!runtime.take_bumped());
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -191,6 +191,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);
|
||||
|
||||
@@ -21,6 +21,7 @@ wasm = [
|
||||
"core-types/wasm",
|
||||
"vector-types/wasm",
|
||||
"raster-types/wasm",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
@@ -28,6 +29,7 @@ wasm = [
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
brush-types = { workspace = true }
|
||||
raster-types = { workspace = true, features = ["wgpu"] }
|
||||
vector-types = { workspace = true }
|
||||
@@ -36,8 +38,10 @@ node-macro = { workspace = true }
|
||||
# Workspace dependencies
|
||||
dyn-any = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
num_enum = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
@@ -0,0 +1,557 @@
|
||||
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::effects::{EffectKind, ParameterVisitor};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use graphene_resource::Resource;
|
||||
use num_enum::{FromPrimitive, IntoPrimitive};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// A color adjustment applied to each color on its own, with no regard for its neighbors.
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub enum Adjustment {
|
||||
Desaturate {
|
||||
method: DesaturateMethod,
|
||||
},
|
||||
GammaCorrection {
|
||||
gamma: f64,
|
||||
inverse: bool,
|
||||
},
|
||||
MakeOpaque,
|
||||
BrightnessContrast {
|
||||
/// Percent.
|
||||
brightness: f64,
|
||||
/// Percent.
|
||||
contrast: f64,
|
||||
use_classic: bool,
|
||||
/// On a scale of 0 to 255.
|
||||
classic_pivot: f64,
|
||||
},
|
||||
Levels(Box<LevelsSettings>),
|
||||
Curves(Box<CurvesSettings>),
|
||||
BlackAndWhite(BlackAndWhiteSettings),
|
||||
HueSaturation(Box<HueSaturationSettings>),
|
||||
Invert,
|
||||
Threshold {
|
||||
/// Percent.
|
||||
min_luminance: f64,
|
||||
/// Percent.
|
||||
max_luminance: f64,
|
||||
},
|
||||
GradientMap {
|
||||
/// The gradient, with its whole-ramp settings as its attributes.
|
||||
gradient: Item<Gradient>,
|
||||
reverse: bool,
|
||||
},
|
||||
Vibrance {
|
||||
/// Percent.
|
||||
vibrance: f64,
|
||||
/// Percent.
|
||||
saturation: f64,
|
||||
},
|
||||
ChannelMixer(Box<ChannelMixerSettings>),
|
||||
SelectiveColor(Box<SelectiveColorSettings>),
|
||||
Posterize {
|
||||
levels: i64,
|
||||
},
|
||||
Exposure {
|
||||
exposure: f64,
|
||||
offset: f64,
|
||||
gamma_correction: f64,
|
||||
},
|
||||
ColorBalance(ColorBalanceSettings),
|
||||
PhotoFilter {
|
||||
color: Color,
|
||||
/// Percent.
|
||||
density: f64,
|
||||
preserve_luminosity: bool,
|
||||
},
|
||||
ColorLookup {
|
||||
/// The file the lookup table is read from.
|
||||
lut_file: Resource,
|
||||
},
|
||||
ColorOverlay {
|
||||
color: Color,
|
||||
blend_mode: BlendMode,
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl Adjustment {
|
||||
/// Whether each channel of the result depends only on the same channel of the color, making the adjustment four curves.
|
||||
pub fn is_per_channel(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::GammaCorrection { .. }
|
||||
| Self::MakeOpaque
|
||||
| Self::BrightnessContrast { .. }
|
||||
| Self::Levels(_)
|
||||
| Self::Curves(_)
|
||||
| Self::Invert
|
||||
| Self::Posterize { .. }
|
||||
| Self::Exposure { .. }
|
||||
| Self::ColorBalance(_)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
match self {
|
||||
Self::Desaturate { .. } => EffectKind::Desaturate,
|
||||
Self::GammaCorrection { .. } => EffectKind::GammaCorrection,
|
||||
Self::MakeOpaque => EffectKind::MakeOpaque,
|
||||
Self::BrightnessContrast { .. } => EffectKind::BrightnessContrast,
|
||||
Self::Levels(_) => EffectKind::Levels,
|
||||
Self::Curves(_) => EffectKind::Curves,
|
||||
Self::BlackAndWhite(_) => EffectKind::BlackAndWhite,
|
||||
Self::HueSaturation(_) => EffectKind::HueSaturation,
|
||||
Self::Invert => EffectKind::Invert,
|
||||
Self::Threshold { .. } => EffectKind::Threshold,
|
||||
Self::GradientMap { .. } => EffectKind::GradientMap,
|
||||
Self::Vibrance { .. } => EffectKind::Vibrance,
|
||||
Self::ChannelMixer(_) => EffectKind::ChannelMixer,
|
||||
Self::SelectiveColor(_) => EffectKind::SelectiveColor,
|
||||
Self::Posterize { .. } => EffectKind::Posterize,
|
||||
Self::Exposure { .. } => EffectKind::Exposure,
|
||||
Self::ColorBalance(_) => EffectKind::ColorBalance,
|
||||
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
}
|
||||
}
|
||||
|
||||
/// Visits each parameter with the attribute it rides, named after the node's parameter, and its implicit default, which is the node's.
|
||||
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
match self {
|
||||
Self::Desaturate { method } => visitor.parameter("method", method, DesaturateMethod::default()),
|
||||
Self::GammaCorrection { gamma, inverse } => {
|
||||
visitor.parameter("gamma", gamma, 2.2);
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque | Self::Invert => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
use_classic,
|
||||
classic_pivot,
|
||||
} => {
|
||||
visitor.parameter("brightness", brightness, 0.);
|
||||
visitor.parameter("contrast", contrast, 0.);
|
||||
visitor.parameter("use_classic", use_classic, false);
|
||||
visitor.parameter("classic_pivot", classic_pivot, 127.);
|
||||
}
|
||||
Self::Levels(settings) => {
|
||||
let LevelsSettings { composite, red, green, blue, alpha } = settings.as_mut();
|
||||
composite.visit_parameters(visitor, "");
|
||||
red.visit_parameters(visitor, "red");
|
||||
green.visit_parameters(visitor, "green");
|
||||
blue.visit_parameters(visitor, "blue");
|
||||
alpha.visit_parameters(visitor, "alpha");
|
||||
}
|
||||
Self::Curves(settings) => {
|
||||
let CurvesSettings { composite, red, green, blue, alpha } = settings.as_mut();
|
||||
visitor.parameter("curve", composite, TransferCurve::default());
|
||||
visitor.parameter("red_curve", red, TransferCurve::default());
|
||||
visitor.parameter("green_curve", green, TransferCurve::default());
|
||||
visitor.parameter("blue_curve", blue, TransferCurve::default());
|
||||
visitor.parameter("alpha_curve", alpha, TransferCurve::default());
|
||||
}
|
||||
Self::BlackAndWhite(settings) => {
|
||||
visitor.parameter("use_tint", &mut settings.use_tint, false);
|
||||
visitor.parameter("tint", &mut settings.tint, Color::from(SRGBA8::new(0xe1, 0xd3, 0xb3, 0xff)));
|
||||
visitor.parameter("reds", &mut settings.reds, 40.);
|
||||
visitor.parameter("yellows", &mut settings.yellows, 60.);
|
||||
visitor.parameter("greens", &mut settings.greens, 40.);
|
||||
visitor.parameter("cyans", &mut settings.cyans, 60.);
|
||||
visitor.parameter("blues", &mut settings.blues, 20.);
|
||||
visitor.parameter("magentas", &mut settings.magentas, 80.);
|
||||
}
|
||||
Self::HueSaturation(settings) => {
|
||||
let HueSaturationSettings {
|
||||
master,
|
||||
colorize,
|
||||
colorize_sliders,
|
||||
reds,
|
||||
yellows,
|
||||
greens,
|
||||
cyans,
|
||||
blues,
|
||||
magentas,
|
||||
} = settings.as_mut();
|
||||
|
||||
master.visit_parameters(visitor, "", [0., 0., 0.]);
|
||||
visitor.parameter("colorize", colorize, false);
|
||||
colorize_sliders.visit_parameters(visitor, "colorize", [24., 25., 0.]);
|
||||
|
||||
reds.visit_parameters(visitor, "reds", [315., 345., 15., 45.]);
|
||||
yellows.visit_parameters(visitor, "yellows", [15., 45., 75., 105.]);
|
||||
greens.visit_parameters(visitor, "greens", [75., 105., 135., 165.]);
|
||||
cyans.visit_parameters(visitor, "cyans", [135., 165., 195., 225.]);
|
||||
blues.visit_parameters(visitor, "blues", [195., 225., 255., 285.]);
|
||||
magentas.visit_parameters(visitor, "magentas", [255., 285., 315., 345.]);
|
||||
}
|
||||
Self::Threshold { min_luminance, max_luminance } => {
|
||||
visitor.parameter("min_luminance", min_luminance, 50.);
|
||||
visitor.parameter("max_luminance", max_luminance, 100.);
|
||||
}
|
||||
Self::GradientMap { gradient, reverse } => {
|
||||
visitor.parameter("gradient", gradient, Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])));
|
||||
visitor.parameter("reverse", reverse, false);
|
||||
}
|
||||
Self::Vibrance { vibrance, saturation } => {
|
||||
visitor.parameter("vibrance", vibrance, 0.);
|
||||
visitor.parameter("saturation", saturation, 0.);
|
||||
}
|
||||
Self::ChannelMixer(settings) => {
|
||||
let ChannelMixerSettings {
|
||||
monochrome,
|
||||
monochrome_mix,
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
} = settings.as_mut();
|
||||
|
||||
visitor.parameter("monochrome", monochrome, false);
|
||||
monochrome_mix.visit_parameters(visitor, "monochrome", [40., 40., 20., 0.]);
|
||||
red.visit_parameters(visitor, "red", [100., 0., 0., 0.]);
|
||||
green.visit_parameters(visitor, "green", [0., 100., 0., 0.]);
|
||||
blue.visit_parameters(visitor, "blue", [0., 0., 100., 0.]);
|
||||
}
|
||||
Self::SelectiveColor(settings) => {
|
||||
let SelectiveColorSettings {
|
||||
mode,
|
||||
reds,
|
||||
yellows,
|
||||
greens,
|
||||
cyans,
|
||||
blues,
|
||||
magentas,
|
||||
whites,
|
||||
neutrals,
|
||||
blacks,
|
||||
} = settings.as_mut();
|
||||
|
||||
visitor.parameter("mode", mode, RelativeAbsolute::default());
|
||||
let groups = [
|
||||
("reds", reds),
|
||||
("yellows", yellows),
|
||||
("greens", greens),
|
||||
("cyans", cyans),
|
||||
("blues", blues),
|
||||
("magentas", magentas),
|
||||
("whites", whites),
|
||||
("neutrals", neutrals),
|
||||
("blacks", blacks),
|
||||
];
|
||||
for (name, inks) in groups {
|
||||
inks.visit_parameters(visitor, name);
|
||||
}
|
||||
}
|
||||
Self::Posterize { levels } => visitor.parameter("levels", levels, 4),
|
||||
Self::Exposure { exposure, offset, gamma_correction } => {
|
||||
visitor.parameter("exposure", exposure, 0.);
|
||||
visitor.parameter("offset", offset, 0.);
|
||||
visitor.parameter("gamma_correction", gamma_correction, 1.);
|
||||
}
|
||||
Self::ColorBalance(settings) => {
|
||||
settings.shadows.visit_parameters(visitor, "shadows");
|
||||
settings.midtones.visit_parameters(visitor, "midtones");
|
||||
settings.highlights.visit_parameters(visitor, "highlights");
|
||||
visitor.parameter("preserve_luminosity", &mut settings.preserve_luminosity, true);
|
||||
}
|
||||
Self::PhotoFilter { color, density, preserve_luminosity } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xec, 0x8a, 0x00, 0xff)));
|
||||
visitor.parameter("density", density, 25.);
|
||||
visitor.parameter("preserve_luminosity", preserve_luminosity, true);
|
||||
}
|
||||
Self::ColorLookup { lut_file } => visitor.parameter("lut_file", lut_file, Resource::default()),
|
||||
Self::ColorOverlay { color, blend_mode, opacity } => {
|
||||
// Rides the row as the paint of the Paint Overlay node, which stamps it
|
||||
let mut paint = Graphic::from(*color);
|
||||
visitor.parameter("paint", &mut paint, Graphic::from(Color::BLACK));
|
||||
if let Graphic::Color(paint) = paint {
|
||||
*color = *paint.element();
|
||||
}
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Conversion from a color to grayscale.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
|
||||
#[widget(Dropdown)]
|
||||
#[repr(u32)]
|
||||
pub enum DesaturateMethod {
|
||||
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
|
||||
///
|
||||
/// Accessibility contrast ratios and SVG luminance masks use this.
|
||||
#[default]
|
||||
#[label("Luminance (Rec. 709)")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
|
||||
LuminanceRec709,
|
||||
/// Light level approximation for the color, the Y′ (luma) of Rec. 709, which weights the gamma-encoded RGB channels by `0.2126, 0.7152, 0.0722`.
|
||||
///
|
||||
/// CSS filter functions such as `grayscale()` use this.
|
||||
#[label("Luma (Rec. 709)")]
|
||||
LumaRec709,
|
||||
/// Light level approximation for the color, the Y′ (luma) of Rec. 601, which weights the gamma-encoded RGB channels by `0.299, 0.587, 0.114`.
|
||||
///
|
||||
/// The Luminosity family of blend modes uses this, rounded to `0.3, 0.59, 0.11`.
|
||||
#[label("Luma (Rec. 601)")]
|
||||
LumaRec601,
|
||||
/// Perceptually uniform scale from black to white, the L (lightness) of OkLab.
|
||||
#[label("Lightness (OkLab)")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "Perceptual"))]
|
||||
LightnessOkLab,
|
||||
/// Mean of the three linear-light RGB channels.
|
||||
#[menu_separator]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "AverageChannels"))]
|
||||
ChannelsAverage,
|
||||
/// Smallest of the three linear-light RGB channels.
|
||||
#[cfg_attr(feature = "serde", serde(alias = "MinimumChannels"))]
|
||||
ChannelsMinimum,
|
||||
/// Largest of the three linear-light RGB channels, the V (value) of HSV.
|
||||
#[cfg_attr(feature = "serde", serde(alias = "MaximumChannels"))]
|
||||
ChannelsMaximum,
|
||||
/// Midpoint of the largest and smallest gamma-encoded RGB channels, the L (lightness) of HSL.
|
||||
///
|
||||
/// The classic "Desaturate" command of many image editors uses this.
|
||||
#[label("Lightness (HSL)")]
|
||||
LightnessHsl,
|
||||
}
|
||||
|
||||
#[repr(u32)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
|
||||
#[widget(Radio)]
|
||||
pub enum RelativeAbsolute {
|
||||
#[default]
|
||||
Relative,
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// A group of colors whose inks the Selective Color adjustment offsets.
|
||||
#[repr(u32)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
|
||||
pub enum SelectiveColorChoice {
|
||||
#[default]
|
||||
Reds,
|
||||
Yellows,
|
||||
Greens,
|
||||
Cyans,
|
||||
Blues,
|
||||
Magentas,
|
||||
|
||||
#[menu_separator]
|
||||
Whites,
|
||||
Neutrals,
|
||||
Blacks,
|
||||
}
|
||||
|
||||
/// One channel's Levels record: percentage input and output points and the midtones gamma.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct LevelsRecord {
|
||||
pub shadows: f64,
|
||||
pub midtones: f64,
|
||||
pub highlights: f64,
|
||||
pub output_minimums: f64,
|
||||
pub output_maximums: f64,
|
||||
}
|
||||
|
||||
/// The composite record that the three color channels pass through after their own, and the alpha record that stands apart.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct LevelsSettings {
|
||||
pub composite: LevelsRecord,
|
||||
pub red: LevelsRecord,
|
||||
pub green: LevelsRecord,
|
||||
pub blue: LevelsRecord,
|
||||
pub alpha: LevelsRecord,
|
||||
}
|
||||
|
||||
/// The composite curve that the three color channels pass through after their own, and the alpha curve that stands apart.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct CurvesSettings {
|
||||
pub composite: TransferCurve,
|
||||
pub red: TransferCurve,
|
||||
pub green: TransferCurve,
|
||||
pub blue: TransferCurve,
|
||||
pub alpha: TransferCurve,
|
||||
}
|
||||
|
||||
/// The percentage each hue contributes to the gray, and the color tinting it when `use_tint` is set.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct BlackAndWhiteSettings {
|
||||
pub use_tint: bool,
|
||||
pub tint: Color,
|
||||
pub reds: f64,
|
||||
pub yellows: f64,
|
||||
pub greens: f64,
|
||||
pub cyans: f64,
|
||||
pub blues: f64,
|
||||
pub magentas: f64,
|
||||
}
|
||||
|
||||
/// One set of Hue/Saturation sliders: a hue in degrees and saturation and lightness percentages.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueSaturationSliders {
|
||||
pub hue: f64,
|
||||
pub saturation: f64,
|
||||
pub lightness: f64,
|
||||
}
|
||||
|
||||
/// The sliders for one range of hues, which apply fully from the range start to its end, fading out at the falloff ends. Edges are in degrees.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueRangeSettings {
|
||||
pub sliders: HueSaturationSliders,
|
||||
pub falloff_start: f64,
|
||||
pub range_start: f64,
|
||||
pub range_end: f64,
|
||||
pub falloff_end: f64,
|
||||
}
|
||||
|
||||
/// The master sliders shift every color, each hue range adds its own, and colorizing replaces them all with an absolute hue and saturation.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueSaturationSettings {
|
||||
pub master: HueSaturationSliders,
|
||||
pub colorize: bool,
|
||||
pub colorize_sliders: HueSaturationSliders,
|
||||
pub reds: HueRangeSettings,
|
||||
pub yellows: HueRangeSettings,
|
||||
pub greens: HueRangeSettings,
|
||||
pub cyans: HueRangeSettings,
|
||||
pub blues: HueRangeSettings,
|
||||
pub magentas: HueRangeSettings,
|
||||
}
|
||||
|
||||
/// The percentages of each source channel, plus a constant, that sum to one output channel.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelMixerRow {
|
||||
pub red: f64,
|
||||
pub green: f64,
|
||||
pub blue: f64,
|
||||
pub constant: f64,
|
||||
}
|
||||
|
||||
/// A row for each output channel, or for the single gray channel when monochrome.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelMixerSettings {
|
||||
pub monochrome: bool,
|
||||
pub monochrome_mix: ChannelMixerRow,
|
||||
pub red: ChannelMixerRow,
|
||||
pub green: ChannelMixerRow,
|
||||
pub blue: ChannelMixerRow,
|
||||
}
|
||||
|
||||
/// Percentage offsets to the cyan, magenta, yellow, and black inks of one group of colors.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct SelectiveColorInks {
|
||||
pub cyan: f64,
|
||||
pub magenta: f64,
|
||||
pub yellow: f64,
|
||||
pub black: f64,
|
||||
}
|
||||
|
||||
/// The ink offsets of each group of colors, and whether they are relative to the inks already present.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct SelectiveColorSettings {
|
||||
pub mode: RelativeAbsolute,
|
||||
pub reds: SelectiveColorInks,
|
||||
pub yellows: SelectiveColorInks,
|
||||
pub greens: SelectiveColorInks,
|
||||
pub cyans: SelectiveColorInks,
|
||||
pub blues: SelectiveColorInks,
|
||||
pub magentas: SelectiveColorInks,
|
||||
pub whites: SelectiveColorInks,
|
||||
pub neutrals: SelectiveColorInks,
|
||||
pub blacks: SelectiveColorInks,
|
||||
}
|
||||
|
||||
/// Percentage shifts along the three opponent color axes for one tonal range.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ColorBalanceShifts {
|
||||
pub cyan_red: f64,
|
||||
pub magenta_green: f64,
|
||||
pub yellow_blue: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ColorBalanceSettings {
|
||||
pub shadows: ColorBalanceShifts,
|
||||
pub midtones: ColorBalanceShifts,
|
||||
pub highlights: ColorBalanceShifts,
|
||||
pub preserve_luminosity: bool,
|
||||
}
|
||||
|
||||
/// The attribute key of a parameter in one of a node's groups of parameters, which the node names with the group's prefix.
|
||||
fn grouped_key(group: &str, parameter: &str) -> String {
|
||||
if group.is_empty() { parameter.to_string() } else { format!("{group}_{parameter}") }
|
||||
}
|
||||
|
||||
impl LevelsRecord {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
||||
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
||||
visitor.parameter(&grouped_key(group, "highlights"), &mut self.highlights, 100.);
|
||||
visitor.parameter(&grouped_key(group, "output_minimums"), &mut self.output_minimums, 0.);
|
||||
visitor.parameter(&grouped_key(group, "output_maximums"), &mut self.output_maximums, 100.);
|
||||
}
|
||||
}
|
||||
|
||||
impl HueSaturationSliders {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [hue, saturation, lightness]: [f64; 3]) {
|
||||
visitor.parameter(&grouped_key(group, "hue"), &mut self.hue, hue);
|
||||
visitor.parameter(&grouped_key(group, "saturation"), &mut self.saturation, saturation);
|
||||
visitor.parameter(&grouped_key(group, "lightness"), &mut self.lightness, lightness);
|
||||
}
|
||||
}
|
||||
|
||||
impl HueRangeSettings {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [falloff_start, range_start, range_end, falloff_end]: [f64; 4]) {
|
||||
self.sliders.visit_parameters(visitor, group, [0.; 3]);
|
||||
visitor.parameter(&grouped_key(group, "falloff_start"), &mut self.falloff_start, falloff_start);
|
||||
visitor.parameter(&grouped_key(group, "range_start"), &mut self.range_start, range_start);
|
||||
visitor.parameter(&grouped_key(group, "range_end"), &mut self.range_end, range_end);
|
||||
visitor.parameter(&grouped_key(group, "falloff_end"), &mut self.falloff_end, falloff_end);
|
||||
}
|
||||
}
|
||||
|
||||
impl ChannelMixerRow {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [red, green, blue, constant]: [f64; 4]) {
|
||||
visitor.parameter(&grouped_key(group, "red"), &mut self.red, red);
|
||||
visitor.parameter(&grouped_key(group, "green"), &mut self.green, green);
|
||||
visitor.parameter(&grouped_key(group, "blue"), &mut self.blue, blue);
|
||||
visitor.parameter(&grouped_key(group, "constant"), &mut self.constant, constant);
|
||||
}
|
||||
}
|
||||
|
||||
impl SelectiveColorInks {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "cyan"), &mut self.cyan, 0.);
|
||||
visitor.parameter(&grouped_key(group, "magenta"), &mut self.magenta, 0.);
|
||||
visitor.parameter(&grouped_key(group, "yellow"), &mut self.yellow, 0.);
|
||||
visitor.parameter(&grouped_key(group, "black"), &mut self.black, 0.);
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorBalanceShifts {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "cyan_red"), &mut self.cyan_red, 0.);
|
||||
visitor.parameter(&grouped_key(group, "magenta_green"), &mut self.magenta_green, 0.);
|
||||
visitor.parameter(&grouped_key(group, "yellow_blue"), &mut self.yellow_blue, 0.);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
//! An item's effects: an ordered list of image operations on the pixels the item renders to, stored in the `ATTR_EFFECTS` attribute.
|
||||
//! Each row is an [`EffectKind`] whose parameters ride its item as attributes, read as their defaults when absent.
|
||||
//! Each renderer decodes the rows into [`EffectOperation`]s and carries them out its own way, at the resolution of each render.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
use std::fmt::Debug;
|
||||
use vector_types::vector::style::StrokeAlign;
|
||||
|
||||
/// The image operation an [`Effect`] carries out.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash)]
|
||||
pub enum EffectKind {
|
||||
/// Softens the content by blurring it.
|
||||
#[default]
|
||||
Blur,
|
||||
/// Casts the content's silhouette as a soft shadow beneath it.
|
||||
DropShadow,
|
||||
/// Casts a soft shadow inward from the content's edges, as if it were cut out of the surface.
|
||||
InnerShadow,
|
||||
/// Surrounds the content with a soft glow of its silhouette.
|
||||
OuterGlow,
|
||||
/// Glows inward from the content's edges, or outward from its center.
|
||||
InnerGlow,
|
||||
/// Shades the content's interior with soft bands from its silhouette cast two ways.
|
||||
Satin,
|
||||
/// Draws a band of color along the content's silhouette.
|
||||
Outline,
|
||||
/// Lights the content as if raised from the surface or pressed into it, with highlights and shadows along its edges.
|
||||
BevelAndEmboss,
|
||||
/// Paints over the content within its silhouette, mixing with its colors by a blend mode. A solid color paint is the color overlay adjustment.
|
||||
PaintOverlay,
|
||||
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
MakeOpaque,
|
||||
BrightnessContrast,
|
||||
Levels,
|
||||
Curves,
|
||||
BlackAndWhite,
|
||||
HueSaturation,
|
||||
Invert,
|
||||
Threshold,
|
||||
GradientMap,
|
||||
Vibrance,
|
||||
ChannelMixer,
|
||||
SelectiveColor,
|
||||
Posterize,
|
||||
Exposure,
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Blur => "Blur",
|
||||
Self::DropShadow => "Drop Shadow",
|
||||
Self::InnerShadow => "Inner Shadow",
|
||||
Self::OuterGlow => "Outer Glow",
|
||||
Self::InnerGlow => "Inner Glow",
|
||||
Self::Satin => "Satin",
|
||||
Self::Outline => "Outline",
|
||||
Self::BevelAndEmboss => "Bevel & Emboss",
|
||||
Self::PaintOverlay => "Paint Overlay",
|
||||
Self::Desaturate => "Desaturate",
|
||||
Self::GammaCorrection => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
Self::BrightnessContrast => "Brightness/Contrast",
|
||||
Self::Levels => "Levels",
|
||||
Self::Curves => "Curves",
|
||||
Self::BlackAndWhite => "Black & White",
|
||||
Self::HueSaturation => "Hue/Saturation",
|
||||
Self::Invert => "Invert",
|
||||
Self::Threshold => "Threshold",
|
||||
Self::GradientMap => "Gradient Map",
|
||||
Self::Vibrance => "Vibrance",
|
||||
Self::ChannelMixer => "Channel Mixer",
|
||||
Self::SelectiveColor => "Selective Color",
|
||||
Self::Posterize => "Posterize",
|
||||
Self::Exposure => "Exposure",
|
||||
Self::ColorBalance => "Color Balance",
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an inner glow starts from.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum GlowSource {
|
||||
/// Glows inward from the edges.
|
||||
#[default]
|
||||
Edge,
|
||||
/// Glows outward from the center.
|
||||
Center,
|
||||
}
|
||||
|
||||
/// Which slopes a bevel shapes from the content's edges.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum BevelStyle {
|
||||
/// Slopes up from the edges into the content.
|
||||
#[default]
|
||||
InnerBevel,
|
||||
/// Slopes down from the edges away from the content.
|
||||
OuterBevel,
|
||||
/// Slopes across the edges, half inside the content and half outside.
|
||||
Emboss,
|
||||
/// Slopes away from the edges both ways, as if pressed into the surface along them.
|
||||
PillowEmboss,
|
||||
}
|
||||
|
||||
/// Whether a bevel rises from the surface or sinks into it.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum BevelDirection {
|
||||
/// Raised from the surface.
|
||||
#[default]
|
||||
Up,
|
||||
/// Pressed into the surface.
|
||||
Down,
|
||||
}
|
||||
|
||||
/// The deviation of the blur that rounds a bevel's slopes of `size`, in the same units.
|
||||
pub fn bevel_smoothing(size: f64) -> f64 {
|
||||
size.max(0.) / 4.
|
||||
}
|
||||
|
||||
/// The unit vector toward a bevel's light from its `angle` and `altitude` in degrees, with `lengths_to_target` mapping document directions into the y-down space it's lit in.
|
||||
pub fn bevel_light(angle: f64, altitude: f64, lengths_to_target: DMat2) -> DVec3 {
|
||||
let (angle, altitude) = (angle.to_radians(), altitude.clamp(0., 90.).to_radians());
|
||||
let across = (lengths_to_target * DVec2::new(angle.cos(), -angle.sin())).try_normalize().unwrap_or(DVec2::X);
|
||||
(across * altitude.cos()).extend(altitude.sin())
|
||||
}
|
||||
|
||||
/// An overlay's paint with its unit square fitted to `content_bounds`, the content's extent in the space it's drawn in, if it's a gradient or image without its own placement.
|
||||
pub fn fitted_paint(paint: &Graphic, content_bounds: [DVec2; 2]) -> Option<Graphic> {
|
||||
let unplaced = match paint {
|
||||
Graphic::Gradient(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterCPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterGPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
_ => false,
|
||||
};
|
||||
if !unplaced {
|
||||
return None;
|
||||
}
|
||||
|
||||
let fit = DAffine2::from_translation(content_bounds[0]) * DAffine2::from_scale(content_bounds[1] - content_bounds[0]);
|
||||
let mut paint = paint.clone();
|
||||
match &mut paint {
|
||||
Graphic::Gradient(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterCPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterGPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
_ => {}
|
||||
}
|
||||
Some(paint)
|
||||
}
|
||||
|
||||
/// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item.
|
||||
/// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct Effect(pub Item<EffectKind>);
|
||||
|
||||
impl Effect {
|
||||
/// Creates an effect row carrying out the given operation, stamping only the parameters that differ from their implicit defaults.
|
||||
pub fn new(operation: &EffectOperation) -> Self {
|
||||
let mut item = Item::new_from_element(operation.kind());
|
||||
operation.clone().visit_parameters(&mut WriteParameters(&mut item));
|
||||
Self(item)
|
||||
}
|
||||
|
||||
/// This effect's kind.
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
*self.0.element()
|
||||
}
|
||||
|
||||
/// Decodes the parameters into an [`EffectOperation`], falling back to the default for any absent attribute.
|
||||
pub fn operation(&self) -> EffectOperation {
|
||||
let mut operation = EffectOperation::placeholder(self.kind());
|
||||
operation.visit_parameters(&mut ReadParameters(&self.0));
|
||||
|
||||
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
|
||||
match operation {
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: Graphic::Color(color),
|
||||
blend_mode,
|
||||
opacity,
|
||||
} => EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: *color.element(),
|
||||
blend_mode,
|
||||
opacity,
|
||||
}),
|
||||
operation => operation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An item's ordered list of effects. A blur acts on the result of those before it, while shadows and glows are cast from the content and stack in order beneath it (or within it, for an inner shadow).
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct Effects(pub List<Effect>);
|
||||
|
||||
impl Effects {
|
||||
/// Creates the list of rows carrying out the given operations in order.
|
||||
pub fn from_operations(operations: impl IntoIterator<Item = EffectOperation>) -> Self {
|
||||
let mut effects = Self::default();
|
||||
for operation in operations {
|
||||
effects.0.push(Item::new_from_element(Effect::new(&operation)));
|
||||
}
|
||||
effects
|
||||
}
|
||||
|
||||
/// The effects in the order they're carried out.
|
||||
pub fn effects(&self) -> impl Iterator<Item = &Effect> {
|
||||
self.0.iter_element_values()
|
||||
}
|
||||
|
||||
/// The effects after the first `count`.
|
||||
pub fn after(&self, count: usize) -> Self {
|
||||
let mut remaining = Self::default();
|
||||
for effect in self.effects().skip(count) {
|
||||
remaining.0.push(Item::new_from_element(effect.clone()));
|
||||
}
|
||||
remaining
|
||||
}
|
||||
|
||||
/// The effects decoded into the operations renderers carry out, in order.
|
||||
pub fn operations(&self) -> impl Iterator<Item = EffectOperation> + '_ {
|
||||
self.effects().map(Effect::operation)
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint, in document pixels.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.reach()).sum()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// How far an outline of `weight` reaches outside the silhouette's edge and inside it, by where it's aligned.
|
||||
pub fn outline_extents(weight: f64, align: StrokeAlign) -> (f64, f64) {
|
||||
match align {
|
||||
StrokeAlign::Outside => (weight, 0.),
|
||||
StrokeAlign::Inside => (0., weight),
|
||||
StrokeAlign::Center => (weight / 2., weight / 2.),
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends an effect to the item's list, after those already applied to it.
|
||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS).0.push(Item::new_from_element(effect));
|
||||
}
|
||||
|
||||
/// An effect's parameters decoded from its row, the form that renderers carry it out from. Lengths are in document pixels.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EffectOperation {
|
||||
Blur {
|
||||
/// The standard deviation of the Gaussian, or the half width of the box.
|
||||
radius: f64,
|
||||
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
|
||||
box_blur: bool,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
DropShadow {
|
||||
color: Color,
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
InnerShadow {
|
||||
color: Color,
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
OuterGlow {
|
||||
color: Color,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
InnerGlow {
|
||||
color: Color,
|
||||
blur: f64,
|
||||
/// How far the glow grows into the content before it softens.
|
||||
choke: f64,
|
||||
source: GlowSource,
|
||||
},
|
||||
Satin {
|
||||
color: Color,
|
||||
/// How far each of the two casts of the silhouette is moved, in opposite directions.
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
invert: bool,
|
||||
},
|
||||
Outline {
|
||||
color: Color,
|
||||
weight: f64,
|
||||
align: StrokeAlign,
|
||||
},
|
||||
BevelAndEmboss {
|
||||
style: BevelStyle,
|
||||
/// How steep the slopes are, as a percentage.
|
||||
depth: f64,
|
||||
direction: BevelDirection,
|
||||
/// How wide the slopes are.
|
||||
size: f64,
|
||||
/// How much the highlights and shadows are blurred.
|
||||
soften: f64,
|
||||
/// The direction the light comes from, in degrees counterclockwise from the right.
|
||||
angle: f64,
|
||||
/// How high the light is above the surface, in degrees from flat to straight overhead.
|
||||
altitude: f64,
|
||||
highlight_color: Color,
|
||||
shadow_color: Color,
|
||||
},
|
||||
/// Paints over the content with a paint other than a solid color, since a solid one decodes into the color overlay adjustment instead.
|
||||
PaintOverlay {
|
||||
/// Placed in the space the content's item is, or fitted to the content's bounds if it's a gradient or image without its own placement.
|
||||
paint: Graphic,
|
||||
blend_mode: BlendMode,
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
Adjustment(Adjustment),
|
||||
}
|
||||
|
||||
impl EffectOperation {
|
||||
/// The operation an effect of this kind carries out when its row gives none of its parameters, matching the defaults of the node that stamps it.
|
||||
pub fn default_for(kind: EffectKind) -> Self {
|
||||
Effect(Item::new_from_element(kind)).operation()
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
match self {
|
||||
Self::Blur { .. } => EffectKind::Blur,
|
||||
Self::DropShadow { .. } => EffectKind::DropShadow,
|
||||
Self::InnerShadow { .. } => EffectKind::InnerShadow,
|
||||
Self::OuterGlow { .. } => EffectKind::OuterGlow,
|
||||
Self::InnerGlow { .. } => EffectKind::InnerGlow,
|
||||
Self::Satin { .. } => EffectKind::Satin,
|
||||
Self::Outline { .. } => EffectKind::Outline,
|
||||
Self::BevelAndEmboss { .. } => EffectKind::BevelAndEmboss,
|
||||
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Adjustment(adjustment) => adjustment.kind(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How far past the content this operation can paint, or reads from, in document pixels.
|
||||
pub fn reach(&self) -> f64 {
|
||||
// A Gaussian is negligible past three standard deviations
|
||||
match self {
|
||||
Self::Blur { radius, .. } => 3. * radius.max(0.),
|
||||
Self::DropShadow { offset, blur, spread, .. } => offset.length() + spread.max(0.) + 3. * blur.max(0.),
|
||||
Self::InnerShadow { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
|
||||
Self::OuterGlow { blur, spread, .. } => spread.max(0.) + 3. * blur.max(0.),
|
||||
Self::InnerGlow { blur, choke, .. } => choke.max(0.) + 3. * blur.max(0.),
|
||||
Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
|
||||
Self::Outline { weight, .. } => weight.max(0.),
|
||||
Self::BevelAndEmboss { size, soften, .. } => size.max(0.) + 3. * (soften.max(0.) + bevel_smoothing(*size)),
|
||||
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
/// An operation of this kind with arbitrary parameters, for a visitor to fill in.
|
||||
fn placeholder(kind: EffectKind) -> Self {
|
||||
match kind {
|
||||
EffectKind::Blur => Self::Blur {
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
},
|
||||
EffectKind::DropShadow => Self::DropShadow {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::InnerShadow => Self::InnerShadow {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::OuterGlow => Self::OuterGlow {
|
||||
color: Color::TRANSPARENT,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::InnerGlow => Self::InnerGlow {
|
||||
color: Color::TRANSPARENT,
|
||||
blur: 0.,
|
||||
choke: 0.,
|
||||
source: GlowSource::default(),
|
||||
},
|
||||
EffectKind::Satin => Self::Satin {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
invert: false,
|
||||
},
|
||||
EffectKind::Outline => Self::Outline {
|
||||
color: Color::TRANSPARENT,
|
||||
weight: 0.,
|
||||
align: StrokeAlign::default(),
|
||||
},
|
||||
EffectKind::BevelAndEmboss => Self::BevelAndEmboss {
|
||||
style: BevelStyle::default(),
|
||||
depth: 0.,
|
||||
direction: BevelDirection::default(),
|
||||
size: 0.,
|
||||
soften: 0.,
|
||||
angle: 0.,
|
||||
altitude: 0.,
|
||||
highlight_color: Color::TRANSPARENT,
|
||||
shadow_color: Color::TRANSPARENT,
|
||||
},
|
||||
EffectKind::PaintOverlay => Self::PaintOverlay {
|
||||
paint: Graphic::default(),
|
||||
blend_mode: BlendMode::default(),
|
||||
opacity: 0.,
|
||||
},
|
||||
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
|
||||
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
|
||||
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque),
|
||||
EffectKind::BrightnessContrast => Self::Adjustment(Adjustment::BrightnessContrast {
|
||||
brightness: 0.,
|
||||
contrast: 0.,
|
||||
use_classic: false,
|
||||
classic_pivot: 0.,
|
||||
}),
|
||||
EffectKind::Levels => Self::Adjustment(Adjustment::Levels(Default::default())),
|
||||
EffectKind::Curves => Self::Adjustment(Adjustment::Curves(Default::default())),
|
||||
EffectKind::BlackAndWhite => Self::Adjustment(Adjustment::BlackAndWhite(Default::default())),
|
||||
EffectKind::HueSaturation => Self::Adjustment(Adjustment::HueSaturation(Default::default())),
|
||||
EffectKind::Invert => Self::Adjustment(Adjustment::Invert),
|
||||
EffectKind::Threshold => Self::Adjustment(Adjustment::Threshold { min_luminance: 0., max_luminance: 0. }),
|
||||
EffectKind::GradientMap => Self::Adjustment(Adjustment::GradientMap {
|
||||
gradient: Default::default(),
|
||||
reverse: false,
|
||||
}),
|
||||
EffectKind::Vibrance => Self::Adjustment(Adjustment::Vibrance { vibrance: 0., saturation: 0. }),
|
||||
EffectKind::ChannelMixer => Self::Adjustment(Adjustment::ChannelMixer(Default::default())),
|
||||
EffectKind::SelectiveColor => Self::Adjustment(Adjustment::SelectiveColor(Default::default())),
|
||||
EffectKind::Posterize => Self::Adjustment(Adjustment::Posterize { levels: 0 }),
|
||||
EffectKind::Exposure => Self::Adjustment(Adjustment::Exposure {
|
||||
exposure: 0.,
|
||||
offset: 0.,
|
||||
gamma_correction: 0.,
|
||||
}),
|
||||
EffectKind::ColorBalance => Self::Adjustment(Adjustment::ColorBalance(Default::default())),
|
||||
EffectKind::PhotoFilter => Self::Adjustment(Adjustment::PhotoFilter {
|
||||
color: Color::TRANSPARENT,
|
||||
density: 0.,
|
||||
preserve_luminosity: false,
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visits each parameter with the attribute it rides and its implicit default, the one listing that writing and reading rows share.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
match self {
|
||||
Self::Blur { radius, box_blur, gamma } => {
|
||||
visitor.parameter("radius", radius, 0.);
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::DropShadow { color, offset, blur, spread } | Self::InnerShadow { color, offset, blur, spread } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
|
||||
visitor.parameter("offset", offset, DVec2::splat(4.));
|
||||
visitor.parameter("blur", blur, 4.);
|
||||
visitor.parameter("spread", spread, 0.);
|
||||
}
|
||||
Self::OuterGlow { color, blur, spread } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
|
||||
visitor.parameter("blur", blur, 8.);
|
||||
visitor.parameter("spread", spread, 0.);
|
||||
}
|
||||
Self::InnerGlow { color, blur, choke, source } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
|
||||
visitor.parameter("blur", blur, 8.);
|
||||
visitor.parameter("choke", choke, 0.);
|
||||
visitor.parameter("source", source, GlowSource::default());
|
||||
}
|
||||
Self::Satin { color, offset, blur, invert } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
|
||||
visitor.parameter("offset", offset, DVec2::new(10., 4.));
|
||||
visitor.parameter("blur", blur, 14.);
|
||||
visitor.parameter("invert", invert, true);
|
||||
}
|
||||
Self::Outline { color, weight, align } => {
|
||||
visitor.parameter("color", color, Color::BLACK);
|
||||
visitor.parameter("weight", weight, 3.);
|
||||
visitor.parameter("align", align, StrokeAlign::Outside);
|
||||
}
|
||||
Self::BevelAndEmboss {
|
||||
style,
|
||||
depth,
|
||||
direction,
|
||||
size,
|
||||
soften,
|
||||
angle,
|
||||
altitude,
|
||||
highlight_color,
|
||||
shadow_color,
|
||||
} => {
|
||||
visitor.parameter("style", style, BevelStyle::default());
|
||||
visitor.parameter("depth", depth, 100.);
|
||||
visitor.parameter("direction", direction, BevelDirection::default());
|
||||
visitor.parameter("size", size, 5.);
|
||||
visitor.parameter("soften", soften, 0.);
|
||||
visitor.parameter("angle", angle, 120.);
|
||||
visitor.parameter("altitude", altitude, 30.);
|
||||
visitor.parameter("highlight_color", highlight_color, Color::from(SRGBA8::new(0xff, 0xff, 0xff, 0xbf)));
|
||||
visitor.parameter("shadow_color", shadow_color, Color::from(SRGBA8::new(0, 0, 0, 0xbf)));
|
||||
}
|
||||
Self::PaintOverlay { paint, blend_mode, opacity } => {
|
||||
visitor.parameter("paint", paint, Graphic::from(Color::BLACK));
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a value needs to ride an attribute.
|
||||
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
|
||||
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
|
||||
|
||||
/// Handles each parameter of an operation, given the attribute key it rides and its implicit default.
|
||||
pub(crate) trait ParameterVisitor {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
|
||||
}
|
||||
|
||||
/// Stamps each parameter that differs from its default onto a row.
|
||||
struct WriteParameters<'a>(&'a mut Item<EffectKind>);
|
||||
|
||||
impl ParameterVisitor for WriteParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
if *value != default {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads each parameter from a row, or its default where the row lacks it.
|
||||
struct ReadParameters<'a>(&'a Item<EffectKind>);
|
||||
|
||||
impl ParameterVisitor for ReadParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
*value = self.0.attribute::<T>(key).cloned().unwrap_or(default);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vector_types::{Gradient, GradientStop};
|
||||
|
||||
#[test]
|
||||
fn rows_round_trip_their_operations_eliding_defaults() {
|
||||
let operations = [
|
||||
EffectOperation::Blur {
|
||||
radius: 6.,
|
||||
box_blur: true,
|
||||
gamma: false,
|
||||
},
|
||||
EffectOperation::default_for(EffectKind::DropShadow),
|
||||
EffectOperation::InnerShadow {
|
||||
color: Color::RED,
|
||||
offset: DVec2::new(-2., 3.),
|
||||
blur: 1.,
|
||||
spread: 5.,
|
||||
},
|
||||
EffectOperation::OuterGlow {
|
||||
color: Color::BLUE,
|
||||
blur: 8.,
|
||||
spread: 2.,
|
||||
},
|
||||
EffectOperation::InnerGlow {
|
||||
color: Color::GREEN,
|
||||
blur: 3.,
|
||||
choke: 1.,
|
||||
source: GlowSource::Center,
|
||||
},
|
||||
EffectOperation::Satin {
|
||||
color: Color::BLACK,
|
||||
offset: DVec2::new(5., -6.),
|
||||
blur: 2.,
|
||||
invert: false,
|
||||
},
|
||||
EffectOperation::Outline {
|
||||
color: Color::RED,
|
||||
weight: 7.,
|
||||
align: StrokeAlign::Center,
|
||||
},
|
||||
EffectOperation::BevelAndEmboss {
|
||||
style: BevelStyle::PillowEmboss,
|
||||
depth: 250.,
|
||||
direction: BevelDirection::Down,
|
||||
size: 12.,
|
||||
soften: 2.,
|
||||
angle: -45.,
|
||||
altitude: 60.,
|
||||
highlight_color: Color::YELLOW,
|
||||
shadow_color: Color::BLUE,
|
||||
},
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: Graphic::from(Gradient::new([0., 1.].map(|position| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: Color::from_rgbaf32_unchecked(position as f32, 0., 1., 1.),
|
||||
}))),
|
||||
blend_mode: BlendMode::Multiply,
|
||||
opacity: 60.,
|
||||
},
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::GREEN,
|
||||
blend_mode: BlendMode::Screen,
|
||||
opacity: 100.,
|
||||
}),
|
||||
];
|
||||
|
||||
for operation in operations {
|
||||
assert_eq!(Effect::new(&operation).operation(), operation);
|
||||
}
|
||||
|
||||
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
|
||||
let solid = EffectOperation::PaintOverlay {
|
||||
paint: Graphic::from(Color::RED),
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
};
|
||||
let solid_row = Effect::new(&solid);
|
||||
assert_eq!(solid_row.kind(), EffectKind::PaintOverlay);
|
||||
assert_eq!(
|
||||
solid_row.operation(),
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
})
|
||||
);
|
||||
|
||||
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
|
||||
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() {
|
||||
use EffectKind::*;
|
||||
let kinds = [
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
MakeOpaque,
|
||||
BrightnessContrast,
|
||||
Levels,
|
||||
Curves,
|
||||
BlackAndWhite,
|
||||
HueSaturation,
|
||||
Invert,
|
||||
Threshold,
|
||||
GradientMap,
|
||||
Vibrance,
|
||||
ChannelMixer,
|
||||
SelectiveColor,
|
||||
Posterize,
|
||||
Exposure,
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
let operation = EffectOperation::default_for(kind);
|
||||
assert_eq!(operation.kind(), kind);
|
||||
assert_eq!(Effect::new(&operation).0.attributes().iter_any().count(), 0, "{kind} stamps no defaults");
|
||||
}
|
||||
|
||||
// A parameter in one of the node's groups rides the attribute named with the group's prefix
|
||||
let mut levels = EffectOperation::default_for(Levels);
|
||||
if let EffectOperation::Adjustment(Adjustment::Levels(settings)) = &mut levels {
|
||||
settings.blue.midtones = 1.5;
|
||||
}
|
||||
let row = Effect::new(&levels);
|
||||
assert_eq!(row.0.attribute::<f64>("blue_midtones"), Some(&1.5));
|
||||
assert_eq!(row.operation(), levels);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
|
||||
/// Style of noise pattern.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum NoiseType {
|
||||
#[default]
|
||||
Perlin,
|
||||
#[label("OpenSimplex2")]
|
||||
OpenSimplex2,
|
||||
#[label("OpenSimplex2S")]
|
||||
OpenSimplex2S,
|
||||
Cellular,
|
||||
ValueCubic,
|
||||
Value,
|
||||
WhiteNoise,
|
||||
}
|
||||
|
||||
/// Style of layered levels of the noise pattern.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
pub enum FractalType {
|
||||
#[default]
|
||||
None,
|
||||
#[label("Fractional Brownian Motion")]
|
||||
FBm,
|
||||
Ridged,
|
||||
PingPong,
|
||||
#[label("Progressive (Domain Warp Only)")]
|
||||
DomainWarpProgressive,
|
||||
#[label("Independent (Domain Warp Only)")]
|
||||
DomainWarpIndependent,
|
||||
}
|
||||
|
||||
/// Distance function used by the cellular noise.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
pub enum CellularDistanceFunction {
|
||||
#[default]
|
||||
Euclidean,
|
||||
#[label("Euclidean Squared (Faster)")]
|
||||
EuclideanSq,
|
||||
Manhattan,
|
||||
Hybrid,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
pub enum CellularReturnType {
|
||||
CellValue,
|
||||
#[default]
|
||||
#[label("Nearest (F1)")]
|
||||
Nearest,
|
||||
#[label("Next Nearest (F2)")]
|
||||
NextNearest,
|
||||
#[label("Average (F1 / 2 + F2 / 2)")]
|
||||
Average,
|
||||
#[label("Difference (F2 - F1)")]
|
||||
Difference,
|
||||
#[label("Product (F2 * F1 / 2)")]
|
||||
Product,
|
||||
#[label("Division (F1 / F2)")]
|
||||
Division,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(dyn_any::DynAny)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum DomainWarpType {
|
||||
#[default]
|
||||
None,
|
||||
#[label("OpenSimplex2")]
|
||||
OpenSimplex2,
|
||||
#[label("OpenSimplex2 Reduced")]
|
||||
OpenSimplex2Reduced,
|
||||
BasicGrid,
|
||||
}
|
||||
|
||||
/// The settings of a noise pattern, whose lengths are measured in the document units of the space it's sampled in.
|
||||
#[derive(Debug, Clone, PartialEq, CacheHash)]
|
||||
pub struct NoiseSettings {
|
||||
pub seed: i64,
|
||||
pub scale: f64,
|
||||
pub noise_type: NoiseType,
|
||||
pub domain_warp_type: DomainWarpType,
|
||||
pub domain_warp_amplitude: f64,
|
||||
pub fractal_type: FractalType,
|
||||
pub fractal_octaves: i64,
|
||||
pub fractal_lacunarity: f64,
|
||||
pub fractal_gain: f64,
|
||||
pub fractal_weighted_strength: f64,
|
||||
pub fractal_ping_pong_strength: f64,
|
||||
pub cellular_distance_function: CellularDistanceFunction,
|
||||
pub cellular_return_type: CellularReturnType,
|
||||
pub cellular_jitter: f64,
|
||||
}
|
||||
|
||||
/// A procedural pattern, a function of position in its own space that renders across any area at any resolution.
|
||||
#[derive(Debug, Clone, PartialEq, CacheHash)]
|
||||
pub enum GeneratorPattern {
|
||||
Noise(NoiseSettings),
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
pub mod adjustment;
|
||||
pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod effects;
|
||||
pub mod generator;
|
||||
pub mod graphic;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
@@ -8,8 +11,10 @@ pub use raster_types;
|
||||
pub use vector_types;
|
||||
|
||||
// Re-export commonly used types at the crate root
|
||||
pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
|
||||
pub mod migrations {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "raster-kernels"
|
||||
description = "The GPU kernels of Graphene's raster operations, with the per-color CPU mapping of those that have one"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,29 @@
|
||||
//! The kernels blending one color with another.
|
||||
|
||||
use crate::{MapColor, Wgsl, gpu_param_enum, gpu_params};
|
||||
use core_types::blending::{BlendMode, apply_blend_mode};
|
||||
use core_types::color::Color;
|
||||
|
||||
gpu_param_enum!(i32: BlendMode);
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct ColorOverlay {
|
||||
pub(crate) color: Color,
|
||||
pub(crate) blend_mode: BlendMode,
|
||||
pub(crate) opacity: f32,
|
||||
}
|
||||
}
|
||||
|
||||
impl MapColor for ColorOverlay {
|
||||
fn map_cpu(&self, pixel: Color) -> Color {
|
||||
let overlay = apply_blend_mode(self.color, pixel, self.blend_mode);
|
||||
let mix = |image: f32, overlay: f32| image + (overlay - image) * self.opacity;
|
||||
|
||||
Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a())
|
||||
}
|
||||
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(format!("{}\n{}", include_str!("wgsl/blending.wgsl"), include_str!("wgsl/color_overlay.wgsl")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! The passes of a Gaussian or box blur, which halve an image until its kernel fits one pass, blur it along each axis, and double it back.
|
||||
|
||||
use crate::{RasterKernel, ToGpuParams, Wgsl, gpu_param_enum, gpu_params};
|
||||
|
||||
/// The farthest texel from the center a blur pass weighs, beyond which the image is first halved until the kernel fits.
|
||||
pub const MAX_BLUR_REACH: i32 = 64;
|
||||
|
||||
/// The radius of a blur over texels `scale` image pixels wide, and the farthest texel from the center it weighs.
|
||||
///
|
||||
/// A box covers its whole texels and a fraction of the texel at each end, which keeps the window as wide as the whole pixel window of the unhalved image once halved,
|
||||
/// and a Gaussian leaves out the blur that halving and doubling the image add.
|
||||
pub fn blur_extent(radius: f64, box_blur: bool, scale: u32) -> (f32, i32) {
|
||||
let scale = scale as f64;
|
||||
if box_blur {
|
||||
let radius = ((radius as i32) as f64 + 0.5) / scale - 0.5;
|
||||
(radius as f32, radius.ceil() as i32)
|
||||
} else {
|
||||
let radius = (radius * radius - (scale * scale - 1.) / 3.).max(0.).sqrt() / scale;
|
||||
(radius as f32, (3. * radius).ceil() as i32)
|
||||
}
|
||||
}
|
||||
|
||||
/// The colors a blur pass reads from its input or writes to its output, around the premultiplied colors it sums.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[repr(u32)]
|
||||
pub enum BlurSpace {
|
||||
/// Values summed as they are, such as premultiplied colors or coverage.
|
||||
Premultiplied,
|
||||
/// Straight-alpha linear-light colors, premultiplied for summing.
|
||||
Linear,
|
||||
/// Straight-alpha linear-light colors, gamma-encoded and premultiplied for summing.
|
||||
Gamma,
|
||||
}
|
||||
|
||||
impl From<BlurSpace> for u32 {
|
||||
fn from(space: BlurSpace) -> Self {
|
||||
space as u32
|
||||
}
|
||||
}
|
||||
|
||||
gpu_param_enum!(u32: BlurSpace);
|
||||
|
||||
gpu_params! {
|
||||
/// Averages each 2x2 block of texels `scale` image pixels wide, weighed by how much of the `full_size` image each covers.
|
||||
#[derive(Clone)]
|
||||
pub struct BlurHalve {
|
||||
pub space: BlurSpace,
|
||||
pub scale: i32,
|
||||
pub full_size: [i32; 2],
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BlurHalve {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_halve.wgsl")))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// One axis of a blur over texels `scale` image pixels wide, each weighed by how much of the `full_size` image it covers.
|
||||
#[derive(Clone)]
|
||||
pub struct BlurPass {
|
||||
pub radius: f32,
|
||||
pub reach: i32,
|
||||
pub box_blur: bool,
|
||||
pub space: BlurSpace,
|
||||
pub scale: i32,
|
||||
pub full_size: [i32; 2],
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BlurHorizontal(pub BlurPass);
|
||||
|
||||
impl ToGpuParams for BlurHorizontal {
|
||||
type Params = BlurPass;
|
||||
fn to_params(&self) -> BlurPass {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BlurHorizontal {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_horizontal.wgsl")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads its input in pairs of texels sampled bilinearly between them, so the input must be in a filterable format.
|
||||
pub struct BlurVertical(pub BlurPass);
|
||||
|
||||
impl ToGpuParams for BlurVertical {
|
||||
type Params = BlurPass;
|
||||
fn to_params(&self) -> BlurPass {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BlurVertical {
|
||||
const INPUTS: usize = 1;
|
||||
const FILTERED: bool = true;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_vertical.wgsl")))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
pub struct BlurUpsample {
|
||||
pub scale: f32,
|
||||
pub space: BlurSpace,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BlurUpsample {
|
||||
const INPUTS: usize = 1;
|
||||
const FILTERED: bool = true;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(concat!(include_str!("wgsl/blur.wgsl"), include_str!("wgsl/blur_upsample.wgsl")))
|
||||
}
|
||||
}
|
||||
+36
-31
@@ -13,40 +13,46 @@ use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
pub const LUT_FILE_EXTENSIONS: &[&str] = &["cube", "3dl", "look", "csp", "icc", "icm"];
|
||||
|
||||
/// How many files keep their parse results after the adjustments that read them move on to other files.
|
||||
const MAX_PARSED_FILES: usize = 8;
|
||||
|
||||
/// A file's parse result, in the form the cache shares out.
|
||||
type ParsedLut = Result<Arc<Lut>, LutParseError>;
|
||||
|
||||
/// The last file a node parsed, kept as the node's own data so the file is not parsed anew each time the node runs again.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LutCache(Arc<Mutex<Option<(ResourceHash, ParsedLut)>>>);
|
||||
/// The files parsed most recently, least recent first, shared by every adjustment that reads a lookup table.
|
||||
static PARSED_FILES: Mutex<Vec<(ResourceHash, ParsedLut)>> = Mutex::new(Vec::new());
|
||||
|
||||
impl LutCache {
|
||||
/// [`Lut::parse`] for a resource, reusing the last result while the file's content hash stays the same.
|
||||
pub fn parse(&self, resource: &Resource) -> ParsedLut {
|
||||
// A lock poisoned by a panic elsewhere still guards a usable cache
|
||||
let mut cached = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
/// [`Lut::parse`] for a resource, reusing the result while recent adjustments keep reading a file with the same content hash.
|
||||
pub fn parse_cached(resource: &Resource) -> ParsedLut {
|
||||
// A lock poisoned by a panic elsewhere still guards a usable cache
|
||||
let mut parsed_files = PARSED_FILES.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
|
||||
let hash = resource.hash();
|
||||
if let Some((cached_hash, result)) = cached.as_ref()
|
||||
&& *cached_hash == hash
|
||||
{
|
||||
return result.clone();
|
||||
}
|
||||
|
||||
let result = Lut::parse(resource).map(Arc::new);
|
||||
*cached = Some((hash, result.clone()));
|
||||
result
|
||||
let hash = resource.hash();
|
||||
if let Some(index) = parsed_files.iter().position(|(parsed_hash, _)| *parsed_hash == hash) {
|
||||
let entry = parsed_files.remove(index);
|
||||
let result = entry.1.clone();
|
||||
parsed_files.push(entry);
|
||||
return result;
|
||||
}
|
||||
|
||||
let result = Lut::parse(resource).map(Arc::new);
|
||||
parsed_files.push((hash, result.clone()));
|
||||
let excess = parsed_files.len().saturating_sub(MAX_PARSED_FILES);
|
||||
parsed_files.drain(..excess);
|
||||
result
|
||||
}
|
||||
|
||||
/// Why a file could not be read as a lookup table.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum LutParseError {
|
||||
/// An ICC profile that describes a device's colors, not an "abstract" or "device link" profile that remaps them.
|
||||
#[error("The ICC profile describes a device's colors, but only abstract and device link profiles work as LUTs")]
|
||||
IccProfileClass,
|
||||
/// An ICC "abstract" profile that does not map Lab to Lab, or a "device link" profile that does not map RGB to RGB.
|
||||
#[error("The ICC profile's color spaces are unsupported, as a device link profile must map RGB to RGB and an abstract profile Lab to Lab")]
|
||||
IccColorSpaces,
|
||||
/// Not a lookup table in any of the formats, or one that is damaged.
|
||||
#[error("The file is not a LUT in a supported format, or it is damaged")]
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
@@ -93,7 +99,8 @@ impl Curve {
|
||||
return outputs[count - 1];
|
||||
}
|
||||
|
||||
let upper = inputs.partition_point(|&input| input <= value).min(count - 1);
|
||||
// A NaN value leaves the search without a segment, so the clamp keeps it in bounds
|
||||
let upper = inputs.partition_point(|&input| input <= value).clamp(1, count - 1);
|
||||
let lower = upper - 1;
|
||||
let t = (value - inputs[lower]) / (inputs[upper] - inputs[lower]).max(f32::EPSILON);
|
||||
outputs[lower] + t * (outputs[upper] - outputs[lower])
|
||||
@@ -468,18 +475,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cache_parses_a_file_once_until_the_file_changes() {
|
||||
let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n1 1 1\n".to_vec());
|
||||
let cache = LutCache::default();
|
||||
let first = cache.parse(&file).unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &cache.parse(&file).unwrap()));
|
||||
fn the_cache_parses_a_file_once_while_it_stays_recent() {
|
||||
let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n0.5 1 1\n".to_vec());
|
||||
let first = parse_cached(&file).unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &parse_cached(&file).unwrap()));
|
||||
|
||||
// A cloned node shares its cache
|
||||
assert!(Arc::ptr_eq(&first, &cache.clone().parse(&file).unwrap()));
|
||||
|
||||
// Another file takes its place, a failed one included
|
||||
assert!(cache.parse(&Resource::new(b"hello world".to_vec())).is_err());
|
||||
assert!(!Arc::ptr_eq(&first, &cache.parse(&file).unwrap()));
|
||||
// Enough other files push it out, failed ones included
|
||||
for index in 0..MAX_PARSED_FILES {
|
||||
assert!(parse_cached(&Resource::new(format!("not a table {index}").into_bytes())).is_err());
|
||||
}
|
||||
assert!(!Arc::ptr_eq(&first, &parse_cached(&file).unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
File renamed without changes.
+7
@@ -81,6 +81,13 @@ mod tests {
|
||||
assert_close(lut.apply([1., 0.5, 2.]), [0.5, 0.25, 1.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pre_lut_passes_a_value_that_is_not_a_number_through() {
|
||||
let text = "CSPLUTV100\n1D\n2\n0 2\n0 1\n2\n0 2\n0 1\n2\n0 2\n0 1\n2\n0 0 0\n1 1 1\n";
|
||||
let lut = Lut::parse(text.as_bytes()).unwrap();
|
||||
assert!(lut.apply([f32::NAN, 0.5, 2.])[0].is_nan());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pre_lut_under_two_points_is_identity() {
|
||||
let text = "CSPLUTV100\n1D\n0\n1\n0\n2\n0 0 0\n1 1 1\n";
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,263 @@
|
||||
//! The kernels of the passes that carry out an item's effects on the pixels of its content.
|
||||
//! They work on images of premultiplied gamma-encoded channels, as Vello GPU blends, and on coverage held in every channel.
|
||||
|
||||
use crate::{RasterKernel, Wgsl, gpu_params};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
|
||||
/// A color as the premultiplied, gamma-encoded channels the passes work with, carried in a [`Color`] to be passed to them.
|
||||
pub fn premultiplied_gamma_channels(color: Color) -> Color {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
Color::from_rgbaf32_unchecked(red * alpha, green * alpha, blue * alpha, alpha)
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The straight-alpha linear-light content, placed where its input lies, as the channels the passes work with, multiplied by `amount`.
|
||||
#[derive(Clone)]
|
||||
pub struct EffectEncode {
|
||||
pub amount: f32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for EffectEncode {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_encode.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The channels the passes work with, back into straight-alpha linear-light colors.
|
||||
#[derive(Clone)]
|
||||
pub struct EffectDecode {}
|
||||
}
|
||||
|
||||
impl RasterKernel for EffectDecode {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_decode.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The coverage of the content's silhouette, or of the area outside it if `inverse`, cast by its input's placement.
|
||||
#[derive(Clone)]
|
||||
pub struct CastSilhouette {
|
||||
pub inverse: bool,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for CastSilhouette {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_cast_silhouette.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The most coverage of its three inputs, the same coverage placed at the pixel and a step to either side along an axis.
|
||||
#[derive(Clone)]
|
||||
pub struct Dilate {}
|
||||
}
|
||||
|
||||
impl RasterKernel for Dilate {
|
||||
const INPUTS: usize = 3;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_dilate.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// A silhouette's coverage in `color`, given as [`premultiplied_gamma_channels`].
|
||||
#[derive(Clone)]
|
||||
pub struct Tint {
|
||||
pub color: Color,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for Tint {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_tint.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// Stacks a silhouette's coverage, tinted `color` (given as [`premultiplied_gamma_channels`]), over the shadows and glows beneath the content.
|
||||
#[derive(Clone)]
|
||||
pub struct Accumulate {
|
||||
pub color: Color,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for Accumulate {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_accumulate.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The image with a silhouette's coverage, tinted `color` (given as [`premultiplied_gamma_channels`]), placed over it within the full-strength content.
|
||||
#[derive(Clone)]
|
||||
pub struct CompositeWithin {
|
||||
pub color: Color,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for CompositeWithin {
|
||||
const INPUTS: usize = 3;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_composite_within.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The image with the shadows and glows beneath it, knocked out by the full-strength content.
|
||||
#[derive(Clone)]
|
||||
pub struct CompositeBeneath {}
|
||||
}
|
||||
|
||||
impl RasterKernel for CompositeBeneath {
|
||||
const INPUTS: usize = 3;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_composite_beneath.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The coverage of everything a coverage doesn't cover.
|
||||
#[derive(Clone)]
|
||||
pub struct InvertCoverage {}
|
||||
}
|
||||
|
||||
impl RasterKernel for InvertCoverage {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_invert_coverage.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The coverage of satin's shading, from the two casts of the silhouette.
|
||||
#[derive(Clone)]
|
||||
pub struct SatinShading {
|
||||
pub invert: bool,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for SatinShading {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_satin.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// Starts a jump flood from the texels inside the content's silhouette, or outside it if `inward`.
|
||||
#[derive(Clone)]
|
||||
pub struct JumpFloodSeed {
|
||||
pub inward: bool,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for JumpFloodSeed {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_jump_flood_seed.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// One step of a jump flood, spreading the nearest seeds found so far by `step` texels.
|
||||
#[derive(Clone)]
|
||||
pub struct JumpFloodStep {
|
||||
pub step: i32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for JumpFloodStep {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_jump_flood_step.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The coverage of the band `width` texels wide along the silhouette's edge, from a finished jump flood.
|
||||
#[derive(Clone)]
|
||||
pub struct EdgeBand {
|
||||
pub width: f32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for EdgeBand {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_edge_band.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// A bevel's height from 0 to 1, from the two finished jump floods across the silhouette's edge. `style` is a [`graphic_types::BevelStyle`].
|
||||
#[derive(Clone)]
|
||||
pub struct BevelHeight {
|
||||
pub size: f32,
|
||||
pub style: u32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BevelHeight {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_bevel_height.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The coverage of a bevel's highlight, or if `shadow` of its shadow, from its height lit from the direction of the unit vector `light`.
|
||||
#[derive(Clone)]
|
||||
pub struct BevelShading {
|
||||
pub slope: f32,
|
||||
pub light_x: f32,
|
||||
pub light_y: f32,
|
||||
pub light_z: f32,
|
||||
pub shadow: bool,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for BevelShading {
|
||||
const INPUTS: usize = 1;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_bevel_shading.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The first image, emptied wherever the second is empty, since an adjustment that changes alpha would otherwise conjure content from the empty space around it.
|
||||
#[derive(Clone)]
|
||||
pub struct KeepEmpty {}
|
||||
}
|
||||
|
||||
impl RasterKernel for KeepEmpty {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/effect_keep_empty.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
/// The image (input 0) with a straight-alpha linear-light paint (input 1) mixed over its colors by a blend mode, as much as the paint covers and `opacity` lets it, keeping the image's alpha.
|
||||
#[derive(Clone)]
|
||||
pub struct PaintOverlay {
|
||||
pub blend_mode: BlendMode,
|
||||
pub opacity: f32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for PaintOverlay {
|
||||
const INPUTS: usize = 2;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(format!("{}\n{}", include_str!("wgsl/blending.wgsl"), include_str!("wgsl/effect_paint_overlay.wgsl")))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
//! The kernels rendering each [`GeneratorPattern`] across any area of its space at any resolution.
|
||||
|
||||
use crate::{RasterKernel, RasterKernelVisitor, Wgsl, gpu_params};
|
||||
use glam::{DVec2, UVec2, Vec2};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
|
||||
|
||||
/// Hands `visitor` the kernel rendering `pattern` across `area` of its own space, from its minimum to its maximum corner, into a grid of `size` pixels.
|
||||
pub fn visit_generator_kernel<V: RasterKernelVisitor>(pattern: &GeneratorPattern, area: [DVec2; 2], size: UVec2, visitor: V) -> V::Output {
|
||||
let texel = ((area[1] - area[0]).as_vec2() / size.as_vec2()).to_array();
|
||||
let corner = area[0].as_vec2().to_array();
|
||||
|
||||
match pattern {
|
||||
GeneratorPattern::Noise(settings) => visit_noise_kernel(settings, corner, texel, visitor),
|
||||
GeneratorPattern::Mandelbrot => visitor.visit(&Mandelbrot {
|
||||
corner: (Vec2::from(corner) * 3. - Vec2::new(2., 1.5)).to_array(),
|
||||
texel: (Vec2::from(texel) * 3.).to_array(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_noise_kernel<V: RasterKernelVisitor>(settings: &NoiseSettings, corner: [f32; 2], texel: [f32; 2], visitor: V) -> V::Output {
|
||||
let NoiseSettings {
|
||||
seed,
|
||||
scale,
|
||||
noise_type,
|
||||
domain_warp_type,
|
||||
domain_warp_amplitude,
|
||||
fractal_type,
|
||||
fractal_octaves,
|
||||
fractal_lacunarity,
|
||||
fractal_gain,
|
||||
fractal_weighted_strength,
|
||||
fractal_ping_pong_strength,
|
||||
cellular_distance_function,
|
||||
cellular_return_type,
|
||||
cellular_jitter,
|
||||
} = *settings;
|
||||
|
||||
if noise_type == NoiseType::WhiteNoise {
|
||||
return visitor.visit(&WhiteNoise { corner, texel, seed: seed as u32 });
|
||||
}
|
||||
|
||||
let domain_warp_type = match domain_warp_type {
|
||||
DomainWarpType::None => None,
|
||||
DomainWarpType::OpenSimplex2 => Some(0),
|
||||
DomainWarpType::OpenSimplex2Reduced => Some(1),
|
||||
DomainWarpType::BasicGrid => Some(2),
|
||||
};
|
||||
let noise = NoiseState {
|
||||
seed: seed as i32,
|
||||
frequency: 1. / (scale as f32).max(f32::EPSILON),
|
||||
noise_type: match noise_type {
|
||||
NoiseType::OpenSimplex2 | NoiseType::WhiteNoise => 0,
|
||||
NoiseType::OpenSimplex2S => 1,
|
||||
NoiseType::Cellular => 2,
|
||||
NoiseType::Perlin => 3,
|
||||
NoiseType::ValueCubic => 4,
|
||||
NoiseType::Value => 5,
|
||||
},
|
||||
rotation_type_3d: 0,
|
||||
fractal_type: match fractal_type {
|
||||
FractalType::None => 0,
|
||||
FractalType::FBm => 1,
|
||||
FractalType::Ridged => 2,
|
||||
FractalType::PingPong => 3,
|
||||
FractalType::DomainWarpProgressive => 4,
|
||||
FractalType::DomainWarpIndependent => 5,
|
||||
},
|
||||
octaves: fractal_octaves as i32,
|
||||
lacunarity: fractal_lacunarity as f32,
|
||||
gain: fractal_gain as f32,
|
||||
weighted_strength: fractal_weighted_strength as f32,
|
||||
ping_pong_strength: fractal_ping_pong_strength as f32,
|
||||
cellular_distance_func: match cellular_distance_function {
|
||||
CellularDistanceFunction::Euclidean => 0,
|
||||
CellularDistanceFunction::EuclideanSq => 1,
|
||||
CellularDistanceFunction::Manhattan => 2,
|
||||
CellularDistanceFunction::Hybrid => 3,
|
||||
},
|
||||
cellular_return_type: match cellular_return_type {
|
||||
CellularReturnType::CellValue => 0,
|
||||
CellularReturnType::Nearest => 1,
|
||||
CellularReturnType::NextNearest => 2,
|
||||
CellularReturnType::Average => 3,
|
||||
CellularReturnType::Difference => 4,
|
||||
CellularReturnType::Product => 5,
|
||||
CellularReturnType::Division => 6,
|
||||
},
|
||||
cellular_jitter_mod: cellular_jitter as f32,
|
||||
domain_warp_type: domain_warp_type.unwrap_or(0),
|
||||
domain_warp_amp: domain_warp_amplitude as f32,
|
||||
};
|
||||
|
||||
visitor.visit(&NoisePattern {
|
||||
corner,
|
||||
texel,
|
||||
domain_warp: domain_warp_type.is_some() && domain_warp_amplitude > 0.,
|
||||
noise,
|
||||
})
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
struct NoiseState {
|
||||
seed: i32,
|
||||
frequency: f32,
|
||||
noise_type: i32,
|
||||
rotation_type_3d: i32,
|
||||
fractal_type: i32,
|
||||
octaves: i32,
|
||||
lacunarity: f32,
|
||||
gain: f32,
|
||||
weighted_strength: f32,
|
||||
ping_pong_strength: f32,
|
||||
cellular_distance_func: i32,
|
||||
cellular_return_type: i32,
|
||||
cellular_jitter_mod: f32,
|
||||
domain_warp_type: i32,
|
||||
domain_warp_amp: f32,
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
struct NoisePattern {
|
||||
corner: [f32; 2],
|
||||
texel: [f32; 2],
|
||||
domain_warp: bool,
|
||||
noise: NoiseState,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for NoisePattern {
|
||||
const INPUTS: usize = 0;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(concat!(include_str!("wgsl/fast_noise_lite.wgsl"), "\n", include_str!("wgsl/noise_pattern.wgsl")))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
struct WhiteNoise {
|
||||
corner: [f32; 2],
|
||||
texel: [f32; 2],
|
||||
seed: u32,
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for WhiteNoise {
|
||||
const INPUTS: usize = 0;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::function(include_str!("wgsl/white_noise.wgsl"))
|
||||
}
|
||||
}
|
||||
|
||||
gpu_params! {
|
||||
#[derive(Clone)]
|
||||
struct Mandelbrot {
|
||||
corner: [f32; 2],
|
||||
texel: [f32; 2],
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterKernel for Mandelbrot {
|
||||
const INPUTS: usize = 0;
|
||||
fn wgsl() -> Wgsl {
|
||||
Wgsl::body(
|
||||
r#"
|
||||
let c = vec2<f32>(coord) * vec2<f32>(texel[0], texel[1]) + vec2<f32>(corner[0], corner[1]);
|
||||
var z = vec2<f32>(0.);
|
||||
for (var iteration = 0u; iteration < 1024u; iteration++) {
|
||||
z = vec2<f32>(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c;
|
||||
let magnitude_squared = dot(z, z);
|
||||
if magnitude_squared > 65536. {
|
||||
let smooth_iteration = f32(iteration) + 1. - log2(0.5 * log2(magnitude_squared));
|
||||
return vec4<f32>(vec3<f32>(clamp(smooth_iteration / 255., 0., 1.)), 1.);
|
||||
}
|
||||
}
|
||||
return vec4<f32>(1.);
|
||||
"#,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
use core_types::color::Color;
|
||||
|
||||
/// The WGSL of a [`MapColor`] or [`RasterKernel`], which sees the shared prelude and the `Params` struct with its `params()` accessor.
|
||||
pub enum Wgsl {
|
||||
/// The body of the kernel's function, with every parameter bound as a local.
|
||||
Body(String),
|
||||
/// A source defining the kernel's function and any helpers it calls.
|
||||
Function(String),
|
||||
}
|
||||
|
||||
impl Wgsl {
|
||||
pub fn body(body: impl Into<String>) -> Self {
|
||||
Self::Body(body.into())
|
||||
}
|
||||
|
||||
pub fn function(source: impl Into<String>) -> Self {
|
||||
Self::Function(source.into())
|
||||
}
|
||||
}
|
||||
|
||||
/// A parameter struct passed to a [`MapColor`] or [`RasterKernel`] shader, declared with [`gpu_params!`].
|
||||
pub trait GpuParams {
|
||||
fn write(&self, slots: &mut Vec<u32>);
|
||||
/// The WGSL declarations of the struct and its nested structs, aliased as `Params`, and the `params()` accessor, or nothing for a struct without fields.
|
||||
fn wgsl() -> String;
|
||||
/// The WGSL statements binding every field of `params()` as a local.
|
||||
fn wgsl_locals() -> String;
|
||||
/// The WGSL declaring the texture and accessors of each lookup field, bound in order from `binding`.
|
||||
fn wgsl_lookups(_binding: usize) -> String {
|
||||
String::new()
|
||||
}
|
||||
/// The tables of the lookup fields, in order.
|
||||
fn lookups(&self) -> Vec<RasterKernelLookup<'_>> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// A field type of a [`gpu_params!`] struct, occupying `SLOTS` 32-bit uniform slots.
|
||||
pub trait GpuParamField {
|
||||
const SLOTS: usize;
|
||||
/// Whether the type is a lookup table, bound as its own texture rather than packed into slots, which only a top-level field may be.
|
||||
const LOOKUP: bool = false;
|
||||
fn wgsl_type() -> String;
|
||||
fn write(&self, slots: &mut Vec<u32>);
|
||||
fn wgsl_read(slot: usize) -> String;
|
||||
/// Appends the WGSL struct declarations this type needs, each only once.
|
||||
fn wgsl_declarations(_declarations: &mut Vec<String>) {}
|
||||
/// The WGSL declaring a lookup table's texture at `binding` and its accessors named after `field`.
|
||||
fn wgsl_lookup(_field: &str, _binding: usize) -> String {
|
||||
String::new()
|
||||
}
|
||||
fn lookup<'a>(&'a self, _lookups: &mut Vec<RasterKernelLookup<'a>>) {}
|
||||
}
|
||||
|
||||
fn wgsl_slot(slot: usize) -> String {
|
||||
format!("uniform_params[{}][{}]", slot / 4, slot % 4)
|
||||
}
|
||||
|
||||
impl GpuParamField for f32 {
|
||||
const SLOTS: usize = 1;
|
||||
fn wgsl_type() -> String {
|
||||
"f32".into()
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
slots.push(self.to_bits());
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
format!("bitcast<f32>({})", wgsl_slot(slot))
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuParamField for u32 {
|
||||
const SLOTS: usize = 1;
|
||||
fn wgsl_type() -> String {
|
||||
"u32".into()
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
slots.push(*self);
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
wgsl_slot(slot)
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuParamField for i32 {
|
||||
const SLOTS: usize = 1;
|
||||
fn wgsl_type() -> String {
|
||||
"i32".into()
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
slots.push(*self as u32);
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
format!("bitcast<i32>({})", wgsl_slot(slot))
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuParamField for bool {
|
||||
const SLOTS: usize = 1;
|
||||
fn wgsl_type() -> String {
|
||||
"bool".into()
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
slots.push(*self as u32);
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
format!("{} != 0u", wgsl_slot(slot))
|
||||
}
|
||||
}
|
||||
|
||||
impl GpuParamField for Color {
|
||||
const SLOTS: usize = 4;
|
||||
fn wgsl_type() -> String {
|
||||
"vec4<f32>".into()
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
slots.extend(self.to_vec4().to_array().map(f32::to_bits));
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
let channels = (slot..slot + 4).map(<f32 as GpuParamField>::wgsl_read).collect::<Vec<_>>();
|
||||
format!("vec4<f32>({})", channels.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: GpuParamField, const N: usize> GpuParamField for [T; N] {
|
||||
const SLOTS: usize = N * T::SLOTS;
|
||||
fn wgsl_type() -> String {
|
||||
format!("array<{}, {N}>", T::wgsl_type())
|
||||
}
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
self.iter().for_each(|element| element.write(slots));
|
||||
}
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
let elements = (0..N).map(|index| T::wgsl_read(slot + index * T::SLOTS)).collect::<Vec<_>>();
|
||||
format!("{}({})", Self::wgsl_type(), elements.join(", "))
|
||||
}
|
||||
fn wgsl_declarations(declarations: &mut Vec<String>) {
|
||||
T::wgsl_declarations(declarations);
|
||||
}
|
||||
}
|
||||
|
||||
/// A lookup field of entries spread evenly across 0 to 1, read in WGSL by `fn <field>(t: f32) -> vec4<f32>`, which clamps `t` and interpolates linearly between the nearest two entries.
|
||||
///
|
||||
/// Holds 1 to 4096 entries, the texture width every device supports.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Lut1d(pub Vec<Color>);
|
||||
|
||||
impl GpuParamField for Lut1d {
|
||||
const SLOTS: usize = 0;
|
||||
const LOOKUP: bool = true;
|
||||
fn wgsl_type() -> String {
|
||||
String::new()
|
||||
}
|
||||
fn write(&self, _: &mut Vec<u32>) {}
|
||||
fn wgsl_read(_: usize) -> String {
|
||||
String::new()
|
||||
}
|
||||
fn wgsl_lookup(field: &str, binding: usize) -> String {
|
||||
include_str!("wgsl/lut_1d.wgsl").replace("LUT", field).replace("BINDING", &binding.to_string())
|
||||
}
|
||||
fn lookup<'a>(&'a self, lookups: &mut Vec<RasterKernelLookup<'a>>) {
|
||||
assert!((1..=4096).contains(&self.0.len()), "A 1D lookup table holds 1 to 4096 entries");
|
||||
lookups.push(RasterKernelLookup::Lut1d(&self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// A lookup field of a `size` cubed grid of entries, red fastest, then green, then blue, read in WGSL by `fn <field>_load(index: vec3<i32>) -> vec4<f32>`,
|
||||
/// which clamps the index to the grid, and `fn <field>_size() -> i32`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Lut3d {
|
||||
pub size: u32,
|
||||
pub data: Vec<Color>,
|
||||
}
|
||||
|
||||
impl GpuParamField for Lut3d {
|
||||
const SLOTS: usize = 0;
|
||||
const LOOKUP: bool = true;
|
||||
fn wgsl_type() -> String {
|
||||
String::new()
|
||||
}
|
||||
fn write(&self, _: &mut Vec<u32>) {}
|
||||
fn wgsl_read(_: usize) -> String {
|
||||
String::new()
|
||||
}
|
||||
fn wgsl_lookup(field: &str, binding: usize) -> String {
|
||||
include_str!("wgsl/lut_3d.wgsl").replace("LUT", field).replace("BINDING", &binding.to_string())
|
||||
}
|
||||
fn lookup<'a>(&'a self, lookups: &mut Vec<RasterKernelLookup<'a>>) {
|
||||
assert_eq!(self.data.len(), self.size.pow(3) as usize, "A 3D lookup table holds `size` cubed entries");
|
||||
lookups.push(RasterKernelLookup::Lut3d { size: self.size, data: &self.data });
|
||||
}
|
||||
}
|
||||
|
||||
/// Declares a struct usable as [`GpuParams`] and as a nested [`GpuParamField`], generating its packing and WGSL unpacking.
|
||||
///
|
||||
/// The WGSL struct takes the Rust struct's name, so it must not collide with other WGSL names in the kernel.
|
||||
/// Lookup fields such as [`Lut1d`] and [`Lut3d`] stay out of the WGSL struct, read instead through accessors named after the field.
|
||||
#[macro_export]
|
||||
macro_rules! gpu_params {
|
||||
($(#[$attribute:meta])* $vis:vis struct $name:ident { $($(#[$field_attribute:meta])* $field_vis:vis $field:ident: $ty:ty),* $(,)? }) => {
|
||||
$(#[$attribute])*
|
||||
$vis struct $name {
|
||||
$($(#[$field_attribute])* $field_vis $field: $ty),*
|
||||
}
|
||||
|
||||
impl $crate::GpuParamField for $name {
|
||||
const SLOTS: usize = 0 $(+ <$ty as $crate::GpuParamField>::SLOTS)*;
|
||||
fn wgsl_type() -> String {
|
||||
stringify!($name).into()
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
$(<$ty as $crate::GpuParamField>::write(&self.$field, slots);)*
|
||||
}
|
||||
|
||||
#[allow(unused_mut, unused_variables, unused_assignments)]
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
let mut slot = slot;
|
||||
let reads: Vec<(bool, String)> = vec![$({
|
||||
let read = <$ty as $crate::GpuParamField>::wgsl_read(slot);
|
||||
slot += <$ty as $crate::GpuParamField>::SLOTS;
|
||||
(<$ty as $crate::GpuParamField>::LOOKUP, read)
|
||||
}),*];
|
||||
let reads: Vec<String> = reads.into_iter().filter(|(lookup, _)| !lookup).map(|(_, read)| read).collect();
|
||||
format!("{}({})", stringify!($name), reads.join(", "))
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
fn wgsl_declarations(declarations: &mut Vec<String>) {
|
||||
$(<$ty as $crate::GpuParamField>::wgsl_declarations(declarations);)*
|
||||
let fields: Vec<(bool, String)> = vec![$((
|
||||
<$ty as $crate::GpuParamField>::LOOKUP,
|
||||
format!("{}: {}", stringify!($field), <$ty as $crate::GpuParamField>::wgsl_type())
|
||||
)),*];
|
||||
let fields: Vec<String> = fields.into_iter().filter(|(lookup, _)| !lookup).map(|(_, field)| field).collect();
|
||||
if fields.is_empty() {
|
||||
return;
|
||||
}
|
||||
let declaration = format!("struct {} {{\n\t{},\n}}\n", stringify!($name), fields.join(",\n\t"));
|
||||
if !declarations.contains(&declaration) {
|
||||
declarations.push(declaration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl $crate::GpuParams for $name {
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
<Self as $crate::GpuParamField>::write(self, slots);
|
||||
}
|
||||
|
||||
fn wgsl() -> String {
|
||||
let mut declarations = Vec::new();
|
||||
<Self as $crate::GpuParamField>::wgsl_declarations(&mut declarations);
|
||||
if declarations.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
format!(
|
||||
"{}\nalias Params = {};\n\nfn params() -> Params {{\n\treturn {};\n}}\n",
|
||||
declarations.join("\n"),
|
||||
stringify!($name),
|
||||
<Self as $crate::GpuParamField>::wgsl_read(0)
|
||||
)
|
||||
}
|
||||
|
||||
fn wgsl_locals() -> String {
|
||||
let fields: &[(bool, &str)] = &[$((<$ty as $crate::GpuParamField>::LOOKUP, stringify!($field))),*];
|
||||
let fields: Vec<&str> = fields.iter().filter(|(lookup, _)| !lookup).map(|(_, field)| *field).collect();
|
||||
if fields.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let locals = fields.iter().map(|field| format!("\tlet {field} = parameters.{field};\n")).collect::<String>();
|
||||
format!("\tlet parameters = params();\n{locals}")
|
||||
}
|
||||
|
||||
#[allow(unused_mut, unused_variables, unused_assignments)]
|
||||
fn wgsl_lookups(binding: usize) -> String {
|
||||
let mut binding = binding;
|
||||
let mut source = String::new();
|
||||
$(if <$ty as $crate::GpuParamField>::LOOKUP {
|
||||
source += &<$ty as $crate::GpuParamField>::wgsl_lookup(stringify!($field), binding);
|
||||
binding += 1;
|
||||
})*
|
||||
source
|
||||
}
|
||||
|
||||
#[allow(unused_mut)]
|
||||
fn lookups(&self) -> Vec<$crate::RasterKernelLookup<'_>> {
|
||||
let mut lookups = Vec::new();
|
||||
$(<$ty as $crate::GpuParamField>::lookup(&self.$field, &mut lookups);)*
|
||||
lookups
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Implements [`GpuParamField`] for enums converting into the `u32` or `i32` primitive `$repr`, such as through `IntoPrimitive`.
|
||||
#[macro_export]
|
||||
macro_rules! gpu_param_enum {
|
||||
($repr:ident: $($ty:ty),* $(,)?) => {
|
||||
$(
|
||||
impl $crate::GpuParamField for $ty {
|
||||
const SLOTS: usize = 1;
|
||||
fn wgsl_type() -> String {
|
||||
<$repr as $crate::GpuParamField>::wgsl_type()
|
||||
}
|
||||
|
||||
fn write(&self, slots: &mut Vec<u32>) {
|
||||
<$repr as $crate::GpuParamField>::write(&$repr::from(*self), slots);
|
||||
}
|
||||
|
||||
fn wgsl_read(slot: usize) -> String {
|
||||
<$repr as $crate::GpuParamField>::wgsl_read(slot)
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
/// The [`GpuParams`] a kernel passes to its shader, which is the kernel itself unless it implements this to flatten richer data.
|
||||
pub trait ToGpuParams {
|
||||
type Params: GpuParams;
|
||||
fn to_params(&self) -> Self::Params;
|
||||
}
|
||||
|
||||
impl<T: GpuParams + Clone> ToGpuParams for T {
|
||||
type Params = T;
|
||||
fn to_params(&self) -> T {
|
||||
self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// A per-pixel color mapping, run by `map_cpu` on the CPU and by its WGSL on the GPU, which must agree.
|
||||
///
|
||||
/// Its WGSL function is `fn map_color(color: vec4<f32>) -> vec4<f32>`.
|
||||
pub trait MapColor: ToGpuParams + 'static {
|
||||
fn map_cpu(&self, color: Color) -> Color;
|
||||
fn wgsl() -> Wgsl;
|
||||
}
|
||||
|
||||
/// A GPU-only kernel computing each output pixel from `INPUTS` input rasters, which a type implements instead of [`MapColor`], not alongside it.
|
||||
///
|
||||
/// Its WGSL function is `fn kernel(coord: vec2<i32>) -> vec4<f32>`, which may call `output_size()` and, for each input `i`,
|
||||
/// `input_i_size()`, `input_i_load(coord)` reading the input's own texel clamped to its edge,
|
||||
/// and `input_i_at(coord)` sampling the input bilinearly where the output pixel's center lies, transparent beyond the input.
|
||||
pub trait RasterKernel: ToGpuParams + 'static {
|
||||
const INPUTS: usize;
|
||||
/// Whether the inputs are bound filterable, adding `input_i_sample(texel)` sampling the input bilinearly at texel coordinates, whose texel centers lie at +0.5, clamped to its edge.
|
||||
/// Every input must then be in a filterable format such as `Rgba16Float`, which the executor's raster format isn't.
|
||||
const FILTERED: bool = false;
|
||||
fn wgsl() -> Wgsl;
|
||||
}
|
||||
|
||||
fn shader_module<Params: GpuParams>(signature: &str, wgsl: Wgsl, inputs: usize) -> String {
|
||||
let function = match wgsl {
|
||||
Wgsl::Body(body) => format!("{signature} {{\n{}{body}\n}}", Params::wgsl_locals()),
|
||||
Wgsl::Function(source) => source,
|
||||
};
|
||||
format!("{}\n{}\n{}\n{function}", include_str!("wgsl/prelude.wgsl"), Params::wgsl(), Params::wgsl_lookups(2 + inputs))
|
||||
}
|
||||
|
||||
/// The WGSL module running a [`MapColor`] on each texel of its one input.
|
||||
pub fn map_color_module<K: MapColor>() -> String {
|
||||
let module = shader_module::<K::Params>("fn map_color(color: vec4<f32>) -> vec4<f32>", K::wgsl(), 1);
|
||||
format!("{module}\nfn kernel(coord: vec2<i32>) -> vec4<f32> {{\n\treturn map_color(input_0_load(coord));\n}}\n")
|
||||
}
|
||||
|
||||
/// The WGSL module of a [`RasterKernel`].
|
||||
pub fn raster_kernel_module<K: RasterKernel>() -> String {
|
||||
shader_module::<K::Params>("fn kernel(coord: vec2<i32>) -> vec4<f32>", K::wgsl(), K::INPUTS)
|
||||
}
|
||||
|
||||
/// A lookup table of a kernel, bound as an `Rgba32Float` texture after its inputs.
|
||||
pub enum RasterKernelLookup<'a> {
|
||||
/// A `width x 1` 2D texture of at most 4096 entries.
|
||||
Lut1d(&'a [Color]),
|
||||
/// A `size x size x size` 3D texture, its entries ordered with x fastest, then y, then z.
|
||||
Lut3d { size: u32, data: &'a [Color] },
|
||||
}
|
||||
|
||||
/// Receives a [`RasterKernel`] whose type depends on what it was picked for, such as the pattern a generator renders.
|
||||
pub trait RasterKernelVisitor {
|
||||
type Output;
|
||||
fn visit<K: RasterKernel>(self, kernel: &K) -> Self::Output;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//! The kernels raster operations are carried out with: each a plain-data struct with the WGSL the GPU runs it by, and for those mapping each color alone, the CPU mapping that colors and gradients are adjusted by.
|
||||
//! Running them on rasters is the job of `wgpu-executor`.
|
||||
|
||||
pub mod adjustments;
|
||||
pub mod blending;
|
||||
pub mod blur;
|
||||
pub mod color_lookup_table;
|
||||
pub mod effects;
|
||||
pub mod generators;
|
||||
mod kernel;
|
||||
|
||||
pub use kernel::*;
|
||||
File renamed without changes.
-42
@@ -261,48 +261,6 @@ fn blend_luminosity(color: vec4<f32>, c_s: vec4<f32>) -> vec4<f32> {
|
||||
return from_gamma_srgb_channels(vec4<f32>(blended, c_s.a));
|
||||
}
|
||||
|
||||
fn alpha_blend(color: vec4<f32>, other: vec4<f32>) -> vec4<f32> {
|
||||
let under_weight = color.a * (1. - other.a);
|
||||
let alpha = other.a + under_weight;
|
||||
if alpha == 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
return vec4<f32>((other.rgb * other.a + color.rgb * under_weight) / alpha, alpha);
|
||||
}
|
||||
|
||||
fn alpha_add(color: vec4<f32>, other: vec4<f32>) -> vec4<f32> {
|
||||
return vec4<f32>(color.rgb, clamp(color.a + other.a, 0., 1.));
|
||||
}
|
||||
|
||||
fn alpha_subtract(color: vec4<f32>, other: vec4<f32>) -> vec4<f32> {
|
||||
return vec4<f32>(color.rgb, clamp(color.a - other.a, 0., 1.));
|
||||
}
|
||||
|
||||
fn alpha_multiply(color: vec4<f32>, other: vec4<f32>) -> vec4<f32> {
|
||||
return vec4<f32>(color.rgb, clamp(color.a * other.a, 0., 1.));
|
||||
}
|
||||
|
||||
fn blend_colors(foreground: vec4<f32>, background: vec4<f32>, blend_mode: i32, opacity: f32) -> vec4<f32> {
|
||||
var applied = vec4<f32>(0.);
|
||||
switch blend_mode {
|
||||
case BLEND_MODE_ERASE: {
|
||||
applied = alpha_subtract(background, foreground);
|
||||
}
|
||||
case BLEND_MODE_RESTORE: {
|
||||
applied = alpha_add(background, foreground);
|
||||
}
|
||||
case BLEND_MODE_MULTIPLY_ALPHA: {
|
||||
applied = alpha_multiply(background, foreground);
|
||||
}
|
||||
default: {
|
||||
let target_color = apply_blend_mode(foreground, background, blend_mode);
|
||||
return alpha_blend(background, vec4<f32>(target_color.rgb, target_color.a * opacity));
|
||||
}
|
||||
}
|
||||
|
||||
return vec4<f32>(background.rgb, background.a + (applied.a - background.a) * opacity);
|
||||
}
|
||||
|
||||
fn apply_blend_mode(foreground: vec4<f32>, background: vec4<f32>, blend_mode: i32) -> vec4<f32> {
|
||||
switch blend_mode {
|
||||
case BLEND_MODE_DARKER_COLOR: {
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,6 @@
|
||||
// Stacks a tinted silhouette (input 1's coverage) over the shadows and glows beneath the content (input 0)
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let beneath = input_0_load(coord);
|
||||
let tinted = params().color * input_1_load(coord).a;
|
||||
return tinted + beneath * (1. - tinted.a);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// A bevel's height from 0 to 1, shaped by the style over a slope `size` texels wide, from the nearest texels inside (input 0) and outside (input 1)
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let parameters = params();
|
||||
let to_inside = input_0_load(coord);
|
||||
let to_outside = input_1_load(coord);
|
||||
let size = parameters.size;
|
||||
|
||||
// Texels inside the silhouette are those at no distance from it, and the edge lies about half a texel short of the nearest texel across it
|
||||
let far = 4. * size + 4.;
|
||||
var signed_distance: f32;
|
||||
if to_inside.z > 0.5 && dot(to_inside.xy, to_inside.xy) == 0. {
|
||||
signed_distance = select(far, length(to_outside.xy) - 0.5, to_outside.z > 0.5);
|
||||
} else {
|
||||
signed_distance = select(-far, 0.5 - length(to_inside.xy), to_inside.z > 0.5);
|
||||
}
|
||||
|
||||
var progress: f32;
|
||||
switch parameters.style {
|
||||
case 0u: {
|
||||
progress = signed_distance / size;
|
||||
}
|
||||
case 1u: {
|
||||
progress = (signed_distance + size) / size;
|
||||
}
|
||||
case 2u: {
|
||||
progress = (signed_distance + size / 2.) / size;
|
||||
}
|
||||
default: {
|
||||
progress = abs(signed_distance) / (size / 2.);
|
||||
}
|
||||
}
|
||||
let height = clamp(progress, 0., 1.);
|
||||
return vec4<f32>(height * height * (3. - 2. * height));
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// How far the light brightens the bevel's surface past a flat surface's brightness, or if `shadow`, how far it falls short.
|
||||
// `slope` scales the height's gradient into the surface's steepness, and is negative for a bevel pressed into the surface.
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let parameters = params();
|
||||
let gradient = vec2<f32>(
|
||||
input_0_load(coord + vec2<i32>(1, 0)).a - input_0_load(coord - vec2<i32>(1, 0)).a,
|
||||
input_0_load(coord + vec2<i32>(0, 1)).a - input_0_load(coord - vec2<i32>(0, 1)).a,
|
||||
) / 2.;
|
||||
let light = vec3<f32>(parameters.light_x, parameters.light_y, parameters.light_z);
|
||||
let shade = dot(normalize(vec3<f32>(-parameters.slope * gradient, 1.)), light);
|
||||
|
||||
if parameters.shadow {
|
||||
return vec4<f32>(clamp((light.z - shade) / max(light.z, 1e-4), 0., 1.));
|
||||
}
|
||||
return vec4<f32>(clamp((shade - light.z) / max(1. - light.z, 1e-4), 0., 1.));
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
// The coverage of the content's silhouette, or of the area outside it if `inverse`, where the input's placement casts it
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let coverage = input_0_at(coord).a;
|
||||
return vec4<f32>(select(coverage, 1. - coverage, params().inverse));
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// Places the shadows and glows (input 1) beneath the image (input 0), knocked out by the content at full strength (input 2) so a faded fill doesn't reveal them
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let image = input_0_load(coord);
|
||||
let beneath = input_1_load(coord);
|
||||
let full_content = input_2_load(coord);
|
||||
return image + beneath * (1. - full_content.a);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// Places a tinted silhouette (input 1's coverage) over the image (input 0), within the content at full strength (input 2) so it stays visible over a faded fill
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let image = input_0_load(coord);
|
||||
let tinted = params().color * input_1_load(coord).a;
|
||||
let full_content = input_2_load(coord);
|
||||
return tinted * full_content.a + image * (1. - tinted.a);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// Premultiplied gamma-encoded channels back into a straight-alpha linear-light color
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
let color = input_0_load(coord);
|
||||
if color.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
return vec4<f32>(srgb_to_linear(max(color.rgb / color.a, vec3<f32>(0.))), color.a);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Grows the shapes by one step along an axis, from the coverage placed at the pixel and one step to either side, so steps that double each time grow them by any distance in a few passes
|
||||
fn kernel(coord: vec2<i32>) -> vec4<f32> {
|
||||
return vec4<f32>(max(input_0_at(coord).a, max(input_1_at(coord).a, input_2_at(coord).a)));
|
||||
}
|
||||
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user