mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e23496e978 | ||
|
|
3704a954ca | ||
|
|
9ecbbb408b | ||
|
|
d743b22f1b | ||
|
|
b6459371a9 | ||
|
|
814c988592 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/9d0fa5caefd7d28f51b55220b405b7d76d05a991.tar.gz
|
||||
a146abe79fa20b6d96f8009279a5a3342dd01596e5eb6a43e4c1f5e1199f1d9f
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/38176c494d7cf0bde3bdf45e6a318ae6a9d89229.tar.gz
|
||||
2ae24506ff786b2b684f5d23bd326a69f5f4551855f19e4ef2b0324f9ec14e5d
|
||||
@@ -29,8 +29,6 @@ const DAILY_LIMIT_PER_CONTRIBUTOR = 40;
|
||||
const MAX_RUN_PAGES = 10;
|
||||
// The workflow step that fails only when a run reached a verdict against its title, by the end of its name
|
||||
const VERDICT_STEP_NAME = "Fail for the title's verdict";
|
||||
// The workflow step that passes a run whose title changed while it ran, without a verdict, by the end of its name
|
||||
const SUPERSEDED_STEP_NAME = "Pass for a newer run's review";
|
||||
const MAX_VERDICT_LOOKUPS = 5;
|
||||
|
||||
// How much of the PR's changes accompany the title, which keeps the message under about 20,000 tokens
|
||||
@@ -177,15 +175,14 @@ async function listBranchRuns(workflowId: number, before?: number): Promise<Work
|
||||
return newestFirst(runs);
|
||||
}
|
||||
|
||||
// The newest finished run that reached a verdict on its title, skipping those that didn't (as when a service was unreachable or the title changed mid-run)
|
||||
// The newest of the finished runs that reached a verdict on its title, skipping failures that didn't (such as when GitHub or the review service couldn't be reached)
|
||||
async function latestVerdictRun(finishedRunsNewestFirst: WorkflowRun[]): Promise<WorkflowRun | undefined> {
|
||||
for (let i = 0; i < Math.min(finishedRunsNewestFirst.length, MAX_VERDICT_LOOKUPS); i++) {
|
||||
const run = finishedRunsNewestFirst[i];
|
||||
if (run.conclusion === "success") return run;
|
||||
|
||||
const { jobs } = await github<{ jobs: { steps?: { name: string; conclusion: string | null }[] }[] }>("GET", `/repos/${repository}/actions/runs/${run.id}/jobs`);
|
||||
const steps = jobs.flatMap((job) => job.steps || []);
|
||||
if (steps.some((step) => step.name.endsWith(SUPERSEDED_STEP_NAME) && step.conclusion === "success")) continue;
|
||||
if (run.conclusion === "success") return run;
|
||||
if (steps.some((step) => step.name.endsWith(VERDICT_STEP_NAME) && step.conclusion === "failure")) return run;
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ const pullRequestNumber = readEvent().pull_request.number;
|
||||
const decision = readDecision();
|
||||
const retried = RETRIED_OUTCOMES.includes(decision.outcome);
|
||||
const passed = PASSING_OUTCOMES.includes(decision.outcome);
|
||||
const superseded = decision.outcome === "superseded";
|
||||
|
||||
// New feedback replaces earlier comments so the latest is at the bottom of the conversation, while carried-over and retried outcomes leave them be
|
||||
if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" && !retried) {
|
||||
@@ -48,10 +47,10 @@ if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" &&
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`::${passed || superseded ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
|
||||
console.log(`::${passed ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
|
||||
|
||||
// Later runs tell verdicts, retries, and superseded runs apart by which of the workflow's last steps each one ran
|
||||
const result = passed ? "approved" : superseded ? "superseded" : retried ? "retry" : "verdict";
|
||||
// The workflow fails a different step for a verdict against the title than for an outcome to retry, which later runs read back to tell them apart
|
||||
const result = passed ? "approved" : retried ? "retry" : "verdict";
|
||||
fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`);
|
||||
|
||||
function readDecision(): Decision {
|
||||
|
||||
@@ -150,14 +150,20 @@ jobs:
|
||||
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
|
||||
|
||||
- name: 📤 Publish to Cloudflare Pages
|
||||
if: inputs.merge_queue == false && !github.event.pull_request.head.repo.fork
|
||||
if: inputs.merge_queue == false
|
||||
id: cloudflare
|
||||
continue-on-error: ${{ github.event_name != 'push' }}
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
# Passed through the environment so a branch name can't inject shell syntax
|
||||
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
|
||||
run: |
|
||||
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
|
||||
echo "No Cloudflare API token available (fork PR), skipping deploy."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "${{ github.event_name }}" = "push" ]; then
|
||||
DEPLOY_BRANCH="master"
|
||||
else
|
||||
|
||||
@@ -7,8 +7,6 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
# Runs the checks on a pushed branch that has no PR yet, such as each branch of a stack
|
||||
workflow_dispatch: {}
|
||||
|
||||
# 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:
|
||||
@@ -247,8 +245,7 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
# A manual run has no base commit of its own, so it compares against master
|
||||
BASE_REF: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || 'master' }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
@@ -262,9 +259,7 @@ jobs:
|
||||
rustflags: ""
|
||||
|
||||
- name: 📥 Fetch the base commit
|
||||
run: |
|
||||
git fetch --depth=1 origin "$BASE_REF"
|
||||
echo "BASE_SHA=$(git rev-parse FETCH_HEAD)" >> "$GITHUB_ENV"
|
||||
run: git fetch --depth=1 origin "$BASE_SHA"
|
||||
|
||||
- name: 🔬 Check migrations against the base commit
|
||||
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
|
||||
|
||||
@@ -51,8 +51,6 @@ jobs:
|
||||
with:
|
||||
# Cache on Cargo.lock file
|
||||
cache-on-failure: true
|
||||
# Saved only by master pushes, since a PR's saved cache is readable only by that PR yet counts toward the repo's size limit
|
||||
save-if: ${{ github.event_name == 'push' }}
|
||||
|
||||
- name: Install gungraun-runner and valgrind
|
||||
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
|
||||
|
||||
@@ -64,12 +64,7 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.report.outputs.result == 'verdict' }}
|
||||
run: exit 1
|
||||
|
||||
# A run whose title changed mid-run passes and leaves the check to the newer run, which skips it by this name (see `SUPERSEDED_STEP_NAME` in `gather.ts`)
|
||||
- name: ⏭️ Pass for a newer run's review
|
||||
if: ${{ !cancelled() && steps.report.outputs.result == 'superseded' }}
|
||||
run: echo "A newer run reviews the changed title"
|
||||
|
||||
# Later runs review the title again after this failure, as they do when a step above fails unexpectedly
|
||||
- name: 🔁 Fail without a verdict
|
||||
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' && steps.report.outputs.result != 'superseded' }}
|
||||
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' }}
|
||||
run: exit 1
|
||||
Generated
+148
-16
@@ -590,7 +590,6 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -1239,7 +1238,7 @@ dependencies = [
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"tinyvec",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
@@ -2136,6 +2135,9 @@ name = "float-cmp"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
@@ -2155,6 +2157,15 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.12.7"
|
||||
@@ -2196,7 +2207,7 @@ dependencies = [
|
||||
"linebender_resource_handle",
|
||||
"memmap2",
|
||||
"parlance",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -2433,6 +2444,21 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glifo"
|
||||
version = "0.4.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"foldhash 0.2.0",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"peniko",
|
||||
"skrifa 0.44.0",
|
||||
"smallvec",
|
||||
"vello_common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.4"
|
||||
@@ -3040,7 +3066,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -3428,6 +3454,12 @@ dependencies = [
|
||||
"quick-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "imagesize"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
|
||||
|
||||
[[package]]
|
||||
name = "imagesize"
|
||||
version = "0.15.0"
|
||||
@@ -3800,6 +3832,33 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
"flate2",
|
||||
"float-cmp",
|
||||
"gif",
|
||||
"image-webp",
|
||||
"imagesize 0.14.0",
|
||||
"indexmap",
|
||||
"pdf-writer",
|
||||
"png 0.18.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"siphasher",
|
||||
"skrifa 0.42.1",
|
||||
"smallvec",
|
||||
"subsetter",
|
||||
"tiny-skia-path",
|
||||
"xmp-writer",
|
||||
"yoke",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kurbo"
|
||||
version = "0.13.1"
|
||||
@@ -5033,7 +5092,7 @@ dependencies = [
|
||||
"parlance",
|
||||
"parley_data",
|
||||
"parley_emoji",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5064,6 +5123,18 @@ dependencies = [
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdf-writer"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peer-transport"
|
||||
version = "0.0.0"
|
||||
@@ -5746,7 +5817,6 @@ dependencies = [
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"raster-types",
|
||||
"thiserror 2.0.21",
|
||||
@@ -5867,6 +5937,16 @@ dependencies = [
|
||||
"yasna",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.39.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.41.0"
|
||||
@@ -5874,7 +5954,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types",
|
||||
"font-types 0.12.7",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
@@ -6017,17 +6097,19 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"glifo",
|
||||
"graphene-application-io",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"krilla",
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
@@ -6605,6 +6687,12 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
@@ -6966,6 +7054,16 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.42.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
@@ -6973,7 +7071,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts",
|
||||
"read-fonts 0.41.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7152,6 +7250,18 @@ version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subsetter"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"rustc-hash 2.1.3",
|
||||
"skrifa 0.42.1",
|
||||
"write-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "substring"
|
||||
version = "1.4.5"
|
||||
@@ -7334,7 +7444,7 @@ dependencies = [
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"thiserror 2.0.21",
|
||||
"titlecase",
|
||||
"tsify",
|
||||
@@ -7934,14 +8044,14 @@ dependencies = [
|
||||
"flate2",
|
||||
"fontdb",
|
||||
"harfrust",
|
||||
"imagesize",
|
||||
"imagesize 0.15.0",
|
||||
"kurbo",
|
||||
"log",
|
||||
"pico-args",
|
||||
"roxmltree 0.21.2",
|
||||
"simplecss",
|
||||
"siphasher",
|
||||
"skrifa",
|
||||
"skrifa 0.44.0",
|
||||
"strict-num",
|
||||
"svgtypes",
|
||||
"tiny-skia-path",
|
||||
@@ -8026,6 +8136,7 @@ dependencies = [
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsify",
|
||||
@@ -8084,7 +8195,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -8099,9 +8210,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"glifo",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
@@ -8113,7 +8225,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
@@ -8584,6 +8696,7 @@ dependencies = [
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"vello_gpu",
|
||||
"web-sys",
|
||||
@@ -9284,6 +9397,19 @@ dependencies = [
|
||||
"toml 0.5.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "write-fonts"
|
||||
version = "0.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
|
||||
dependencies = [
|
||||
"font-types 0.11.3",
|
||||
"indexmap",
|
||||
"kurbo",
|
||||
"log",
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
@@ -9424,6 +9550,12 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||
|
||||
[[package]]
|
||||
name = "xmp-writer"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "yansi"
|
||||
version = "1.0.1"
|
||||
|
||||
+7
-4
@@ -215,7 +215,9 @@ url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support", "text"] }
|
||||
glifo = { version = "0.4", default-features = false, features = ["std"] }
|
||||
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
|
||||
usvg = "0.49"
|
||||
simplecss = "0.2"
|
||||
parley = { version = "0.12", default-features = false, features = ["std"] }
|
||||
@@ -315,6 +317,7 @@ debug = true
|
||||
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
|
||||
fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
glifo = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
@@ -52,11 +52,9 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod branch_simulation;
|
||||
mod crdt;
|
||||
mod history_simulation;
|
||||
mod projection;
|
||||
mod round_trip;
|
||||
mod sessions;
|
||||
mod simulation;
|
||||
}
|
||||
@@ -382,8 +382,7 @@ fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, k
|
||||
if !visited.insert(current) {
|
||||
return None;
|
||||
}
|
||||
// A placeholder knows nothing of the node's network or primary input, so what history kept decides instead
|
||||
let (in_network, input) = match registry.removed_nodes.get(¤t).filter(|tombstone| !tombstone.placeholder) {
|
||||
let (in_network, input) = match registry.removed_nodes.get(¤t) {
|
||||
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
|
||||
None => known.primary.get(¤t).cloned()?,
|
||||
};
|
||||
@@ -406,11 +405,9 @@ fn set(registry: &mut Registry, ops: &mut Vec<RegistryDelta>, slot: Slot, input:
|
||||
match slot {
|
||||
Slot::Input(id, index) => {
|
||||
let Some(input) = input else { return };
|
||||
// A chain the line no longer holds the slot for, as shrinking a node's inputs leaves, is not written back
|
||||
let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) else {
|
||||
return;
|
||||
};
|
||||
slot.input = input.clone();
|
||||
if let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) {
|
||||
slot.input = input.clone();
|
||||
}
|
||||
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
|
||||
}
|
||||
Slot::Export(id, index) => {
|
||||
|
||||
@@ -1,259 +0,0 @@
|
||||
//! Deterministic simulation of a document whose chains branch off inputs past the primary one, with every history
|
||||
//! operation mixed in. After every operation nothing may name a node the document no longer has.
|
||||
|
||||
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
||||
use crate::{Implementation, InputSlot, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp};
|
||||
|
||||
/// A slot that can name a node.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
enum Place {
|
||||
Export(u32),
|
||||
Input(NodeId, u32),
|
||||
}
|
||||
|
||||
fn place_value(registry: &Registry, place: Place) -> Option<NodeInput> {
|
||||
match place {
|
||||
Place::Input(id, index) => registry.node_instances.get(&id)?.inputs.get(index as usize).map(|slot| slot.input.clone()),
|
||||
Place::Export(index) => registry.networks.get(&ROOT_NETWORK)?.exports.get(index as usize)?.target.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_place(place: Place, input: NodeInput) -> RegistryDelta {
|
||||
match place {
|
||||
Place::Input(id, index) => RegistryDelta::ChangeNodeInput { id, index, new_input: input },
|
||||
Place::Export(index) => RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index,
|
||||
export: Some(input),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Every slot naming a node, and the node it names, in a fixed order.
|
||||
fn naming_places(registry: &Registry) -> Vec<(Place, NodeId)> {
|
||||
let mut places = Vec::new();
|
||||
for (&id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = slot.input {
|
||||
places.push((Place::Input(id, index as u32), named));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(network) = registry.networks.get(&ROOT_NETWORK) {
|
||||
for (index, slot) in network.exports.iter().enumerate() {
|
||||
if let Some(NodeInput::Node { id: named, .. }) = slot.target {
|
||||
places.push((Place::Export(index as u32), named));
|
||||
}
|
||||
}
|
||||
}
|
||||
places.sort();
|
||||
places
|
||||
}
|
||||
|
||||
/// The slot naming `node`, of which a document built this way has one.
|
||||
fn consumer_place(registry: &Registry, node: NodeId) -> Option<Place> {
|
||||
naming_places(registry).into_iter().find(|(_, named)| *named == node).map(|(place, _)| place)
|
||||
}
|
||||
|
||||
/// Every node under `place`, through any input.
|
||||
fn under(registry: &Registry, place: Place) -> Vec<NodeId> {
|
||||
let mut seen: Vec<NodeId> = Vec::new();
|
||||
let mut queue: Vec<NodeId> = Vec::new();
|
||||
if let Some(NodeInput::Node { id, .. }) = place_value(registry, place) {
|
||||
queue.push(id);
|
||||
}
|
||||
while let Some(id) = queue.pop() {
|
||||
if seen.contains(&id) || !registry.node_instances.contains_key(&id) {
|
||||
continue;
|
||||
}
|
||||
seen.push(id);
|
||||
for slot in ®istry.node_instances[&id].inputs {
|
||||
if let NodeInput::Node { id: next, .. } = slot.input {
|
||||
queue.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// Nodes chained off the export and off inputs past the primary one.
|
||||
struct Branching;
|
||||
|
||||
impl Scenario for Branching {
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
|
||||
let registry = session.registry().clone();
|
||||
let layers = stack(®istry);
|
||||
let nodes = under(®istry, Place::Export(0));
|
||||
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
|
||||
id: LEAF,
|
||||
network: Network::default(),
|
||||
});
|
||||
let make = |first: NodeInput, second: NodeInput| {
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
|
||||
node.inputs[0].input = first;
|
||||
node.inputs[1].input = second;
|
||||
node
|
||||
};
|
||||
// Nodes that still have an input past the primary one, the only ones an edit may write there
|
||||
let wide: Vec<NodeId> = nodes.iter().copied().filter(|id| registry.node_instances[id].inputs.len() > 1).collect();
|
||||
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
|
||||
let plain: Vec<NodeId> = wide
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| !matches!(place_value(®istry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
|
||||
.collect();
|
||||
|
||||
match random.below(14) {
|
||||
// Draw a node on top of the chain off the export
|
||||
0..=2 => {
|
||||
let id = session.next_node_id();
|
||||
let node = make(layers.first().map_or_else(|| value(0), |&top| on(top)), value(random.below(100)));
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(id)),
|
||||
},
|
||||
]);
|
||||
if let Some(&under) = layers.first() {
|
||||
ops.push(super::crdt::change_node_attribute(under, "position", serde_json::json!(random.below(100))));
|
||||
}
|
||||
ops
|
||||
}
|
||||
// Hang a node on an input past the primary one, over whatever is there already
|
||||
3..=5 => {
|
||||
let Some(host) = random.pick(&wide) else { return Vec::new() };
|
||||
let id = session.next_node_id();
|
||||
let first = match place_value(®istry, Place::Input(host, 1)) {
|
||||
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
|
||||
_ => value(0),
|
||||
};
|
||||
let node = make(first, value(random.below(100)));
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: host,
|
||||
index: 1,
|
||||
new_input: on(id),
|
||||
},
|
||||
]);
|
||||
ops
|
||||
}
|
||||
// Delete a node, reconnecting everything that named it to what it rested on
|
||||
6..=7 => {
|
||||
let Some(node) = random.pick(&plain) else { return Vec::new() };
|
||||
let snapshot = registry.node_instances[&node].clone();
|
||||
let mut ops: Vec<RegistryDelta> = naming_places(®istry)
|
||||
.into_iter()
|
||||
.filter(|(_, named)| *named == node)
|
||||
.map(|(place, _)| set_place(place, below(®istry, node)))
|
||||
.collect();
|
||||
ops.push(RegistryDelta::RemoveNode { id: node, snapshot });
|
||||
ops
|
||||
}
|
||||
// Move a node to the top of the chain off the export
|
||||
8 => {
|
||||
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
|
||||
let Some(place) = consumer_place(®istry, layer) else { return Vec::new() };
|
||||
vec![
|
||||
set_place(place, below(®istry, layer)),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 0,
|
||||
new_input: on(layers[0]),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(layer)),
|
||||
},
|
||||
]
|
||||
}
|
||||
// Change a node's value
|
||||
9..=10 => {
|
||||
let Some(node) = random.pick(&plain) else { return Vec::new() };
|
||||
vec![RegistryDelta::ChangeNodeInput {
|
||||
id: node,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
// Rewrite a node's whole input list, which an index-addressed write cannot express
|
||||
11..=12 => {
|
||||
let Some(node) = random.pick(&nodes) else { return Vec::new() };
|
||||
let mut inputs = registry.node_instances[&node].inputs.clone();
|
||||
match random.below(3) {
|
||||
// Swap the first two, so what the node rested on moves past its primary input
|
||||
0 if inputs.len() > 1 => inputs.swap(0, 1),
|
||||
// One input more, holding a value
|
||||
1 if inputs.len() < 4 => inputs.push(InputSlot {
|
||||
input: value(random.below(100)),
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: Default::default(),
|
||||
}),
|
||||
// One input fewer, as removing a subgraph's import slot leaves the nodes wrapping it
|
||||
_ if inputs.len() > 1 => _ = inputs.pop(),
|
||||
_ => return Vec::new(),
|
||||
}
|
||||
vec![RegistryDelta::SetNodeInputs { id: node, inputs }]
|
||||
}
|
||||
// Cut the chain off an input past the primary one, taking its nodes with it
|
||||
_ => {
|
||||
let hosts: Vec<NodeId> = nodes
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| matches!(place_value(®istry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
|
||||
.collect();
|
||||
let Some(host) = random.pick(&hosts) else { return Vec::new() };
|
||||
let mut gone = under(®istry, Place::Input(host, 1));
|
||||
// Nothing outside the cut may name a node inside it, or taking them would leave that naming nothing
|
||||
let held = naming_places(®istry)
|
||||
.into_iter()
|
||||
.any(|(place, named)| gone.contains(&named) && place != Place::Input(host, 1) && !matches!(place, Place::Input(owner, _) if gone.contains(&owner)));
|
||||
if held {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ops = vec![RegistryDelta::ChangeNodeInput {
|
||||
id: host,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}];
|
||||
gone.sort();
|
||||
for id in gone {
|
||||
ops.push(RegistryDelta::RemoveNode {
|
||||
id,
|
||||
snapshot: registry.node_instances[&id].clone(),
|
||||
});
|
||||
}
|
||||
ops
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing names a node the document no longer has, every node is built from a network it still has, and no node
|
||||
/// input holds the empty export's value. A node may feed nothing or more than one input.
|
||||
fn assert_well_formed(context: &str, registry: &Registry) {
|
||||
for (place, named) in naming_places(registry) {
|
||||
assert!(registry.node_instances.contains_key(&named), "{context}: {place:?} names {named:?}, which is gone");
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
if let Implementation::Network(network) = &node.implementation {
|
||||
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
|
||||
}
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
assert_ne!(slot.input, empty_export(), "{context}: input {index} of {id:?} holds the empty export's value");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_operations_keep_a_branching_document_whole() {
|
||||
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
|
||||
for seed in 0..seeds {
|
||||
simulate::<Branching>(seed, steps, &mut Vec::new());
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,64 @@
|
||||
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation mixed in.
|
||||
//! After every operation the document must still be a well-formed stack.
|
||||
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation the History
|
||||
//! panel offers mixed in: undo, redo, going back, removing a step and bringing one back. After every operation the
|
||||
//! document must still be a well-formed stack, the snapshot must be what history folds to, and a peer following the
|
||||
//! head moves must hold the same document.
|
||||
//!
|
||||
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
|
||||
|
||||
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
||||
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
|
||||
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// What every layer's implementation names, so nodes need no proto-node declarations. The first layer drawn brings it,
|
||||
/// as the editor's first layer brings the subgraph every later one is built from.
|
||||
const LEAF: NetworkId = NetworkId(1);
|
||||
|
||||
/// What the export holds while the stack is empty, of another type than what the bottom layer rests on.
|
||||
fn empty_export() -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!("empty")),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A small xorshift generator, so a seed fixes the run.
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn new(seed: u64) -> Self {
|
||||
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
|
||||
}
|
||||
|
||||
fn below(&mut self, bound: usize) -> usize {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 % bound as u64) as usize
|
||||
}
|
||||
|
||||
fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
|
||||
(!options.is_empty()).then(|| options[self.below(options.len())])
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers from the top of the stack down, following each layer's first input.
|
||||
fn stack(registry: &Registry) -> Vec<NodeId> {
|
||||
let mut layers = Vec::new();
|
||||
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
|
||||
while let Some(NodeInput::Node { id, .. }) = below {
|
||||
if layers.contains(&id) || layers.len() > registry.node_instances.len() {
|
||||
break;
|
||||
}
|
||||
layers.push(id);
|
||||
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
|
||||
}
|
||||
layers
|
||||
}
|
||||
|
||||
/// What feeds into `layer` from below.
|
||||
fn below(registry: &Registry, layer: NodeId) -> NodeInput {
|
||||
registry.node_instances[&layer].inputs[0].input.clone()
|
||||
}
|
||||
|
||||
/// Points what sits directly above `layer`, a layer or the export, at `input`.
|
||||
fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> RegistryDelta {
|
||||
let layers = stack(registry);
|
||||
@@ -24,124 +76,365 @@ fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> Registr
|
||||
}
|
||||
}
|
||||
|
||||
/// A single stack of layers off the export.
|
||||
struct Stack;
|
||||
fn on(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
|
||||
impl Scenario for Stack {
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
|
||||
let registry = session.registry().clone();
|
||||
let layers = stack(®istry);
|
||||
match random.below(10) {
|
||||
// Draw a layer on top
|
||||
0..=3 => {
|
||||
let id = session.next_node_id();
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
|
||||
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
|
||||
node.inputs[1].input = value(random.below(100));
|
||||
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
|
||||
id: LEAF,
|
||||
network: Network::default(),
|
||||
});
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(id)),
|
||||
},
|
||||
]);
|
||||
// The layer below moves into the stack under the new one, as the editor records with its position
|
||||
if let Some(&below) = layers.first() {
|
||||
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
|
||||
}
|
||||
ops
|
||||
fn value(number: usize) -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(number)),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One interaction's ops, as the editor would stage them for a random edit of the stack.
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
|
||||
let registry = session.registry().clone();
|
||||
let layers = stack(®istry);
|
||||
match random.below(10) {
|
||||
// Draw a layer on top
|
||||
0..=3 => {
|
||||
let id = session.next_node_id();
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
|
||||
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
|
||||
node.inputs[1].input = value(random.below(100));
|
||||
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
|
||||
id: LEAF,
|
||||
network: Network::default(),
|
||||
});
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(id)),
|
||||
},
|
||||
]);
|
||||
// The layer below moves into the stack under the new one, as the editor records with its position
|
||||
if let Some(&below) = layers.first() {
|
||||
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
|
||||
}
|
||||
// Delete a layer, reconnecting what was above it to what was below
|
||||
4..=5 => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
let snapshot = registry.node_instances[&layer].clone();
|
||||
vec![rewire_above(®istry, layer, below(®istry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
|
||||
}
|
||||
// Move a layer to the top
|
||||
6 => {
|
||||
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
|
||||
vec![
|
||||
rewire_above(®istry, layer, below(®istry, layer)),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 0,
|
||||
new_input: on(layers[0]),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(layer)),
|
||||
},
|
||||
]
|
||||
}
|
||||
// Change a layer's value
|
||||
_ => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
vec![RegistryDelta::ChangeNodeInput {
|
||||
ops
|
||||
}
|
||||
// Delete a layer, reconnecting what was above it to what was below
|
||||
4..=5 => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
let snapshot = registry.node_instances[&layer].clone();
|
||||
vec![rewire_above(®istry, layer, below(®istry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
|
||||
}
|
||||
// Move a layer to the top
|
||||
6 => {
|
||||
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
|
||||
vec![
|
||||
rewire_above(®istry, layer, below(®istry, layer)),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
index: 0,
|
||||
new_input: on(layers[0]),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(layer)),
|
||||
},
|
||||
]
|
||||
}
|
||||
// Change a layer's value
|
||||
_ => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
vec![RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
|
||||
/// left drawn by nothing.
|
||||
fn assert_well_formed(context: &str, registry: &Registry) {
|
||||
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
|
||||
let export = exports.first().and_then(|slot| slot.target.clone());
|
||||
if let Some(NodeInput::Node { id, .. }) = &export {
|
||||
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
|
||||
/// The ops of an edit, short enough to read in a failing run's log.
|
||||
fn summarize(ops: &[RegistryDelta]) -> String {
|
||||
let short = |id: &NodeId| id.0 % 1000;
|
||||
let input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => format!("{}", short(id)),
|
||||
_ => "value".to_string(),
|
||||
};
|
||||
ops.iter()
|
||||
.map(|op| match op {
|
||||
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
|
||||
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
|
||||
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
|
||||
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
|
||||
other => format!("{other:?}"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// The revs closing each interaction on the head's line, newest first.
|
||||
fn line_steps(session: &Session) -> Vec<Rev> {
|
||||
let mut steps = Vec::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
if delta.is_interaction_end() {
|
||||
steps.push(delta.id);
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = &slot.input {
|
||||
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut stacked_on = HashSet::new();
|
||||
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
|
||||
for input in primary_inputs.chain(export.iter()) {
|
||||
if let NodeInput::Node { id, .. } = input {
|
||||
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
|
||||
}
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
if let Implementation::Network(network) = &node.implementation {
|
||||
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
|
||||
}
|
||||
}
|
||||
let layers = stack(registry);
|
||||
if let Some(bottom) = layers.last() {
|
||||
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
|
||||
}
|
||||
let unique: HashSet<NodeId> = layers.iter().copied().collect();
|
||||
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
|
||||
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
|
||||
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
|
||||
current = delta.parent;
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The revs closing interactions left behind on branches.
|
||||
fn branch_steps(session: &Session) -> Vec<Rev> {
|
||||
let line: HashSet<Rev> = {
|
||||
let mut line = HashSet::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
line.insert(delta.id);
|
||||
current = delta.parent;
|
||||
}
|
||||
line
|
||||
};
|
||||
let mut steps: Vec<Rev> = session
|
||||
.history()
|
||||
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
|
||||
.map(|delta| delta.id)
|
||||
.collect();
|
||||
steps.sort();
|
||||
steps
|
||||
}
|
||||
|
||||
/// The layers the interaction ending at `end` added and deleted, by what it did in all.
|
||||
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
|
||||
let (mut added, mut removed) = (Vec::new(), Vec::new());
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddNode { id, .. } => added.push(*id),
|
||||
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
|
||||
_ => {}
|
||||
}
|
||||
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
|
||||
}
|
||||
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
|
||||
(net(&added, &removed), net(&removed, &added))
|
||||
}
|
||||
|
||||
/// The layers the step ending at `end` added that a newer deletion on its own line had taken again.
|
||||
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
|
||||
let mut lost = HashSet::new();
|
||||
let mut added_at = std::collections::HashMap::new();
|
||||
let mut line = Vec::new();
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
line.push(delta);
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
|
||||
added_at.entry(*id).or_insert(delta.timestamp);
|
||||
}
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
|
||||
&& added.contains(id)
|
||||
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
|
||||
{
|
||||
lost.insert(*id);
|
||||
}
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// The layers live on the line just before the interaction ending at `end`.
|
||||
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
let mut line = Vec::new();
|
||||
while let Some(delta) = current {
|
||||
line.push(delta.clone());
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
line.reverse();
|
||||
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
|
||||
replayed.retired_registry().node_instances.keys().copied().collect()
|
||||
}
|
||||
|
||||
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
|
||||
/// left drawn by nothing.
|
||||
fn assert_well_formed(context: &str, registry: &Registry) {
|
||||
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
|
||||
let export = exports.first().and_then(|slot| slot.target.clone());
|
||||
if let Some(NodeInput::Node { id, .. }) = &export {
|
||||
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = &slot.input {
|
||||
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut stacked_on = HashSet::new();
|
||||
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
|
||||
for input in primary_inputs.chain(export.iter()) {
|
||||
if let NodeInput::Node { id, .. } = input {
|
||||
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
|
||||
}
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
if let Implementation::Network(network) = &node.implementation {
|
||||
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
|
||||
}
|
||||
}
|
||||
let layers = stack(registry);
|
||||
if let Some(bottom) = layers.last() {
|
||||
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
|
||||
}
|
||||
let unique: HashSet<NodeId> = layers.iter().copied().collect();
|
||||
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
|
||||
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
|
||||
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
|
||||
}
|
||||
|
||||
fn assert_consistent(context: &str, session: &Session) {
|
||||
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
|
||||
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
|
||||
let folded = session.snapshot_from_history().expect("history folds");
|
||||
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
|
||||
assert_well_formed(context, session.retired_registry());
|
||||
}
|
||||
|
||||
/// Closes the open interaction and retires it as one step.
|
||||
fn retire_step(session: &mut Session) {
|
||||
session.end_interaction().expect("close");
|
||||
for interaction in session.closed_interactions() {
|
||||
session.retire_interaction(&interaction).expect("retire");
|
||||
}
|
||||
}
|
||||
|
||||
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
|
||||
fn catch_up(follower: &mut Session, host: &Session) {
|
||||
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
|
||||
follower.follow(missing, host.head_rev()).expect("follow");
|
||||
}
|
||||
|
||||
/// A peer that joins now and holds what the host holds.
|
||||
fn fresh_follower(host: &Session) -> Session {
|
||||
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
|
||||
}
|
||||
|
||||
fn simulate(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
|
||||
let mut random = Random::new(seed);
|
||||
let mut host = Session::with_identity(PeerId(1), UserId(1));
|
||||
let document = [
|
||||
RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(empty_export()),
|
||||
},
|
||||
];
|
||||
host.stage_ops(document).expect("stage the document");
|
||||
retire_step(&mut host);
|
||||
let mut follower = fresh_follower(&host);
|
||||
|
||||
for step in 0..steps {
|
||||
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
|
||||
match random.below(12) {
|
||||
0..=5 => {
|
||||
let ops = random_edit(&mut random, &mut host);
|
||||
if ops.is_empty() {
|
||||
continue;
|
||||
}
|
||||
log.push(format!("{step}: edit {}", summarize(&ops)));
|
||||
host.stage_ops(ops).expect("stage");
|
||||
retire_step(&mut host);
|
||||
catch_up(&mut follower, &host);
|
||||
}
|
||||
6 if host.can_undo() => {
|
||||
log.push(format!("{step}: undo"));
|
||||
host.undo().expect("undo");
|
||||
follower = fresh_follower(&host);
|
||||
}
|
||||
7 if host.can_redo() => {
|
||||
log.push(format!("{step}: redo"));
|
||||
host.redo().expect("redo");
|
||||
follower = fresh_follower(&host);
|
||||
}
|
||||
8 => {
|
||||
// Not the newest step, which going back to would leave everything as it is
|
||||
let Some(target) = random.pick(&line_steps(&host)[1.min(line_steps(&host).len())..]) else {
|
||||
continue;
|
||||
};
|
||||
log.push(format!("{step}: go back to {target:?}"));
|
||||
let (moved, _) = host.move_head_to(target).expect("go back");
|
||||
follower.apply_head_move(&moved).expect("follow the move");
|
||||
}
|
||||
9 => {
|
||||
let steps = line_steps(&host);
|
||||
// The first step makes the document, which nothing can do without
|
||||
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
|
||||
log.push(format!("{step}: remove {target:?}"));
|
||||
let (mut added, _) = added_and_removed(&host, target);
|
||||
// A layer the line had before the step stays
|
||||
let earlier = live_before(&host, target);
|
||||
added.retain(|id| !earlier.contains(id));
|
||||
let (moved, _) = host.drop_interaction(target).expect("remove the step");
|
||||
follower.apply_head_move(&moved).expect("follow the removal");
|
||||
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the removed step's layers {kept:?} are still there"), log));
|
||||
}
|
||||
10 | 11 => {
|
||||
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
|
||||
log.push(format!("{step}: bring back {target:?}"));
|
||||
let (mut added, removed) = added_and_removed(&host, target);
|
||||
// A layer the line already had from this step and deleted since stays deleted
|
||||
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
|
||||
// As does one a newer deletion took on the step's own line
|
||||
let lost = lost_on_its_line(&host, target, &added);
|
||||
added.retain(|id| !lost.contains(id));
|
||||
host.restore_interaction(target).expect("bring back");
|
||||
catch_up(&mut follower, &host);
|
||||
let registry = host.retired_registry();
|
||||
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
|
||||
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
|
||||
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's layers {missing:?} are missing"), log));
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the layers {kept:?} the brought back step deleted are still there"), log));
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
let what = log.last().cloned().unwrap_or_default();
|
||||
assert_consistent(&context(&what, log), &host);
|
||||
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
|
||||
assert!(
|
||||
follower.retired_registry().value_equal(host.retired_registry()),
|
||||
"{}",
|
||||
context("the follower holds another document", log)
|
||||
);
|
||||
}
|
||||
host
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_operations_keep_the_stack_whole_and_peers_converged() {
|
||||
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
|
||||
let seeds: u64 = std::env::var("SEEDS").ok().and_then(|seeds| seeds.parse().ok()).unwrap_or(200);
|
||||
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
|
||||
for seed in 0..seeds {
|
||||
simulate::<Stack>(seed, steps, &mut Vec::new());
|
||||
simulate(seed, steps, &mut Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// A seed fixes the run, so one that fails can be replayed.
|
||||
#[test]
|
||||
fn a_seed_fixes_the_history_run() {
|
||||
let histories = |seed| simulate::<Stack>(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
|
||||
let histories = |seed| simulate(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
|
||||
for seed in 0..5 {
|
||||
assert_eq!(histories(seed), histories(seed), "seed {seed}");
|
||||
}
|
||||
@@ -150,7 +443,9 @@ fn a_seed_fixes_the_history_run() {
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn inspect_seed() {
|
||||
let seed = std::env::var("SEED").ok().and_then(|seed| seed.parse().ok()).unwrap_or(0);
|
||||
let mut log = Vec::new();
|
||||
let host = simulate::<Stack>(from_env("SEED", 0), from_env("STEPS", 80), &mut log);
|
||||
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
|
||||
let host = simulate(seed, steps, &mut log);
|
||||
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
|
||||
}
|
||||
@@ -1033,33 +1033,6 @@ fn deleting_a_node_without_inputs_gives_the_input_it_fed_its_earlier_value() {
|
||||
assert_eq!(registry.node_instances[&consumer].inputs()[1].input, earlier_value);
|
||||
}
|
||||
|
||||
/// Bringing back a step that writes to a node the line never had reconnects an input naming that node to what history
|
||||
/// holds as its primary input, though the write leaves only a placeholder of it.
|
||||
#[test]
|
||||
fn bringing_back_a_step_reconnects_past_a_node_the_line_never_had() {
|
||||
let (source, consumer) = (NodeId(1), NodeId(2));
|
||||
let source_value = NodeInput::Value {
|
||||
value: Value::from(serde_json::json!("under the source")),
|
||||
exposed: false,
|
||||
};
|
||||
let mut source_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
|
||||
source_node.inputs[0].input = source_value.clone();
|
||||
let mut consumer_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
|
||||
consumer_node.inputs[0].input = NodeInput::Node { id: source, index: 0 };
|
||||
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
let base = step(&mut session, add_network(5));
|
||||
step(&mut session, RegistryDelta::AddNode { id: source, node: source_node });
|
||||
session.commit_op_for_test(RegistryDelta::AddNode { id: consumer, node: consumer_node }).expect("commit");
|
||||
let consumed = step(&mut session, change_node_attribute(source, "position", serde_json::json!(1)));
|
||||
session.move_head_to(base).expect("go back to before the source");
|
||||
|
||||
session.restore_interaction(consumed).expect("bring the consumer back");
|
||||
let registry = session.retired_registry();
|
||||
assert!(registry.removed_nodes.get(&source).is_some_and(|tombstone| tombstone.placeholder));
|
||||
assert_eq!(registry.node_instances[&consumer].inputs()[0].input, source_value);
|
||||
}
|
||||
|
||||
/// Undo of a retired step names the person's latest step, not the device's. A fresh copy of the document under a new
|
||||
/// peer id still undoes what its user did from the old one, and nobody else's.
|
||||
#[test]
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
//! Shared harness of the deterministic history simulations: a seeded generator, every history operation the History
|
||||
//! panel offers, and the checks each run makes after every operation.
|
||||
|
||||
use crate::{Network, NetworkId, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// What every node's implementation names, so nodes need no proto-node declarations. The first node drawn brings it,
|
||||
/// as the editor's first layer brings the subgraph every later one is built from.
|
||||
pub(super) const LEAF: NetworkId = NetworkId(1);
|
||||
|
||||
/// What the export holds while the document is empty, of another type than what a chain's bottom rests on.
|
||||
pub(super) fn empty_export() -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!("empty")),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A small xorshift generator, so a seed fixes the run.
|
||||
pub(super) struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn new(seed: u64) -> Self {
|
||||
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
|
||||
}
|
||||
|
||||
pub(super) fn below(&mut self, bound: usize) -> usize {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 % bound as u64) as usize
|
||||
}
|
||||
|
||||
pub(super) fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
|
||||
(!options.is_empty()).then(|| options[self.below(options.len())])
|
||||
}
|
||||
}
|
||||
|
||||
/// A kind of document the simulation edits.
|
||||
pub(super) trait Scenario {
|
||||
/// One interaction's ops for a random edit, as the editor would stage them.
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta>;
|
||||
|
||||
/// Panics with `context` when `registry` is not a document this scenario allows.
|
||||
fn assert_well_formed(context: &str, registry: &Registry);
|
||||
}
|
||||
|
||||
/// The nodes down the chain off the export, following each one's primary input.
|
||||
pub(super) fn stack(registry: &Registry) -> Vec<NodeId> {
|
||||
let mut nodes = Vec::new();
|
||||
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
|
||||
while let Some(NodeInput::Node { id, .. }) = below {
|
||||
if nodes.contains(&id) {
|
||||
break;
|
||||
}
|
||||
nodes.push(id);
|
||||
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
|
||||
}
|
||||
nodes
|
||||
}
|
||||
|
||||
/// What feeds into `node` from below.
|
||||
pub(super) fn below(registry: &Registry, node: NodeId) -> NodeInput {
|
||||
registry.node_instances[&node].inputs[0].input.clone()
|
||||
}
|
||||
|
||||
pub(super) fn on(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
|
||||
pub(super) fn value(number: usize) -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(number)),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a number from the environment variable `name`, so a run can be widened or replayed.
|
||||
pub(super) fn from_env<T: std::str::FromStr>(name: &str, default: T) -> T {
|
||||
std::env::var(name).ok().and_then(|text| text.parse().ok()).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// The ops of an edit, short enough to read in a failing run's log.
|
||||
fn summarize(ops: &[RegistryDelta]) -> String {
|
||||
let short = |id: &NodeId| id.0 % 1000;
|
||||
let input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => format!("{}", short(id)),
|
||||
_ => "value".to_string(),
|
||||
};
|
||||
ops.iter()
|
||||
.map(|op| match op {
|
||||
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
|
||||
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
|
||||
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
|
||||
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
|
||||
other => format!("{other:?}"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// The revs closing each interaction on the head's line, newest first.
|
||||
fn line_steps(session: &Session) -> Vec<Rev> {
|
||||
let mut steps = Vec::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
if delta.is_interaction_end() {
|
||||
steps.push(delta.id);
|
||||
}
|
||||
current = delta.parent;
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The revs closing interactions left behind on branches.
|
||||
fn branch_steps(session: &Session) -> Vec<Rev> {
|
||||
let line: HashSet<Rev> = {
|
||||
let mut line = HashSet::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
line.insert(delta.id);
|
||||
current = delta.parent;
|
||||
}
|
||||
line
|
||||
};
|
||||
let mut steps: Vec<Rev> = session
|
||||
.history()
|
||||
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
|
||||
.map(|delta| delta.id)
|
||||
.collect();
|
||||
steps.sort();
|
||||
steps
|
||||
}
|
||||
|
||||
/// The nodes the interaction ending at `end` added and deleted, by what it did in all.
|
||||
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
|
||||
let (mut added, mut removed) = (Vec::new(), Vec::new());
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddNode { id, .. } => added.push(*id),
|
||||
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
|
||||
_ => {}
|
||||
}
|
||||
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
|
||||
}
|
||||
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
|
||||
(net(&added, &removed), net(&removed, &added))
|
||||
}
|
||||
|
||||
/// The nodes the step ending at `end` added that a newer deletion on its own line had taken again.
|
||||
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
|
||||
let mut lost = HashSet::new();
|
||||
let mut added_at = HashMap::new();
|
||||
let mut line = Vec::new();
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
line.push(delta);
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
|
||||
added_at.entry(*id).or_insert(delta.timestamp);
|
||||
}
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
|
||||
&& added.contains(id)
|
||||
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
|
||||
{
|
||||
lost.insert(*id);
|
||||
}
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// The nodes live on the line just before the interaction ending at `end`.
|
||||
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
let mut line = Vec::new();
|
||||
while let Some(delta) = current {
|
||||
line.push(delta.clone());
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
line.reverse();
|
||||
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
|
||||
replayed.retired_registry().node_instances.keys().copied().collect()
|
||||
}
|
||||
|
||||
fn assert_consistent<S: Scenario>(context: &str, session: &Session) {
|
||||
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
|
||||
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
|
||||
let folded = session.snapshot_from_history().expect("history folds");
|
||||
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
|
||||
S::assert_well_formed(context, session.retired_registry());
|
||||
}
|
||||
|
||||
/// Closes the open interaction and retires it as one step.
|
||||
fn retire_step(session: &mut Session) {
|
||||
session.end_interaction().expect("close");
|
||||
for interaction in session.closed_interactions() {
|
||||
session.retire_interaction(&interaction).expect("retire");
|
||||
}
|
||||
}
|
||||
|
||||
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
|
||||
fn catch_up(follower: &mut Session, host: &Session) {
|
||||
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
|
||||
follower.follow(missing, host.head_rev()).expect("follow");
|
||||
}
|
||||
|
||||
/// A peer that joins now and holds what the host holds.
|
||||
fn fresh_follower(host: &Session) -> Session {
|
||||
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
|
||||
}
|
||||
|
||||
/// Runs `steps` random edits and history operations from `seed`. After each one the document must be well formed, the
|
||||
/// snapshot must be what history folds to, and a peer following the host must hold the same document.
|
||||
pub(super) fn simulate<S: Scenario>(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
|
||||
let mut random = Random::new(seed);
|
||||
let mut host = Session::with_identity(PeerId(1), UserId(1));
|
||||
let document = [
|
||||
RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(empty_export()),
|
||||
},
|
||||
];
|
||||
host.stage_ops(document).expect("stage the document");
|
||||
retire_step(&mut host);
|
||||
let mut follower = fresh_follower(&host);
|
||||
|
||||
for step in 0..steps {
|
||||
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
|
||||
match random.below(12) {
|
||||
0..=5 => {
|
||||
let ops = S::random_edit(&mut random, &mut host);
|
||||
if ops.is_empty() {
|
||||
continue;
|
||||
}
|
||||
log.push(format!("{step}: edit {}", summarize(&ops)));
|
||||
host.stage_ops(ops).expect("stage");
|
||||
retire_step(&mut host);
|
||||
catch_up(&mut follower, &host);
|
||||
}
|
||||
6 if host.can_undo() => {
|
||||
log.push(format!("{step}: undo"));
|
||||
host.undo().expect("undo");
|
||||
follower = fresh_follower(&host);
|
||||
}
|
||||
7 if host.can_redo() => {
|
||||
log.push(format!("{step}: redo"));
|
||||
host.redo().expect("redo");
|
||||
follower = fresh_follower(&host);
|
||||
}
|
||||
8 => {
|
||||
let steps = line_steps(&host);
|
||||
// Not the newest step, which going back to would leave everything as it is
|
||||
let Some(target) = random.pick(&steps[1.min(steps.len())..]) else { continue };
|
||||
log.push(format!("{step}: go back to {target:?}"));
|
||||
let (moved, _) = host.move_head_to(target).expect("go back");
|
||||
follower.apply_head_move(&moved).expect("follow the move");
|
||||
}
|
||||
9 => {
|
||||
let steps = line_steps(&host);
|
||||
// The first step makes the document, which nothing can do without
|
||||
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
|
||||
log.push(format!("{step}: remove {target:?}"));
|
||||
let (mut added, _) = added_and_removed(&host, target);
|
||||
// A node the line had before the step stays
|
||||
let earlier = live_before(&host, target);
|
||||
added.retain(|id| !earlier.contains(id));
|
||||
let (moved, _) = host.drop_interaction(target).expect("remove the step");
|
||||
follower.apply_head_move(&moved).expect("follow the removal");
|
||||
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the removed step's nodes {kept:?} are still there"), log));
|
||||
}
|
||||
10 | 11 => {
|
||||
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
|
||||
log.push(format!("{step}: bring back {target:?}"));
|
||||
let (mut added, removed) = added_and_removed(&host, target);
|
||||
// A node the line already had from this step and deleted since stays deleted
|
||||
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
|
||||
// As does one a newer deletion took on the step's own line
|
||||
let lost = lost_on_its_line(&host, target, &added);
|
||||
added.retain(|id| !lost.contains(id));
|
||||
host.restore_interaction(target).expect("bring back");
|
||||
catch_up(&mut follower, &host);
|
||||
let registry = host.retired_registry();
|
||||
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
|
||||
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
|
||||
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's nodes {missing:?} are missing"), log));
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the nodes {kept:?} the brought back step deleted are still there"), log));
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
let what = log.last().cloned().unwrap_or_default();
|
||||
assert_consistent::<S>(&context(&what, log), &host);
|
||||
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
|
||||
assert!(
|
||||
follower.retired_registry().value_equal(host.retired_registry()),
|
||||
"{}",
|
||||
context("the follower holds another document", log)
|
||||
);
|
||||
}
|
||||
host
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
TransferCurve(Vec<[f64; 2]>),
|
||||
TypeDefault(Type),
|
||||
}
|
||||
|
||||
/// Frozen mirror of the `Type` a paint input's lack of a paint stores.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Type {
|
||||
Concrete(TypeDescriptor),
|
||||
Item(Box<Type>),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypeDescriptor {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// 'Bevel & Emboss' gained a texture with its depth, and a gloss contour and a slope contour with its range, set to no texture and straight contours across the whole slope to keep the bevel as it was.
|
||||
#[migration("blending_nodes::effects::BevelAndEmbossNode"@1 => @2)]
|
||||
pub fn bevel_and_emboss_v1(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// The texture, its depth, the slope contour's range, the gloss and slope contours' antialiasing, and the gloss and slope contours.
|
||||
fn added_inputs() -> [NodeInput; 7] {
|
||||
let straight = || literal(Tagged::TransferCurve(vec![[0., 0.], [1., 1.]]));
|
||||
let no_paint = Tagged::TypeDefault(Type::Item(Box::new(Type::Concrete(TypeDescriptor {
|
||||
name: "graphic_types::graphic::Graphic".to_string(),
|
||||
}))));
|
||||
|
||||
[
|
||||
literal(no_paint),
|
||||
literal(Tagged::Number(100.)),
|
||||
literal(Tagged::Number(100.)),
|
||||
literal(Tagged::Bool(false)),
|
||||
literal(Tagged::Bool(false)),
|
||||
straight(),
|
||||
straight(),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(13, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BevelAndEmbossV1, &contract());
|
||||
check_undo(&BevelAndEmbossV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_options_that_leave_the_bevel_as_it_was() {
|
||||
let inputs: Vec<_> = (0..13).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&BevelAndEmbossV1);
|
||||
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&BevelAndEmbossV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, bevel), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Bevel & Emboss' defaults to fitting gradient textures without a transform across the content.
|
||||
#[migration("blending_nodes::effects::BevelAndEmbossNode"@2 => @3)]
|
||||
pub fn bevel_and_emboss_v2(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(20, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BevelAndEmbossV2, &contract());
|
||||
check_undo(&BevelAndEmbossV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_an_unset_texture_placement() {
|
||||
let inputs: Vec<_> = (0..20).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&BevelAndEmbossV2);
|
||||
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&BevelAndEmbossV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, bevel), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
use migration_core::{Inputs, NodeInput, encode, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
TypeDefault(Type),
|
||||
}
|
||||
|
||||
/// Frozen mirror of the `Type` an empty list of graphics stores.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Type {
|
||||
Concrete(TypeDescriptor),
|
||||
List(Box<Type>),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypeDescriptor {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// 'Blur' gained a radius mask after its radius, left empty to keep blurring the whole content by the radius.
|
||||
#[migration("blending_nodes::effects::BlurNode"@2 => @3)]
|
||||
pub fn blur_v2(inputs: &mut Inputs) {
|
||||
inputs.insert(2, empty_radius_mask());
|
||||
}
|
||||
|
||||
/// The radius mask input with nothing connected and not exposed, as the node's definition gives it.
|
||||
fn empty_radius_mask() -> NodeInput {
|
||||
let no_graphics = Tagged::TypeDefault(Type::List(Box::new(Type::Concrete(TypeDescriptor {
|
||||
name: "graphic_types::graphic::Graphic".to_string(),
|
||||
}))));
|
||||
NodeInput::Value {
|
||||
value: encode(&no_graphics),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BlurV2, &contract());
|
||||
check_undo(&BlurV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_an_empty_radius_mask_after_the_radius() {
|
||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&BlurV2);
|
||||
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&BlurV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, empty_radius_mask());
|
||||
assert_eq!(fixture.declaration_of(&migrated, blur), Some(decl!("blending_nodes::effects::BlurNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, blur), expected);
|
||||
assert!(matches!(expected[2], NodeInput::Value { exposed: false, .. }), "the radius mask is not exposed");
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// 'Convolution Kernel' gained Apply to Alpha after its offset, left off to keep the content's coverage as it is.
|
||||
#[migration("blending_nodes::filters::ConvolutionKernelNode"@1 => @2)]
|
||||
pub fn convolution_kernel_v1(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::Bool(false)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ConvolutionKernelV1, &contract());
|
||||
check_undo(&ConvolutionKernelV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_appends_apply_to_alpha_turned_off() {
|
||||
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&ConvolutionKernelV1);
|
||||
let kernel = fixture.add(decl!("blending_nodes::filters::ConvolutionKernelNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&ConvolutionKernelV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, kernel), Some(decl!("blending_nodes::filters::ConvolutionKernelNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, kernel), [inputs, vec![literal(Tagged::Bool(false))]].concat());
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Drop Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
|
||||
#[migration("blending_nodes::effects::DropShadowNode"@1 => @2)]
|
||||
pub fn drop_shadow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&DropShadowV1, &contract());
|
||||
check_undo(&DropShadowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&DropShadowV1);
|
||||
let drop_shadow = fixture.add(decl!("blending_nodes::effects::DropShadowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&DropShadowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, drop_shadow), Some(decl!("blending_nodes::effects::DropShadowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, drop_shadow), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Inner Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
|
||||
#[migration("blending_nodes::effects::InnerGlowNode"@1 => @2)]
|
||||
pub fn inner_glow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&InnerGlowV1, &contract());
|
||||
check_undo(&InnerGlowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&InnerGlowV1);
|
||||
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&InnerGlowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
Integer(i64),
|
||||
}
|
||||
|
||||
/// 'Inner Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth.
|
||||
#[migration("blending_nodes::effects::InnerGlowNode"@2 => @3)]
|
||||
pub fn inner_glow_v2(inputs: &mut Inputs) {
|
||||
inputs.insert(8, literal(Tagged::Number(0.)));
|
||||
inputs.insert(9, literal(Tagged::Number(0.)));
|
||||
inputs.insert(10, literal(Tagged::Integer(0)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(9, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&InnerGlowV2, &contract());
|
||||
check_undo(&InnerGlowV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
|
||||
let inputs: Vec<_> = (0..9).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&InnerGlowV2);
|
||||
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&InnerGlowV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.splice(8..8, [literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
|
||||
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Inner Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
|
||||
#[migration("blending_nodes::effects::InnerShadowNode"@1 => @2)]
|
||||
pub fn inner_shadow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&InnerShadowV1, &contract());
|
||||
check_undo(&InnerShadowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&InnerShadowV1);
|
||||
let inner_shadow = fixture.add(decl!("blending_nodes::effects::InnerShadowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&InnerShadowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, inner_shadow), Some(decl!("blending_nodes::effects::InnerShadowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, inner_shadow), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
MaskMode(MaskMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MaskMode {
|
||||
Luminance,
|
||||
}
|
||||
|
||||
/// 'Mask' became an effect masking any graphic by any other, keeping its content and mask and gaining its mode, density, feather, and invert at their defaults.
|
||||
#[migration("raster_nodes::std_nodes::MaskNode"@1 => "blending_nodes::masks::MaskNode"@2)]
|
||||
pub fn mask_by_any_graphic(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::MaskMode(MaskMode::Luminance)));
|
||||
inputs.push(literal(Tagged::Number(100.)));
|
||||
inputs.push(literal(Tagged::Number(0.)));
|
||||
inputs.push(literal(Tagged::Bool(false)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MaskByAnyGraphic, &contract());
|
||||
check_undo(&MaskByAnyGraphic, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_content_and_mask_and_adds_the_defaults() {
|
||||
let (content, stencil) = (literal(1.), literal(2.));
|
||||
|
||||
let mut fixture = Fixture::new(&MaskByAnyGraphic);
|
||||
let mask = fixture.add(decl!("raster_nodes::std_nodes::MaskNode"@1), vec![content.clone(), stencil.clone()]);
|
||||
let migrated = fixture.migrate(&MaskByAnyGraphic).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, mask), Some(decl!("blending_nodes::masks::MaskNode"@2)));
|
||||
let defaults = [
|
||||
literal(Tagged::MaskMode(MaskMode::Luminance)),
|
||||
literal(Tagged::Number(100.)),
|
||||
literal(Tagged::Number(0.)),
|
||||
literal(Tagged::Bool(false)),
|
||||
];
|
||||
assert_eq!(fixture.inputs(&migrated, mask), [[content, stencil].as_slice(), &defaults].concat());
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,3 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod bevel_and_emboss_v1;
|
||||
mod bevel_and_emboss_v2;
|
||||
mod blur_v2;
|
||||
mod convolution_kernel_v1;
|
||||
mod drop_shadow_v1;
|
||||
mod inner_glow_v1;
|
||||
mod inner_glow_v2;
|
||||
mod inner_shadow_v1;
|
||||
mod mask_by_any_graphic;
|
||||
mod outer_glow_v1;
|
||||
mod outer_glow_v2;
|
||||
mod outline_v1;
|
||||
mod outline_v2;
|
||||
mod outline_v3;
|
||||
mod paint_overlay_from_color_overlay;
|
||||
mod paint_overlay_v2;
|
||||
mod radial_blur_v1;
|
||||
mod renames;
|
||||
mod satin_v1;
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Outer Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
|
||||
#[migration("blending_nodes::effects::OuterGlowNode"@1 => @2)]
|
||||
pub fn outer_glow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OuterGlowV1, &contract());
|
||||
check_undo(&OuterGlowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OuterGlowV1);
|
||||
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&OuterGlowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
Integer(i64),
|
||||
}
|
||||
|
||||
/// 'Outer Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth.
|
||||
#[migration("blending_nodes::effects::OuterGlowNode"@2 => @3)]
|
||||
pub fn outer_glow_v2(inputs: &mut Inputs) {
|
||||
inputs.insert(7, literal(Tagged::Number(0.)));
|
||||
inputs.insert(8, literal(Tagged::Number(0.)));
|
||||
inputs.insert(9, literal(Tagged::Integer(0)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OuterGlowV2, &contract());
|
||||
check_undo(&OuterGlowV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
|
||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OuterGlowV2);
|
||||
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&OuterGlowV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.splice(7..7, [literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
|
||||
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Outline' gained a blend mode after its color, set to Normal, which composites the outline as before.
|
||||
#[migration("blending_nodes::effects::OutlineNode"@1 => @2)]
|
||||
pub fn outline_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OutlineV1, &contract());
|
||||
check_undo(&OutlineV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OutlineV1);
|
||||
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&OutlineV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// 'Outline' takes its color as any paint now, and gained a Contour Gradient option, set off to keep painting by the paint's own placement.
|
||||
#[migration("blending_nodes::effects::OutlineNode"@2 => @3)]
|
||||
pub fn outline_v2(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::Bool(false)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OutlineV2, &contract());
|
||||
check_undo(&OutlineV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_contour_gradient_off() {
|
||||
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OutlineV2);
|
||||
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&OutlineV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.push(literal(Tagged::Bool(false)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Outline' defaults to fitting gradients without a transform across the content.
|
||||
#[migration("blending_nodes::effects::OutlineNode"@3 => @4)]
|
||||
pub fn outline_v3(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(6, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OutlineV3, &contract());
|
||||
check_undo(&OutlineV3, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_an_unset_placement() {
|
||||
let inputs: Vec<_> = (0..6).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OutlineV3);
|
||||
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@3), inputs.clone());
|
||||
let migrated = fixture.migrate(&OutlineV3).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@4)));
|
||||
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Node, migration};
|
||||
|
||||
/// 'Color Overlay' became the 'Paint Overlay' effect, which takes its color as a solid paint. A name it stored as its default would misname it.
|
||||
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => "blending_nodes::effects::PaintOverlayNode"@2)]
|
||||
pub fn paint_overlay_from_color_overlay(node: &Node, attributes: &mut Attributes) {
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Color Overlay") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::TimeStamp;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
let contract = SourceContract {
|
||||
display_names: &["Color Overlay"],
|
||||
..SourceContract::new(4, |random, _| literal(random.below(10) as f64))
|
||||
};
|
||||
check_commutation(&PaintOverlayFromColorOverlay, &contract);
|
||||
check_undo(&PaintOverlayFromColorOverlay, &contract);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_old_default_name_is_cleared() {
|
||||
for (name, kept) in [("Color Overlay", None), ("Tint", Some("Tint"))] {
|
||||
let mut fixture = Fixture::new(&PaintOverlayFromColorOverlay);
|
||||
let overlay = fixture.add(decl!("raster_nodes::blending_nodes::ColorOverlayNode"@1), Vec::new());
|
||||
let attributes = fixture.registry.node_instances.get_mut(&overlay).unwrap().attributes_mut();
|
||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let migrated = fixture.migrate(&PaintOverlayFromColorOverlay).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@2)));
|
||||
assert_eq!(migrated.node_instances[&overlay].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Paint Overlay' defaults to fitting gradients without a transform across the content.
|
||||
#[migration("blending_nodes::effects::PaintOverlayNode"@2 => @3)]
|
||||
pub fn paint_overlay_v2(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PaintOverlayV2, &contract());
|
||||
check_undo(&PaintOverlayV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_an_unset_placement() {
|
||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&PaintOverlayV2);
|
||||
let overlay = fixture.add(decl!("blending_nodes::effects::PaintOverlayNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&PaintOverlayV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, overlay), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const CENTER: u32 = 3;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
DVec2([f64; 2]),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Radial Blur' takes a transform placing a circle in place of its center, which the transform's translation keeps.
|
||||
/// A wired center can't be read before it runs, so it becomes the identity, the circle at the content's origin.
|
||||
#[migration("blending_nodes::distortions::RadialBlurNode"@1 => @2)]
|
||||
pub fn radial_blur_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
|
||||
let Some(center) = node.inputs().get(CENTER as usize) else {
|
||||
return Err(MigrationError::invariant("Radial Blur has a Center input"));
|
||||
};
|
||||
|
||||
inputs.set(CENTER, transform_input(¢er.input));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The transform input placing the circle at the old `center`, shown in the graph if it was exposed or wired.
|
||||
fn transform_input(center: &NodeInput) -> NodeInput {
|
||||
let ([x, y], exposed) = match center {
|
||||
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(center) {
|
||||
Some(Tagged::DVec2(center)) => (center, *exposed),
|
||||
_ => ([0., 0.], *exposed),
|
||||
},
|
||||
_ => ([0., 0.], true),
|
||||
};
|
||||
|
||||
NodeInput::Value {
|
||||
value: encode(&Tagged::DAffine2([1., 0., 0., 1., x, y])),
|
||||
exposed,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const CENTER_SLOT: usize = CENTER as usize;
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| match slot {
|
||||
CENTER_SLOT => literal(Tagged::DVec2([random.below(10) as f64, random.below(10) as f64])),
|
||||
_ => literal(random.below(10) as f64),
|
||||
})
|
||||
}
|
||||
|
||||
fn radial_blur_inputs(center: NodeInput) -> Vec<NodeInput> {
|
||||
let mut inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
||||
inputs[CENTER_SLOT] = center;
|
||||
inputs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RadialBlurV1, &contract());
|
||||
check_undo(&RadialBlurV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_center_becomes_the_translation_of_the_transform_in_its_place() {
|
||||
let mut fixture = Fixture::new(&RadialBlurV1);
|
||||
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(literal(Tagged::DVec2([12.5, -4.]))));
|
||||
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
|
||||
|
||||
let expected = radial_blur_inputs(literal(Tagged::DAffine2([1., 0., 0., 1., 12.5, -4.])));
|
||||
assert_eq!(fixture.declaration_of(&migrated, radial_blur), Some(decl!("blending_nodes::distortions::RadialBlurNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, radial_blur), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wired_center_becomes_the_identity_shown_in_the_graph() {
|
||||
let mut fixture = Fixture::new(&RadialBlurV1);
|
||||
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(NodeInput::Node { id: source, index: 0 }));
|
||||
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
|
||||
|
||||
let identity = NodeInput::Value {
|
||||
value: encode(&Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
|
||||
exposed: true,
|
||||
};
|
||||
assert_eq!(fixture.inputs(&migrated, radial_blur), radial_blur_inputs(identity));
|
||||
}
|
||||
}
|
||||
@@ -3,4 +3,3 @@
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
|
||||
rename!("blending_nodes::filters::AddNoiseNode"@1 => "blending_nodes::filters::SpeckleNode"@2);
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Satin' gained a blend mode after its color, set to Normal to keep compositing the shading as before.
|
||||
#[migration("blending_nodes::effects::SatinNode"@1 => @2)]
|
||||
pub fn satin_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&SatinV1, &contract());
|
||||
check_undo(&SatinV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&SatinV1);
|
||||
let satin = fixture.add(decl!("blending_nodes::effects::SatinNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&SatinV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, satin), Some(decl!("blending_nodes::effects::SatinNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, satin), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const GRADIENT_FORM: u32 = 4;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
#[serde(alias = "GradientType")]
|
||||
GradientForm(GradientForm),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GradientForm {
|
||||
Linear,
|
||||
Radial,
|
||||
}
|
||||
|
||||
/// 'Fill' gives the gradient it paints the curvatures of a form, rather than the form: 0 and 0 for linear, and -1 and 0.5 for radial.
|
||||
/// A wired form becomes linear, and the curvatures stay shown in the graph where the form was.
|
||||
#[migration("graphene_core::vector::FillNode"@1 => @2)]
|
||||
pub fn fill_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
|
||||
let Some(form) = node.inputs().get(GRADIENT_FORM as usize) else {
|
||||
return Err(MigrationError::invariant("Fill has a gradient form input"));
|
||||
};
|
||||
let [start, end] = match literal_of::<Tagged>(&form.input) {
|
||||
Some(Tagged::GradientForm(GradientForm::Radial)) => [-1., 0.5],
|
||||
_ => [0., 0.],
|
||||
};
|
||||
|
||||
let exposed = match form.input {
|
||||
NodeInput::Value { exposed, .. } => exposed,
|
||||
_ => true,
|
||||
};
|
||||
let curvature = |curvature: f64| NodeInput::Value {
|
||||
value: encode(&Tagged::Number(curvature)),
|
||||
exposed,
|
||||
};
|
||||
|
||||
inputs.set(GRADIENT_FORM, curvature(start));
|
||||
inputs.insert(GRADIENT_FORM + 1, curvature(end));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const FORM_SLOT: usize = GRADIENT_FORM as usize;
|
||||
|
||||
/// A form stored under its name from before 'Gradient Type' became 'Gradient Form'.
|
||||
#[derive(Serialize)]
|
||||
enum LegacyTagged {
|
||||
GradientType(GradientForm),
|
||||
}
|
||||
|
||||
fn form(form: GradientForm) -> NodeInput {
|
||||
literal(Tagged::GradientForm(form))
|
||||
}
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, slot| match slot {
|
||||
FORM_SLOT if random.below(2) == 0 => form(GradientForm::Radial),
|
||||
FORM_SLOT => form(GradientForm::Linear),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&FillV1, &contract());
|
||||
check_undo(&FillV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forms_become_their_curvature_presets() {
|
||||
let other_inputs: Vec<NodeInput> = (0..7).map(|index| literal(Tagged::Number(index as f64))).collect();
|
||||
let shown_radial = NodeInput::Value {
|
||||
value: encode(&Tagged::GradientForm(GradientForm::Radial)),
|
||||
exposed: true,
|
||||
};
|
||||
let curvature = |curvature: f64, exposed: bool| NodeInput::Value {
|
||||
value: encode(&Tagged::Number(curvature)),
|
||||
exposed,
|
||||
};
|
||||
|
||||
// The curvatures stay shown in the graph where an exposed or wired form was, and the inputs after them keep their values
|
||||
for (old_form, [start, end], exposed) in [
|
||||
(form(GradientForm::Linear), [0., 0.], false),
|
||||
(form(GradientForm::Radial), [-1., 0.5], false),
|
||||
(literal(LegacyTagged::GradientType(GradientForm::Radial)), [-1., 0.5], false),
|
||||
(shown_radial, [-1., 0.5], true),
|
||||
(NodeInput::Import { index: 0 }, [0., 0.], true),
|
||||
] {
|
||||
let mut old_inputs = other_inputs.clone();
|
||||
old_inputs[FORM_SLOT] = old_form;
|
||||
|
||||
let mut fixture = Fixture::new(&FillV1);
|
||||
let fill = fixture.add(decl!("graphene_core::vector::FillNode"@1), old_inputs);
|
||||
let migrated = fixture.migrate(&FillV1).unwrap();
|
||||
|
||||
let mut expected = other_inputs.clone();
|
||||
expected.splice(FORM_SLOT..=FORM_SLOT, [curvature(start, exposed), curvature(end, exposed)]);
|
||||
assert_eq!(fixture.declaration_of(&migrated, fill), Some(decl!("graphene_core::vector::FillNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, fill), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Migrations of the nodes in `graphene_core`.
|
||||
|
||||
mod fill_v1;
|
||||
mod passthrough_from_read_attribute_gradient_form_node;
|
||||
mod passthrough_from_upload_texture_node;
|
||||
mod renames;
|
||||
mod vary_colors_from_assign_colors;
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// 'Read Attribute Gradient Form' is gone since no node writes that attribute anymore, so it passes its content on and drops the attribute name.
|
||||
#[migration("graphic_nodes::graphic::ReadAttributeGradientFormNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
||||
pub fn passthrough_from_read_attribute_gradient_form_node(inputs: &mut Inputs) {
|
||||
inputs.truncate(1);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PassthroughFromReadAttributeGradientFormNode, &contract());
|
||||
check_undo(&PassthroughFromReadAttributeGradientFormNode, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_content_and_drops_the_name() {
|
||||
let (content, name) = (literal(1.), literal("gradient_form".to_string()));
|
||||
|
||||
let mut fixture = Fixture::new(&PassthroughFromReadAttributeGradientFormNode);
|
||||
let read_attribute = fixture.add(decl!("graphic_nodes::graphic::ReadAttributeGradientFormNode"@1), vec![content.clone(), name]);
|
||||
let migrated = fixture.migrate(&PassthroughFromReadAttributeGradientFormNode).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, read_attribute), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, read_attribute), [content]);
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration uses.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
#[serde(alias = "GradientType")]
|
||||
GradientForm(GradientForm),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GradientForm {
|
||||
Linear,
|
||||
Radial,
|
||||
}
|
||||
|
||||
const FORM: u32 = 1;
|
||||
|
||||
/// 'Gradient Form' became 'Gradient Curvature', with start and end curvatures taking the presets of the form it set: 0 and 0 for linear, -1 and 0.5 for
|
||||
/// radial. A wired form becomes linear, the curvatures stay shown in the graph where the form was, and a name it stored as its default is cleared.
|
||||
#[migration("math_nodes::GradientFormNode"@1 => "math_nodes::GradientCurvatureNode"@2)]
|
||||
pub fn gradient_curvature_from_gradient_form(node: &Node, inputs: &mut Inputs, attributes: &mut Attributes) -> Result<(), MigrationError> {
|
||||
let [_, form] = node.inputs() else {
|
||||
return Err(MigrationError::invariant("Gradient Form has two inputs"));
|
||||
};
|
||||
let [start, end] = match literal_of::<Tagged>(&form.input) {
|
||||
Some(Tagged::GradientForm(GradientForm::Radial)) => [-1., 0.5],
|
||||
_ => [0., 0.],
|
||||
};
|
||||
|
||||
let exposed = match form.input {
|
||||
NodeInput::Value { exposed, .. } => exposed,
|
||||
_ => true,
|
||||
};
|
||||
let curvature = |curvature: f64| NodeInput::Value {
|
||||
value: encode(&Tagged::Number(curvature)),
|
||||
exposed,
|
||||
};
|
||||
|
||||
inputs.set(FORM, curvature(start));
|
||||
inputs.push(curvature(end));
|
||||
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Gradient Form") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::TimeStamp;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn form(form: GradientForm) -> NodeInput {
|
||||
literal(Tagged::GradientForm(form))
|
||||
}
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract {
|
||||
display_names: &["Gradient Form"],
|
||||
..SourceContract::new(2, |random, slot| match slot {
|
||||
1 if random.below(2) == 0 => form(GradientForm::Radial),
|
||||
1 => form(GradientForm::Linear),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&GradientCurvatureFromGradientForm, &contract());
|
||||
check_undo(&GradientCurvatureFromGradientForm, &contract());
|
||||
}
|
||||
|
||||
/// A form stored under its name from before 'Gradient Type' became 'Gradient Form'.
|
||||
#[derive(Serialize)]
|
||||
enum LegacyTagged {
|
||||
GradientType(GradientForm),
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forms_become_their_curvature_presets() {
|
||||
let gradient = literal(Tagged::Number(0.));
|
||||
let shown_radial = NodeInput::Value {
|
||||
value: encode(&Tagged::GradientForm(GradientForm::Radial)),
|
||||
exposed: true,
|
||||
};
|
||||
let curvature = |curvature: f64, exposed: bool| NodeInput::Value {
|
||||
value: encode(&Tagged::Number(curvature)),
|
||||
exposed,
|
||||
};
|
||||
|
||||
// Curvatures stay shown in the graph where an exposed or wired form was
|
||||
for (old_form, [start, end], exposed) in [
|
||||
(form(GradientForm::Linear), [0., 0.], false),
|
||||
(form(GradientForm::Radial), [-1., 0.5], false),
|
||||
(literal(LegacyTagged::GradientType(GradientForm::Radial)), [-1., 0.5], false),
|
||||
(shown_radial, [-1., 0.5], true),
|
||||
(NodeInput::Import { index: 0 }, [0., 0.], true),
|
||||
] {
|
||||
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
|
||||
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![gradient.clone(), old_form]);
|
||||
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, node), Some(decl!("math_nodes::GradientCurvatureNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, node), [gradient.clone(), curvature(start, exposed), curvature(end, exposed)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_old_default_name_is_cleared() {
|
||||
for (name, kept) in [("Gradient Form", None), ("Spotlight", Some("Spotlight"))] {
|
||||
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
|
||||
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![literal(Tagged::Number(0.)), form(GradientForm::Linear)]);
|
||||
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
|
||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
|
||||
|
||||
assert_eq!(migrated.node_instances[&node].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod gradient_curvature_from_gradient_form;
|
||||
mod math_formula_from_math_f;
|
||||
mod renames;
|
||||
@@ -1,43 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
}
|
||||
|
||||
/// 'Make Opaque' gained a Strength percentage, set to 100% to keep making the content fully opaque.
|
||||
#[migration("raster_nodes::adjustments::MakeOpaqueNode"@1 => @2)]
|
||||
pub fn make_opaque_v1(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::Number(100.)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MakeOpaqueV1, &contract());
|
||||
check_undo(&MakeOpaqueV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_content_and_adds_full_strength() {
|
||||
let content = literal(1.);
|
||||
|
||||
let mut fixture = Fixture::new(&MakeOpaqueV1);
|
||||
let make_opaque = fixture.add(decl!("raster_nodes::adjustments::MakeOpaqueNode"@1), vec![content.clone()]);
|
||||
let migrated = fixture.migrate(&MakeOpaqueV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, make_opaque), Some(decl!("raster_nodes::adjustments::MakeOpaqueNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, make_opaque), [content, literal(Tagged::Number(100.))]);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
//! Migrations of the nodes in `raster_nodes`.
|
||||
|
||||
mod make_opaque_v1;
|
||||
mod mandelbrot_v1;
|
||||
mod mandelbrot_v2;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod noise_pattern_v2;
|
||||
mod pattern_square;
|
||||
mod renames;
|
||||
@@ -1,185 +0,0 @@
|
||||
use migration_core::attr::node::VISIBLE;
|
||||
use migration_core::attr::node::ui::POSITION;
|
||||
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// 'Noise Pattern' writes its value as the gray at that gamma-encoded level rather than as linear light, so whatever read it reads it through a
|
||||
/// 'Gamma Correction' at its default gamma of 2.2, which turns the new gray back into about the old one.
|
||||
#[migration("raster_nodes::std_nodes::NoisePatternNode"@2 => @3)]
|
||||
pub fn noise_pattern_v2(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
|
||||
let consumers = downstream.consumers(0);
|
||||
if consumers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let gamma_correction = downstream.add_node(NewNode {
|
||||
declaration: decl!("raster_nodes::adjustments::GammaCorrectionNode"@1),
|
||||
inputs: vec![NodeInput::Node { id: node.id(), index: 0 }, literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))],
|
||||
});
|
||||
for consumer in consumers {
|
||||
downstream.connect(OutputConnector { node: gamma_correction, output: 0 }, consumer);
|
||||
}
|
||||
|
||||
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
|
||||
if !node.attributes().get_or(VISIBLE, true) {
|
||||
attributes.set(gamma_correction, VISIBLE, &false);
|
||||
}
|
||||
|
||||
// The Gamma Correction takes the pattern's place, with the pattern before it
|
||||
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
|
||||
attributes.set(gamma_correction, POSITION, &stored);
|
||||
}
|
||||
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::{Implementation, Network, NetworkId, NodeId, ROOT_NETWORK, TimeStamp};
|
||||
use migration_core::Declaration;
|
||||
use migration_core::attr::node::ui::IS_LAYER;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@2);
|
||||
const GAMMA_CORRECTION: Declaration = decl!("raster_nodes::adjustments::GammaCorrectionNode"@1);
|
||||
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(15, |random, _| literal(Tagged::Number(random.below(10) as f64)))
|
||||
}
|
||||
|
||||
fn noise_inputs() -> Vec<NodeInput> {
|
||||
(0..15).map(|slot| literal(Tagged::Number(slot as f64))).collect()
|
||||
}
|
||||
|
||||
fn wire(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&NoisePatternV2, &contract());
|
||||
check_undo(&NoisePatternV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_reader_reads_the_pattern_through_one_gamma_correction() {
|
||||
let mut fixture = Fixture::new(&NoisePatternV2);
|
||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
||||
let both_slots = fixture.add(CONSUMER, vec![wire(noise), wire(noise)]);
|
||||
let second_slot = fixture.add(CONSUMER, vec![literal(Tagged::Number(0.)), wire(noise)]);
|
||||
fixture.export(wire(noise));
|
||||
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, noise), noise_inputs());
|
||||
|
||||
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, second_slot)[1] else {
|
||||
panic!("the consumer should read a node")
|
||||
};
|
||||
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
|
||||
assert_eq!(fixture.inputs(&migrated, gamma_correction), [wire(noise), literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))]);
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, both_slots), [wire(gamma_correction), wire(gamma_correction)]);
|
||||
assert_eq!(fixture.inputs(&migrated, second_slot)[0], literal(Tagged::Number(0.)));
|
||||
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(gamma_correction)));
|
||||
assert_eq!(migrated.node_instances.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disabled_pattern_is_read_through_a_disabled_gamma_correction() {
|
||||
let visibility_of_gamma_correction = |visible: bool| {
|
||||
let mut fixture = Fixture::new(&NoisePatternV2);
|
||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
||||
if !visible {
|
||||
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
|
||||
attributes.set_serialized(VISIBLE, &false, TimeStamp::ORIGIN).unwrap();
|
||||
}
|
||||
let consumer = fixture.add(CONSUMER, vec![wire(noise)]);
|
||||
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
||||
|
||||
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, consumer)[0] else {
|
||||
panic!("the consumer should read a node")
|
||||
};
|
||||
migrated.node_instances[&gamma_correction].attributes().get_typed::<bool>(VISIBLE)
|
||||
};
|
||||
|
||||
// Visible is the default, so only a disabled pattern writes it
|
||||
assert_eq!(visibility_of_gamma_correction(false), Some(false));
|
||||
assert_eq!(visibility_of_gamma_correction(true), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unread_pattern_gains_no_gamma_correction() {
|
||||
let mut fixture = Fixture::new(&NoisePatternV2);
|
||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
||||
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
|
||||
assert_eq!(migrated.node_instances.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pattern_in_a_subgraph_is_read_through_a_gamma_correction_inside_it() {
|
||||
let mut fixture = Fixture::new(&NoisePatternV2);
|
||||
|
||||
// A custom subgraph exporting the pattern, read by the root network's export
|
||||
let (subgraph, instance) = (NetworkId(100), NodeId(100));
|
||||
fixture.registry.networks.insert(subgraph, Network::default());
|
||||
let instance_node = document_graph_storage::Node::new(ROOT_NETWORK, Implementation::Network(subgraph), 0);
|
||||
fixture.registry.node_instances.insert(instance, instance_node);
|
||||
let noise = fixture.add_in(subgraph, NOISE_PATTERN, noise_inputs());
|
||||
fixture.export_from(subgraph, wire(noise));
|
||||
fixture.export(wire(instance));
|
||||
|
||||
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
||||
|
||||
let Some(NodeInput::Node { id: gamma_correction, .. }) = migrated.networks[&subgraph].exports[0].target else {
|
||||
panic!("the subgraph's export should read a node")
|
||||
};
|
||||
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
|
||||
assert_eq!(migrated.node_instances[&gamma_correction].network(), subgraph);
|
||||
assert_eq!(fixture.inputs(&migrated, gamma_correction)[0], wire(noise));
|
||||
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(instance)));
|
||||
}
|
||||
|
||||
/// The positions of the pattern and its Gamma Correction after migrating a pattern at `position`, read by a layer's chain or by another node.
|
||||
fn placed_gamma_correction(position: Position, read_by_layer: bool) -> [Option<Position>; 2] {
|
||||
let mut fixture = Fixture::new(&NoisePatternV2);
|
||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
||||
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
|
||||
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let (reader, slot) = if read_by_layer {
|
||||
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::Number(0.)), wire(noise)]);
|
||||
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
|
||||
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
|
||||
(layer, 1)
|
||||
} else {
|
||||
(fixture.add(CONSUMER, vec![wire(noise)]), 0)
|
||||
};
|
||||
|
||||
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
||||
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, reader)[slot] else {
|
||||
panic!("slot {slot} of the reader should read a node")
|
||||
};
|
||||
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
|
||||
|
||||
[noise, gamma_correction].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gamma_correction_takes_the_place_of_a_chained_or_placed_pattern() {
|
||||
let chained = Position::Relative([-CHAIN_WIDTH, 0]);
|
||||
for (position, read_by_layer) in [(chained, true), (Position::Absolute([5, 5]), false)] {
|
||||
assert_eq!(placed_gamma_correction(position, read_by_layer), [Some(chained), Some(position)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,24 +148,10 @@ pub const CURVATURE_COMB_MAX_TEETH_PER_SEGMENT: f64 = 128.;
|
||||
pub const CURVATURE_COMB_MAX_TOOTH_LENGTH: f64 = 2000.;
|
||||
|
||||
// GRADIENT TOOL
|
||||
pub const GRADIENT_LINE_WIDTH: f64 = 2.;
|
||||
// Half the height of a midpoint diamond across the gradient line
|
||||
pub const GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT: f64 = 5.;
|
||||
// Half the width of a midpoint diamond along the gradient line
|
||||
pub const GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH: f64 = 3.;
|
||||
// The radius of the circle approximating a midpoint diamond, which a press is measured against
|
||||
pub const GRADIENT_MIDPOINT_DIAMOND_RADIUS: f64 = 4.;
|
||||
// The radius of a color stop dot at its regular size, which a press is measured against
|
||||
pub const GRADIENT_STOP_RADIUS: f64 = MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1.;
|
||||
pub const GRADIENT_MIDPOINT_MIN: f64 = 0.01;
|
||||
pub const GRADIENT_MIDPOINT_MAX: f64 = 0.99;
|
||||
pub const GRADIENT_STOP_MIN_VIEWPORT_GAP: f64 = 10.;
|
||||
// In viewport pixels from a contour's dashed rim, within which a press takes hold of it
|
||||
pub const GRADIENT_CONTOUR_RIM_GRAB_DISTANCE: f64 = 5.;
|
||||
// In viewport pixels, within which a dragged contour handle snaps onto making its contour a line or a point
|
||||
pub const GRADIENT_CONTOUR_SNAP_DISTANCE: f64 = 4.;
|
||||
// In viewport pixels, the shortest an end circle's semi-minor axis lines are drawn, below which they have no aspect handles at their tips
|
||||
pub const GRADIENT_SEMI_MINOR_AXIS_MIN_LENGTH: f64 = 20.;
|
||||
|
||||
// PEN TOOL
|
||||
pub const CREATE_CURVE_THRESHOLD: f64 = 5.;
|
||||
|
||||
@@ -103,22 +103,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
DialogMessage::RequestExportDialog => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
let artboards = document
|
||||
.metadata()
|
||||
.all_layers()
|
||||
.filter(|&layer| document.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| {
|
||||
let name = document
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
.collect();
|
||||
|
||||
self.export_dialog.artboards = artboards;
|
||||
self.export_dialog.artboards = document.artboard_names().into_iter().collect();
|
||||
|
||||
if let ExportBounds::Artboard(layer) = self.export_dialog.bounds
|
||||
&& !self.export_dialog.artboards.contains_key(&layer)
|
||||
|
||||
@@ -94,9 +94,9 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||
|
||||
impl LayoutHolder for ExportDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
// The vector type, then the raster ones
|
||||
// The vector types, then the raster ones
|
||||
let file_types = [
|
||||
vec![(FileType::Svg, "SVG")],
|
||||
vec![(FileType::Svg, "SVG"), (FileType::Pdf, "PDF")],
|
||||
vec![
|
||||
(FileType::Png, "PNG"),
|
||||
(FileType::Jpg, "JPG"),
|
||||
@@ -131,14 +131,25 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let scale_description = match self.file_type {
|
||||
FileType::Pdf => "Resolution of the images of effects and other content PDF can't draw itself, where 1 is 300 DPI.",
|
||||
_ => "Size of the exported image relative to the document's size.",
|
||||
};
|
||||
let resolution = vec![
|
||||
TextLabel::new("Scale Factor").table_align(true).sizing(WidgetSizing::fixed(100)).widget_instance(),
|
||||
TextLabel::new("Scale Factor")
|
||||
.table_align(true)
|
||||
.sizing(WidgetSizing::fixed(100))
|
||||
.tooltip_label("Scale Factor")
|
||||
.tooltip_description(scale_description)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.scale_factor))
|
||||
.unit("")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.increment_step(0.5)
|
||||
.tooltip_label("Scale Factor")
|
||||
.tooltip_description(scale_description)
|
||||
.disabled(self.file_type == FileType::Svg)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
||||
.sizing(WidgetSizing::default().min_width(200))
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
@@ -196,6 +196,10 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "contextMenuInformation")]
|
||||
context_menu_information: Option<ContextMenuInformation>,
|
||||
},
|
||||
UpdateClickTargets {
|
||||
#[serde(rename = "clickTargets")]
|
||||
click_targets: Option<FrontendClickTargets>,
|
||||
},
|
||||
UpdateGraphViewOverlay {
|
||||
open: bool,
|
||||
},
|
||||
|
||||
@@ -78,6 +78,7 @@ pub enum FileType {
|
||||
Tga,
|
||||
Ico,
|
||||
Svg,
|
||||
Pdf,
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
@@ -91,9 +92,15 @@ impl FileType {
|
||||
FileType::Tga => "tga",
|
||||
FileType::Ico => "ico",
|
||||
FileType::Svg => "svg",
|
||||
FileType::Pdf => "pdf",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file holds vector content rather than an image of the export's area.
|
||||
pub fn is_vector(self) -> bool {
|
||||
matches!(self, FileType::Svg | FileType::Pdf)
|
||||
}
|
||||
|
||||
pub fn file_filter(self) -> FileFilter {
|
||||
let name = match self {
|
||||
FileType::Png => "PNG Image",
|
||||
@@ -104,6 +111,7 @@ impl FileType {
|
||||
FileType::Tga => "TGA Image",
|
||||
FileType::Ico => "ICO Image",
|
||||
FileType::Svg => "SVG Image",
|
||||
FileType::Pdf => "PDF Document",
|
||||
};
|
||||
FileFilter {
|
||||
name: name.into(),
|
||||
@@ -129,7 +137,7 @@ impl FileType {
|
||||
FileType::Bmp => ImageFormat::Bmp,
|
||||
FileType::Tga => ImageFormat::Tga,
|
||||
FileType::Ico => ImageFormat::Ico,
|
||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||
FileType::Svg | FileType::Pdf => return Err(format!("{} cannot be exported from an image buffer", self.extension().to_uppercase())),
|
||||
};
|
||||
if self == FileType::Ico && (width > 256 || height > 256) {
|
||||
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
|
||||
@@ -228,6 +236,7 @@ mod tests {
|
||||
#[test]
|
||||
fn file_types_that_cannot_hold_the_image_say_so() {
|
||||
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Pdf.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
|
||||
|
||||
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
|
||||
|
||||
@@ -87,7 +87,9 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
|
||||
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
|
||||
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
|
||||
entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes),
|
||||
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets),
|
||||
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
|
||||
entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
|
||||
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
|
||||
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
|
||||
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
|
||||
|
||||
@@ -878,22 +878,6 @@ pub struct SliderMarker {
|
||||
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
|
||||
#[serde(rename = "betweenNeighbors")]
|
||||
between_neighbors: bool,
|
||||
/// How this marker and the next may pass each other.
|
||||
#[serde(rename = "overlapNext")]
|
||||
overlap_next: MarkerOverlap,
|
||||
}
|
||||
|
||||
/// How a slider marker and the next may pass each other, as split handles whose ranges may overlap.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MarkerOverlap {
|
||||
/// Neither may pass the other.
|
||||
#[default]
|
||||
Never,
|
||||
/// Each may pass the other but not the marker beyond it, so split handles' inner halves can overlap while the handles can't pass each other.
|
||||
NextOnly,
|
||||
/// The markers up to this one and those after it don't bound each other, so split handles can pass each other entirely.
|
||||
Freely,
|
||||
}
|
||||
|
||||
impl SliderMarker {
|
||||
@@ -906,7 +890,6 @@ impl SliderMarker {
|
||||
paired_with_next: false,
|
||||
dashed_to_next: false,
|
||||
between_neighbors: false,
|
||||
overlap_next: MarkerOverlap::Never,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -924,11 +907,6 @@ impl SliderMarker {
|
||||
self.dashed_to_next = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
||||
self.overlap_next = overlap;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
|
||||
@@ -1,262 +0,0 @@
|
||||
//! Layers clipped to a base through the editor's own graph, where the base's filters shape what clips to it but the shadows it casts don't.
|
||||
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::test_utils::gpu_executor;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::application_io::Texture;
|
||||
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
|
||||
use graphene_std::graphic::{IntoGraphicList, extend};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::math_nodes::{color_value, gradient_value};
|
||||
use graphene_std::raster_nodes::std_nodes::noise_pattern;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Base {
|
||||
VectorLayer,
|
||||
ImageLayer,
|
||||
/// A group holding a vector layer, with the effect on the group.
|
||||
Group,
|
||||
}
|
||||
|
||||
async fn add_effect(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, effect: ProtoNodeIdentifier) {
|
||||
let node_type = DefinitionIdentifier::ProtoNode(effect.clone());
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||
|
||||
if effect == blur::IDENTIFIER {
|
||||
let node_id = NodeGraphLayer::new(layer, &editor.active_document().network_interface)
|
||||
.upstream_node_id_from_protonode(effect)
|
||||
.expect("the layer has its blur");
|
||||
let value = Box::new(TaggedValue::Number(10.));
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: blur::RadiusInput::INDEX,
|
||||
value,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The root stack of a document with a blue base filling (50, 50) to (130, 130) and a larger red layer clipped to it, with `effect` on the base.
|
||||
async fn clipped_stack(base: Base, effect: ProtoNodeIdentifier) -> List<Graphic> {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
let red = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
|
||||
|
||||
match base {
|
||||
Base::ImageLayer => editor.create_raster_image(Image::new(80, 80, blue), Some((90., 90.))).await,
|
||||
Base::VectorLayer | Base::Group => {
|
||||
editor.select_primary_color(blue).await;
|
||||
editor.select_secondary_color(blue).await;
|
||||
editor.draw_rect(50., 50., 130., 130.).await;
|
||||
}
|
||||
}
|
||||
let base_layer = editor.get_selected_layer().await.expect("the base is selected");
|
||||
if !matches!(base, Base::Group) {
|
||||
add_effect(&mut editor, base_layer, effect.clone()).await;
|
||||
}
|
||||
|
||||
editor.select_tool(ToolType::Select).await;
|
||||
editor.select_primary_color(red).await;
|
||||
editor.select_secondary_color(red).await;
|
||||
editor.draw_rect(20., 20., 200., 200.).await;
|
||||
let clipped_layer = editor.get_selected_layer().await.expect("the clipped layer is selected");
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::FillColorSet {
|
||||
layer: clipped_layer,
|
||||
color: Some(red),
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(DocumentMessage::ClipLayer { id: clipped_layer.to_node() }).await;
|
||||
|
||||
// Grouped once the red is clipped, the group takes the base's place beneath it
|
||||
if let Base::Group = base {
|
||||
let nodes = vec![base_layer.to_node()];
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
|
||||
let group = editor.get_selected_layer().await.expect("the group is selected");
|
||||
add_effect(&mut editor, group, effect).await;
|
||||
}
|
||||
|
||||
// The stack is what the root's 'Extend' nodes put together: the base's layer extended by the clipped one
|
||||
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
||||
let mut news = instrumented.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime);
|
||||
let clipped = news.find(|new| new.element().had_clip_enabled()).expect("the clipped layer is extended onto the base");
|
||||
let mut bases = instrumented.grab_all_input::<extend::BaseInput, List<Graphic>>(&editor.runtime);
|
||||
let mut stack = bases.find(|base| base.len() == 1).expect("the base's layer is extended");
|
||||
stack.push(clipped);
|
||||
stack
|
||||
}
|
||||
|
||||
/// Checks in SVG and in Vello that the red clipped to the base shows past the base's edges if `blurred`, and that a shadow the base casts doesn't widen the clip.
|
||||
fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
|
||||
// The clip's def in SVG carries out the blur but not the shadow
|
||||
let mut render = SvgRender::new();
|
||||
graphic.render_svg(
|
||||
&mut render,
|
||||
&RenderParams {
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let body = render.svg.to_svg_string();
|
||||
let reference = body.rfind("url(#mask-").expect("the red is clipped");
|
||||
let id: String = body[reference + "url(#".len()..].chars().take_while(|&character| character != ')').collect();
|
||||
let defs = &render.svg_defs;
|
||||
let def_start = defs.find(&format!(r#"id="{id}""#)).expect("the clip has a def");
|
||||
let def_end = ["</mask>", "</clipPath>"]
|
||||
.iter()
|
||||
.filter_map(|closing| defs[def_start..].find(closing))
|
||||
.min()
|
||||
.expect("the clip's def is closed");
|
||||
let clip = &defs[def_start..def_start + def_end];
|
||||
assert_eq!(clip.contains("filter="), blurred, "{name}: the clip's def is {clip}");
|
||||
|
||||
// In Vello, the red past the base's edges shows where the blur reaches, but not where the shadow falls
|
||||
let size = UVec2::new(256, 256);
|
||||
let executor = gpu_executor();
|
||||
let texture = executor
|
||||
.render_vello(size, DAffine2::IDENTITY, &mut |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||||
.expect("the clip renders");
|
||||
let pixels = executor.read_texture_pixels(&texture).expect("the render reads back");
|
||||
let pixel = |x: u32, y: u32| -> [u8; 4] {
|
||||
let index = (y * size.x + x) as usize * 4;
|
||||
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
|
||||
};
|
||||
|
||||
let within = pixel(90, 90);
|
||||
assert!(within[0] >= 250 && within[2] <= 5 && within[3] == 255, "{name}: within the base, the red is {within:?}");
|
||||
assert_eq!(pixel(134, 90)[0] > 0, blurred, "{name}: past the base's right edge, the red is {:?}", pixel(134, 90));
|
||||
assert_eq!(pixel(93, 135)[0] > 0, blurred, "{name}: past the base's bottom edge, the red is {:?}", pixel(93, 135));
|
||||
assert!(blurred || pixel(93, 135)[3] > 0, "{name}: the base's shadow shows where it falls");
|
||||
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
|
||||
}
|
||||
|
||||
/// Endless content a layer can hold, which fills the whole canvas unless something clips it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Endless {
|
||||
Color,
|
||||
Gradient,
|
||||
NoisePattern,
|
||||
}
|
||||
|
||||
/// A document viewed in the `render_mode` with a blue rectangle filling (50, 50) to (130, 130).
|
||||
async fn document_with_a_rectangle(render_mode: RenderMode) -> EditorTestUtils {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
|
||||
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
editor.select_primary_color(blue).await;
|
||||
editor.select_secondary_color(blue).await;
|
||||
editor.draw_rect(50., 50., 130., 130.).await;
|
||||
|
||||
editor
|
||||
}
|
||||
|
||||
/// Adds a new layer of `endless` content above the selected layer, clipped to it as by an Alt-click between them.
|
||||
async fn add_clipped_endless_layer(editor: &mut EditorTestUtils, endless: Endless) {
|
||||
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
|
||||
let layer = editor.get_selected_layer().await.expect("the new layer is selected");
|
||||
let node = match endless {
|
||||
Endless::Color => color_value::IDENTIFIER,
|
||||
Endless::Gradient => gradient_value::IDENTIFIER,
|
||||
Endless::NoisePattern => noise_pattern::IDENTIFIER,
|
||||
};
|
||||
let node_type = DefinitionIdentifier::ProtoNode(node);
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||
editor.handle_message(DocumentMessage::ClipLayer { id: layer.to_node() }).await;
|
||||
}
|
||||
|
||||
/// Evaluates the document for a viewport of `size` as the app does, returning what the frontend is sent and the frame the runtime presents.
|
||||
async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<FrontendMessage>, Option<Texture>) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.expect("a document is open");
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).expect("the active document exists");
|
||||
let submitted = executor
|
||||
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.expect("the evaluation is submitted");
|
||||
|
||||
let mut messages = editor.dispatch(submitted);
|
||||
editor.runtime.update();
|
||||
let frame = editor.runtime.run().await;
|
||||
messages.extend(editor.dispatch(Message::Wake));
|
||||
|
||||
(messages, frame)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn endless_layers_clip_to_the_shape_beneath_them() {
|
||||
let size = UVec2::new(256, 256);
|
||||
|
||||
let frame_pixels = async |editor: &mut EditorTestUtils| {
|
||||
let (_, frame) = evaluate_viewport(editor, size).await;
|
||||
let frame = frame.expect("the viewport presents a frame");
|
||||
gpu_executor().read_texture_pixels(&frame).expect("the frame reads back")
|
||||
};
|
||||
let pixel = |pixels: &[u8], x: u32, y: u32| {
|
||||
let index = (y * size.x + x) as usize * 4;
|
||||
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
|
||||
};
|
||||
|
||||
for endless in [Endless::Color, Endless::Gradient, Endless::NoisePattern] {
|
||||
// In the viewport's Vello render, the endless content covers the rectangle but leaves the canvas past it as the rectangle alone left it
|
||||
let mut editor = document_with_a_rectangle(RenderMode::Normal).await;
|
||||
let rectangle_alone = frame_pixels(&mut editor).await;
|
||||
add_clipped_endless_layer(&mut editor, endless).await;
|
||||
let clipped = frame_pixels(&mut editor).await;
|
||||
|
||||
assert_ne!(pixel(&clipped, 90, 90), pixel(&rectangle_alone, 90, 90), "{endless:?}: the content shows within the rectangle");
|
||||
for (x, y) in [(20, 20), (200, 90), (90, 200), (230, 230)] {
|
||||
assert_eq!(
|
||||
pixel(&clipped, x, y),
|
||||
pixel(&rectangle_alone, x, y),
|
||||
"{endless:?}: the content is clipped away at ({x}, {y}), past the rectangle"
|
||||
);
|
||||
}
|
||||
|
||||
// In SVG Preview, the endless content is drawn only within the rectangle's mask
|
||||
let mut editor = document_with_a_rectangle(RenderMode::SvgPreview).await;
|
||||
add_clipped_endless_layer(&mut editor, endless).await;
|
||||
let (messages, _) = evaluate_viewport(&mut editor, size).await;
|
||||
let svg = messages
|
||||
.into_iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the viewport's artwork is sent as SVG");
|
||||
|
||||
let (unmasked, masked) = svg.split_once(r#"mask="url(#mask-"#).unwrap_or_else(|| panic!("{endless:?}: the content is masked: {svg}"));
|
||||
let draws_endless_content = |markup: &str| ["<polyline", "<foreignObject"].iter().any(|tag| markup.contains(tag));
|
||||
assert!(
|
||||
!draws_endless_content(unmasked) && draws_endless_content(masked),
|
||||
"{endless:?}: the content is drawn within the mask: {svg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
|
||||
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
|
||||
for base in [Base::VectorLayer, Base::ImageLayer, Base::Group] {
|
||||
let stack = clipped_stack(base, effect.clone()).await;
|
||||
assert_clip(&format!("{base:?} with {effect_name}"), &Graphic::GraphicList(stack.clone()), blurred);
|
||||
|
||||
// Flattened into one list of vectors, the base clips its sibling by the same rule
|
||||
if let Base::VectorLayer = base {
|
||||
let flattened: List<Vector> = stack.into_flattened_list();
|
||||
assert_clip(&format!("flattened vectors with {effect_name}"), &Graphic::VectorList(flattened), blurred);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use crate::node_graph_executor::InspectedContext;
|
||||
use glam::{Affine2, DAffine2, Vec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::WarpStyle;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
@@ -31,15 +30,10 @@ use graphene_std::vector::misc::{
|
||||
WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
|
||||
StrokeJoin,
|
||||
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, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource,
|
||||
GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||
};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowTechnique, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::ops::Range;
|
||||
@@ -409,6 +403,7 @@ macro_rules! inspectable_types {
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<BlendMode>,
|
||||
List<GradientForm>,
|
||||
List<GradientSpread>,
|
||||
List<GradientSpace>,
|
||||
List<GradientHueDirection>,
|
||||
@@ -469,7 +464,6 @@ macro_rules! inspectable_types {
|
||||
Item<DAffine2>,
|
||||
Item<BlendMode>,
|
||||
Item<GradientForm>,
|
||||
Item<GradientModel>,
|
||||
Item<GradientSpread>,
|
||||
Item<GradientSpace>,
|
||||
Item<GradientHueDirection>,
|
||||
@@ -1271,27 +1265,14 @@ macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
Cover,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
BevelStyle,
|
||||
RadialBlurMethod,
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
GradientInterpolation,
|
||||
GlowTechnique,
|
||||
NoiseDistribution,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
@@ -1465,29 +1446,16 @@ macro_rules! known_item_types {
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
RadialBlurMethod,
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
GradientInterpolation,
|
||||
GlowTechnique,
|
||||
NoiseDistribution,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate,
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use glam::{DAffine2, IVec2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::list::Item;
|
||||
@@ -334,7 +334,6 @@ pub enum DocumentMessage {
|
||||
},
|
||||
UpdateEffectsReach {
|
||||
effects_reach: HashMap<NodeId, f64>,
|
||||
effects_frames: HashMap<NodeId, [DVec2; 2]>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
|
||||
@@ -304,15 +304,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let visibility_settings = self.overlays_visibility_settings;
|
||||
|
||||
// Send the overlays message to the overlays message handler
|
||||
self.overlays_message_handler.process_message(
|
||||
message,
|
||||
responses,
|
||||
OverlaysMessageContext {
|
||||
visibility_settings,
|
||||
viewport,
|
||||
graph_open: self.graph_view_overlay_open,
|
||||
},
|
||||
);
|
||||
self.overlays_message_handler
|
||||
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
|
||||
}
|
||||
DocumentMessage::Inspector(message) => {
|
||||
let context = InspectorMessageContext {
|
||||
@@ -1952,20 +1945,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||
}
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach, effects_frames } => {
|
||||
let is_document_layer = |node_id: &NodeId| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]);
|
||||
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
||||
let layer_effects_reach = effects_reach
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| is_document_layer(node_id))
|
||||
.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();
|
||||
let layer_effects_frames = effects_frames
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| is_document_layer(node_id))
|
||||
.map(|(node_id, frames)| (LayerNodeIdentifier::new(node_id, &self.network_interface), frames))
|
||||
.collect();
|
||||
self.network_interface.update_effects_reach(layer_effects_reach, layer_effects_frames);
|
||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
|
||||
@@ -2459,6 +2445,20 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
/// The document's artboards with their names, called "Artboard" while left unnamed.
|
||||
pub fn artboard_names(&self) -> Vec<(LayerNodeIdentifier, String)> {
|
||||
(self.metadata().all_layers())
|
||||
.filter(|&layer| self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| {
|
||||
let name = (self.network_interface.node_metadata(&layer.to_node(), &[]))
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
|
||||
&self.breadcrumb_network_path
|
||||
}
|
||||
@@ -2694,6 +2694,7 @@ impl DocumentMessageHandler {
|
||||
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
|
||||
for path in self.network_interface.paths_reaching(&reconciled.networks) {
|
||||
self.network_interface.unload_import_export_ports(&path);
|
||||
self.network_interface.unload_all_nodes_bounding_box(&path);
|
||||
self.network_interface.unload_outward_wires(&path);
|
||||
}
|
||||
self.network_interface.load_structure();
|
||||
@@ -4138,7 +4139,7 @@ impl DocumentMessageHandler {
|
||||
})
|
||||
.unwrap_or((None, None, None));
|
||||
|
||||
let blend_mode_menu_entries = BlendMode::list()
|
||||
let blend_mode_menu_entries = BlendMode::list_svg_subset()
|
||||
.iter()
|
||||
.map(|modes| {
|
||||
modes
|
||||
@@ -4155,7 +4156,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
let widgets = vec![
|
||||
DropdownInput::new(blend_mode_menu_entries)
|
||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32))
|
||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32))
|
||||
.disabled(disabled)
|
||||
.draw_icon(false)
|
||||
.sizing(WidgetSizing::default().grow(false))
|
||||
|
||||
@@ -26,8 +26,7 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
#[serde(skip)]
|
||||
gradient: Gradient,
|
||||
/// The form whose curvatures the Fill takes, or `None` to keep its own.
|
||||
gradient_form: Option<GradientForm>,
|
||||
gradient_form: GradientForm,
|
||||
gradient_settings: GradientSettings,
|
||||
/// `None` lets the gradient cover the layer's bounding box, following it as the layer changes.
|
||||
transform: Option<DAffine2>,
|
||||
@@ -57,11 +56,6 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
gradient_form: GradientForm,
|
||||
},
|
||||
GradientCurvatureSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
/// The start and end curvatures.
|
||||
curvatures: [f64; 2],
|
||||
},
|
||||
GradientSpreadSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
gradient_spread: GradientSpread,
|
||||
|
||||
+5
-7
@@ -86,11 +86,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
modify_inputs.gradient_form_set(gradient_form);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientCurvatureSet { layer, curvatures } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_curvature_set(curvatures);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientSpreadSet { layer, gradient_spread } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_spread_set(gradient_spread);
|
||||
@@ -812,6 +807,9 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
||||
// Set positions for all imported descendants in a single O(n) pass
|
||||
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
|
||||
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
|
||||
|
||||
// Invalidate caches once after all positions are set
|
||||
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
|
||||
}
|
||||
usvg::Node::Path(path) => {
|
||||
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
|
||||
@@ -1039,7 +1037,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
||||
space: gradient_info.spaces.get(linear.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
||||
..Default::default()
|
||||
};
|
||||
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
|
||||
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
|
||||
}
|
||||
usvg::Paint::RadialGradient(radial) => {
|
||||
let gradient_transform = usvg_transform(radial.transform());
|
||||
@@ -1067,7 +1065,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
||||
space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
||||
..Default::default()
|
||||
};
|
||||
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
|
||||
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
|
||||
}
|
||||
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
|
||||
};
|
||||
|
||||
@@ -6,8 +6,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{
|
||||
ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_fill_node_id_with_direct_fill_input, get_upstream_gradient_value_node_id, gradient_chain_target_input,
|
||||
gradient_curvature_values, replaceable_paint_chain,
|
||||
ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
|
||||
};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
@@ -207,9 +206,6 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||
]);
|
||||
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
|
||||
.expect("Text to Vector node does not exist")
|
||||
.default_node_template();
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
@@ -217,17 +213,13 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.expect("Fill node does not exist")
|
||||
.default_node_template();
|
||||
|
||||
// Build the chain `Text -> Text to Vector -> Transform -> Fill -> layer`
|
||||
// Build the chain `Text -> Transform -> Fill -> layer`, keeping the text native so backends lay out and draw its glyphs
|
||||
let text_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_id, text, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
|
||||
|
||||
self.responses.add(DocumentMessage::Resource(ResourceMessage::AddFont { resource_id: font_resource_id, font }));
|
||||
|
||||
let text_to_vector_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_to_vector_id, text_to_vector, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_to_vector_id, layer, &[], self.import);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
|
||||
@@ -451,8 +443,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints the layer's Fill with `gradient`, giving its curvatures those of `gradient_form` if that's given, unless the graph feeds them.
|
||||
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: Option<GradientForm>, settings: GradientSettings, transform: Option<DAffine2>) {
|
||||
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: Option<DAffine2>) {
|
||||
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
|
||||
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
|
||||
return;
|
||||
@@ -492,31 +483,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// Only a chosen form sets the curvatures, leaving any the graph feeds or that already make it
|
||||
if let Some(gradient_form) = gradient_form {
|
||||
self.write_fill_curvatures(fill_node_id, gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form));
|
||||
}
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientFormInput),
|
||||
NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
|
||||
false,
|
||||
);
|
||||
|
||||
if existing_fill_node_id.is_none() {
|
||||
self.restore_default_stroke_order();
|
||||
}
|
||||
}
|
||||
|
||||
/// Write both curvatures to a Fill node's hidden curvature inputs unless the graph feeds them or its current ones are `already_written`, for the caller to then run the graph.
|
||||
fn write_fill_curvatures(&mut self, fill_node_id: NodeId, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) {
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let current = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
|
||||
if current.is_none_or(already_written) {
|
||||
return;
|
||||
}
|
||||
|
||||
let [start, end] = curvatures;
|
||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
|
||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), true);
|
||||
}
|
||||
|
||||
/// A freshly created Fill node lands at the chain start, downstream of any Stroke node, where it would
|
||||
/// paint over the stroke. This hops the stroke back downstream so it keeps painting above by default.
|
||||
fn restore_default_stroke_order(&mut self) {
|
||||
@@ -777,47 +754,20 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// 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`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched.
|
||||
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||
/// from the default (`Linear`).
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
self.write_gradient_curvatures(gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form));
|
||||
}
|
||||
|
||||
/// Write both curvatures to the layer's gradient: a Fill node holding it, or else the last 'Gradient Curvature' node in its chain, inserting
|
||||
/// one only when they differ from the default form's (`Linear`). Curvatures fed from the graph (procedural authorship) are left untouched.
|
||||
pub fn gradient_curvature_set(&mut self, curvatures: [f64; 2]) {
|
||||
if let Some(output_layer) = self.get_output_layer()
|
||||
&& let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(output_layer, self.network_interface)
|
||||
{
|
||||
self.write_fill_curvatures(fill_node_id, curvatures, |current| current == curvatures);
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
return;
|
||||
}
|
||||
|
||||
self.write_gradient_curvatures(curvatures, |current| current == curvatures);
|
||||
}
|
||||
|
||||
/// Write these curvatures to the last 'Gradient Curvature' node in the chain unless its current ones are `already_written`.
|
||||
fn write_gradient_curvatures(&mut self, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let create_if_nonexistent = curvatures != GradientForm::default().curvatures();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
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 {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return };
|
||||
let Some(current) = gradient_curvature_values(node) else { return };
|
||||
if already_written(current) {
|
||||
return;
|
||||
}
|
||||
|
||||
let [start, end] = curvatures;
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
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);
|
||||
}
|
||||
|
||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#[cfg(test)]
|
||||
mod clipping_tests;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod document_diff;
|
||||
mod document_history;
|
||||
mod document_message;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::application::Environment;
|
||||
use crate::consts::{
|
||||
DOUBLE_CLICK_ALLOWED_TRAVEL, VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX,
|
||||
VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
|
||||
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
};
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
|
||||
use crate::messages::input_mapper::utility_types::pointer::{MouseKeys, ViewportPosition};
|
||||
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
|
||||
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
|
||||
use crate::messages::portfolio::document::utility_types::misc::PTZ;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
@@ -34,8 +34,6 @@ pub struct NavigationMessageHandler {
|
||||
abortable_pan_start: Option<f64>,
|
||||
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
|
||||
artwork_behind_graph: bool,
|
||||
/// Where a middle press began panning the open node graph, kept until the pointer travels too far for its release to still be a click.
|
||||
graph_middle_click_start: Option<ViewportPosition>,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -101,10 +99,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
return;
|
||||
};
|
||||
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
|
||||
|
||||
// Released before traveling far, a middle press that pans the open graph is instead a click on the node under it
|
||||
let middle_press_in_graph = graph_view_overlay_open && ipp.mouse.mouse_keys == MouseKeys::MIDDLE;
|
||||
self.graph_middle_click_start = middle_press_in_graph.then_some(ipp.mouse.position);
|
||||
}
|
||||
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
@@ -347,13 +341,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
responses.add(ToolMessage::UpdateCursor);
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
responses.add(NavigateToolMessage::End);
|
||||
|
||||
// Not a pan after all, but a middle click in the graph
|
||||
let middle_click_start = self.graph_middle_click_start.take();
|
||||
let middle_released = !ipp.mouse.mouse_keys.contains(MouseKeys::MIDDLE);
|
||||
if !abort_transform && middle_released && middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL) {
|
||||
responses.add(NodeGraphMessage::MiddleClick);
|
||||
}
|
||||
}
|
||||
NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
|
||||
self.finish_operation_with_click = false;
|
||||
@@ -430,10 +417,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
}
|
||||
NavigationMessage::PointerMove { snap } => {
|
||||
if self.graph_middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) > DOUBLE_CLICK_ALLOWED_TRAVEL) {
|
||||
self.graph_middle_click_start = None;
|
||||
}
|
||||
|
||||
match self.navigation_operation {
|
||||
NavigationOperation::None => {}
|
||||
NavigationOperation::Pan { .. } => {
|
||||
|
||||
@@ -139,6 +139,18 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
|
||||
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
||||
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let custom = vec![
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Custom Node",
|
||||
version: 1,
|
||||
category: "Routing",
|
||||
icon: Some("NodeCustomNode"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
version: 1,
|
||||
@@ -676,7 +688,6 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
|
||||
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
|
||||
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
|
||||
map.insert("blend_if_inspector".to_string(), Box::new(node_inspector::blend_if_inspector));
|
||||
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
|
||||
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
|
||||
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
|
||||
@@ -686,13 +697,10 @@ 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));
|
||||
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
|
||||
map.insert("sharpen_inspector".to_string(), Box::new(node_inspector::sharpen_inspector));
|
||||
map.insert("displace_inspector".to_string(), Box::new(node_inspector::displace_inspector));
|
||||
map
|
||||
}
|
||||
|
||||
@@ -701,15 +709,6 @@ type InputInspector = HashMap<String, Box<dyn Fn(NodeId, usize, &mut NodeInspect
|
||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector);
|
||||
|
||||
/// The metadata of the proto node's field at `index`, cloned so the lock is released before the row is built, which locks the node metadata again.
|
||||
fn proto_node_field(node_id: NodeId, index: usize, context: &mut NodeInspectorContext) -> Option<registry::FieldMetadata> {
|
||||
context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().ok()?.get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
}
|
||||
|
||||
/// Defines the logic for inputs to display a custom Inspector widget.
|
||||
fn static_input_inspector() -> InputInspector {
|
||||
let mut map: InputInspector = HashMap::new();
|
||||
@@ -873,82 +872,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// A slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them
|
||||
"wrapping_slider".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let field = proto_node_field(node_id, index, context);
|
||||
|
||||
let mut number_input = NumberInput::default().mode_increment();
|
||||
let mut period = None;
|
||||
if let Some(field) = field {
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
if let Some(display_decimal_places) = field.number_display_decimal_places {
|
||||
number_input = number_input.display_decimal_places(display_decimal_places);
|
||||
}
|
||||
if let Some(number_step) = field.number_step {
|
||||
number_input = number_input.step(number_step);
|
||||
}
|
||||
period = field.number_soft_min.zip(field.number_soft_max);
|
||||
}
|
||||
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
let row = match period {
|
||||
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
|
||||
let default = node_inspector::definition_default_number(¶meter_widgets_info);
|
||||
node_inspector::wrapping_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
|
||||
}
|
||||
_ => {
|
||||
log::error!("A wrapping slider needs finite soft bounds at both ends");
|
||||
node_inspector::number_widget(parameter_widgets_info, number_input)
|
||||
}
|
||||
};
|
||||
Ok(vec![LayoutGroup::row(row)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// A slider across the soft bounds (or the hard ones where a soft one is absent), beside a number input that types past them up to the hard bounds
|
||||
"slider".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let field = proto_node_field(node_id, index, context);
|
||||
|
||||
let mut number_input = NumberInput::default().mode_increment();
|
||||
let mut extent = None;
|
||||
if let Some(field) = field {
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
if let Some(display_decimal_places) = field.number_display_decimal_places {
|
||||
number_input = number_input.display_decimal_places(display_decimal_places);
|
||||
}
|
||||
if let Some(number_step) = field.number_step {
|
||||
number_input = number_input.step(number_step);
|
||||
}
|
||||
if let Some(min) = field.number_hard_min {
|
||||
number_input = number_input.min(min);
|
||||
}
|
||||
if let Some(max) = field.number_hard_max {
|
||||
number_input = number_input.max(max);
|
||||
}
|
||||
extent = field.number_soft_min.or(field.number_hard_min).zip(field.number_soft_max.or(field.number_hard_max));
|
||||
}
|
||||
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
let row = match extent {
|
||||
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
|
||||
let default = node_inspector::definition_default_number(¶meter_widgets_info);
|
||||
node_inspector::slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
|
||||
}
|
||||
_ => {
|
||||
log::error!("A slider needs finite bounds at both ends");
|
||||
node_inspector::number_widget(parameter_widgets_info, number_input)
|
||||
}
|
||||
};
|
||||
Ok(vec![LayoutGroup::row(row)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
|
||||
"type_choice".to_string(),
|
||||
@@ -1107,7 +1030,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"noise_inspector_fractal_weighted_strength".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||
let fractal_weighted_strength = node_inspector::slider_widget(
|
||||
let fractal_weighted_strength = node_inspector::range_slider_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
NumberInput::default()
|
||||
.min(0.)
|
||||
|
||||
@@ -45,11 +45,6 @@ pub enum NodeGraphMessage {
|
||||
xy: Option<(i32, i32)>,
|
||||
add_transaction: bool,
|
||||
},
|
||||
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
|
||||
CreateEmptySubgraph {
|
||||
node_id: Option<NodeId>,
|
||||
xy: Option<(i32, i32)>,
|
||||
},
|
||||
CreateWire {
|
||||
output_connector: OutputConnector,
|
||||
input_connector: InputConnector,
|
||||
@@ -170,8 +165,6 @@ pub enum NodeGraphMessage {
|
||||
PointerOutsideViewport {
|
||||
shift: Key,
|
||||
},
|
||||
/// Sent when the middle button is released where it was pressed in the graph, rather than having panned it.
|
||||
MiddleClick,
|
||||
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
|
||||
WireHoverTick,
|
||||
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
|
||||
@@ -209,6 +202,8 @@ pub enum NodeGraphMessage {
|
||||
SelectedNodesSet {
|
||||
nodes: Vec<NodeId>,
|
||||
},
|
||||
SendClickTargets,
|
||||
EndSendClickTargets,
|
||||
UnloadWires,
|
||||
SendWires,
|
||||
UpdateVisibleNodes,
|
||||
@@ -388,7 +383,6 @@ impl NodeGraphMessage {
|
||||
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
||||
Self::AddNodes { .. }
|
||||
| Self::CreateNodeFromContextMenu { .. }
|
||||
| Self::CreateEmptySubgraph { .. }
|
||||
| Self::CreateWire { .. }
|
||||
| Self::CreateWires { .. }
|
||||
| Self::ConnectUpstreamOutputToInput { .. }
|
||||
@@ -439,7 +433,6 @@ impl NodeGraphMessage {
|
||||
| Self::PointerMove { .. }
|
||||
| Self::PointerUp
|
||||
| Self::PointerOutsideViewport { .. }
|
||||
| Self::MiddleClick
|
||||
| Self::WireHoverTick
|
||||
| Self::SendGlide
|
||||
| Self::GlideTick
|
||||
@@ -449,6 +442,8 @@ impl NodeGraphMessage {
|
||||
| Self::SelectedNodesAdd { .. }
|
||||
| Self::SelectedNodesRemove { .. }
|
||||
| Self::SelectedNodesSet { .. }
|
||||
| Self::SendClickTargets
|
||||
| Self::EndSendClickTargets
|
||||
| Self::UnloadWires
|
||||
| Self::SendWires
|
||||
| Self::UpdateVisibleNodes
|
||||
|
||||
@@ -5,14 +5,13 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
|
||||
TransactionStatus,
|
||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||
@@ -24,12 +23,14 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e
|
||||
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
||||
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
||||
use crate::messages::viewport::Position;
|
||||
use glam::{DVec2, IVec2};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graphene_std::math::math_ext::QuadExt;
|
||||
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
|
||||
use graphene_std::*;
|
||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||
use renderer::Quad;
|
||||
|
||||
#[derive(Debug, ExtractField)]
|
||||
pub struct NodeGraphMessageContext<'a> {
|
||||
@@ -421,23 +422,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
});
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
|
||||
let node_id = node_id.unwrap_or_else(NodeId::new);
|
||||
let (x, y) = xy.unwrap_or_else(|| {
|
||||
network_interface
|
||||
.node_graph_ptz(breadcrumb_network_path)
|
||||
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id,
|
||||
node_template: Box::new(NodeTemplate::empty_subgraph()),
|
||||
});
|
||||
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
||||
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
||||
log::error!("Failed to find upstream node for downstream_input");
|
||||
@@ -785,19 +769,24 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
}
|
||||
|
||||
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
|
||||
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
|
||||
let encapsulating_node_id = NodeId::new();
|
||||
let mut subgraph_template = NodeTemplate::empty_subgraph();
|
||||
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
|
||||
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
||||
log::error!("Could not get center of selected_nodes");
|
||||
return;
|
||||
};
|
||||
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
||||
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id: encapsulating_node_id,
|
||||
node_template: Box::new(subgraph_template),
|
||||
node_template: Box::new(default_node_template),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: encapsulating_node_id,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
alias: "Untitled Node".to_string(),
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
||||
@@ -1752,20 +1741,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.auto_panning.stop(&messages, responses);
|
||||
}
|
||||
}
|
||||
// Middle-clicking a node toggles its visibility
|
||||
NodeGraphMessage::MiddleClick => {
|
||||
if !graph_view_overlay_open || network_interface.is_read_only(breadcrumb_network_path) {
|
||||
return;
|
||||
}
|
||||
let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::ToggleVisibility {
|
||||
node_id,
|
||||
network_path: breadcrumb_network_path.to_vec(),
|
||||
});
|
||||
}
|
||||
NodeGraphMessage::WireHoverTick => {
|
||||
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
|
||||
}
|
||||
@@ -2037,6 +2012,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
selected_nodes.set_selected_nodes(nodes);
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
NodeGraphMessage::SendClickTargets => responses.add(FrontendMessage::UpdateClickTargets {
|
||||
click_targets: Some(network_interface.collect_frontend_click_targets(breadcrumb_network_path)),
|
||||
}),
|
||||
NodeGraphMessage::EndSendClickTargets => responses.add(FrontendMessage::UpdateClickTargets { click_targets: None }),
|
||||
NodeGraphMessage::UnloadWires => {
|
||||
self.frontend_wires.clear();
|
||||
responses.add(FrontendMessage::ClearAllNodeGraphWires);
|
||||
@@ -2551,13 +2530,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
HashSet::new()
|
||||
};
|
||||
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
|
||||
let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)];
|
||||
for node_id in all_nodes {
|
||||
let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else {
|
||||
log::error!("Could not get the body of node {node_id}");
|
||||
let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else {
|
||||
log::error!("Could not get transient metadata for node {node_id}");
|
||||
continue;
|
||||
};
|
||||
if body.overlaps(selection_min, selection_max) {
|
||||
let quad = Quad::from_box([box_selection_start, box_selection_end_graph]);
|
||||
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
|
||||
if alt {
|
||||
nodes.remove(&node_id);
|
||||
} else {
|
||||
@@ -3219,6 +3198,11 @@ impl NodeGraphMessageHandler {
|
||||
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
|
||||
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp);
|
||||
|
||||
// Only development builds draw the click targets, so users don't come across the overlay by accident
|
||||
if cfg!(debug_assertions) {
|
||||
common.extend(actions!(NodeGraphMessageDiscriminant; SendClickTargets, EndSendClickTargets));
|
||||
}
|
||||
|
||||
if self.has_selection {
|
||||
common.extend(actions!(NodeGraphMessageDiscriminant;
|
||||
Copy,
|
||||
@@ -3442,13 +3426,6 @@ impl NodeGraphMessageHandler {
|
||||
})
|
||||
.disabled(read_only)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextButton::new("New Custom Node")
|
||||
.tooltip_label("New Custom Node")
|
||||
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
|
||||
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
|
||||
.disabled(read_only)
|
||||
.widget_instance(),
|
||||
//
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
//
|
||||
|
||||
@@ -20,7 +20,6 @@ use graph_craft::application_io::resource::{DataSource, Resource, ResourceId};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graph_craft::{Type, concrete, item};
|
||||
use graphene_std::WarpStyle;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::{
|
||||
@@ -37,12 +36,11 @@ use graphene_std::vector::misc::{
|
||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign,
|
||||
StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use graphene_std::{Artboard, GlowTechnique, Graphic, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -254,23 +252,6 @@ pub(crate) struct ParameterOptions {
|
||||
pub step: Option<f64>,
|
||||
}
|
||||
|
||||
impl From<&graphene_std::registry::FieldMetadata> for ParameterOptions {
|
||||
fn from(field: &graphene_std::registry::FieldMetadata) -> Self {
|
||||
Self {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct SliderRange {
|
||||
@@ -287,18 +268,10 @@ impl SliderRange {
|
||||
fn value(self, position: f64) -> f64 {
|
||||
(self.min + position * (self.max - self.min)).clamp(self.min, self.max)
|
||||
}
|
||||
|
||||
/// The `value` moved into the bounds by whole periods of their width, for a periodic number like an angle.
|
||||
fn wrapped(self, value: f64) -> f64 {
|
||||
if (self.min..=self.max).contains(&value) {
|
||||
return value;
|
||||
}
|
||||
self.min + (value - self.min).rem_euclid(self.max - self.min)
|
||||
}
|
||||
}
|
||||
|
||||
/// The number a parameter's definition gives it by default, which a slider's double-click restores.
|
||||
pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
|
||||
fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
|
||||
let identifier = parameter_widgets_info
|
||||
.network_interface
|
||||
.reference(¶meter_widgets_info.node_id, parameter_widgets_info.selection_network_path)?;
|
||||
@@ -361,7 +334,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
match (number_input.min, number_input.max) {
|
||||
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
|
||||
let default = definition_default_number(&default_info);
|
||||
slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
|
||||
range_slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
|
||||
}
|
||||
_ => number_widget(default_info, number_input).into(),
|
||||
}
|
||||
@@ -412,10 +385,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &mut extra_widgets),
|
||||
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
|
||||
// ============
|
||||
@@ -434,7 +406,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
// AUTO-GENERATED ENUM TYPES
|
||||
// =========================
|
||||
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientModel>(x) => enum_choice::<GradientModel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
|
||||
@@ -471,18 +442,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MinimumMaximumMode>(x) => enum_choice::<MinimumMaximumMode>().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::<RadialBlurMethod>(x) => enum_choice::<RadialBlurMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<WarpStyle>(x) => enum_choice::<WarpStyle>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<WaveType>(x) => enum_choice::<WaveType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DisplaceMode>(x) => enum_choice::<DisplaceMode>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BlendIfChannel>(x) => enum_choice::<BlendIfChannel>().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(),
|
||||
@@ -813,10 +772,8 @@ pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
||||
last.clone()
|
||||
}
|
||||
|
||||
/// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size.
|
||||
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||
let size_unit = size_unit.unwrap_or("x");
|
||||
|
||||
let mut location_widgets = start_widgets(¶meter_widgets_info);
|
||||
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
@@ -883,7 +840,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
||||
scale_widgets.extend_from_slice(&[
|
||||
NumberInput::new(Some(scale.x))
|
||||
.label("W")
|
||||
.unit(size_unit)
|
||||
.unit("x")
|
||||
.on_update(update_value_at_index(
|
||||
move |w: &NumberInput| {
|
||||
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix;
|
||||
@@ -897,7 +854,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(scale.y))
|
||||
.label("H")
|
||||
.unit(size_unit)
|
||||
.unit("x")
|
||||
.on_update(update_value_at_index(
|
||||
move |h: &NumberInput| {
|
||||
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix;
|
||||
@@ -1241,7 +1198,7 @@ pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_in
|
||||
|
||||
let number_props = number_props.disabled(enabled == Some(false));
|
||||
let mut widgets = match slider {
|
||||
Some(slider) => slider_widget(parameter_widgets_info, number_props, slider),
|
||||
Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider),
|
||||
None => number_widget(parameter_widgets_info, number_props),
|
||||
};
|
||||
|
||||
@@ -1355,7 +1312,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
||||
return LayoutGroup::row(vec![]);
|
||||
};
|
||||
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
|
||||
let entries = BlendMode::list()
|
||||
let entries = BlendMode::list_svg_subset()
|
||||
.iter()
|
||||
.map(|category| {
|
||||
category
|
||||
@@ -1372,7 +1329,9 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
||||
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(),
|
||||
DropdownInput::new(entries)
|
||||
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
|
||||
@@ -1933,8 +1892,6 @@ pub(crate) fn levels_inspector(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
enum MarkerScale {
|
||||
/// A 0..100 percentage, placed linearly.
|
||||
Percent,
|
||||
/// A 0..100 percentage of a channel's 256 levels, placed linearly and shown to a tenth, which tells neighboring levels apart.
|
||||
LevelPercent,
|
||||
/// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center.
|
||||
Gamma,
|
||||
/// A hue of 0..360 degrees, placed linearly on a track that wraps around.
|
||||
@@ -1944,7 +1901,7 @@ enum MarkerScale {
|
||||
impl MarkerScale {
|
||||
fn position(self, value: f64) -> f64 {
|
||||
match self {
|
||||
Self::Percent | Self::LevelPercent => value / 100.,
|
||||
Self::Percent => value / 100.,
|
||||
Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(),
|
||||
Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(),
|
||||
Self::Degrees => {
|
||||
@@ -1958,7 +1915,7 @@ impl MarkerScale {
|
||||
|
||||
fn value(self, position: f64) -> f64 {
|
||||
match self {
|
||||
Self::Percent | Self::LevelPercent => (position * 100.).clamp(0., 100.),
|
||||
Self::Percent => (position * 100.).clamp(0., 100.),
|
||||
Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99),
|
||||
Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.),
|
||||
Self::Degrees => (position * 360.).clamp(0., 360.),
|
||||
@@ -1968,7 +1925,6 @@ impl MarkerScale {
|
||||
fn number_input(self) -> NumberInput {
|
||||
match self {
|
||||
Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0),
|
||||
Self::LevelPercent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(1),
|
||||
Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2),
|
||||
Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0),
|
||||
}
|
||||
@@ -1993,8 +1949,6 @@ struct SliderSectionParam {
|
||||
dash_to_next: bool,
|
||||
/// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move.
|
||||
between_neighbors: bool,
|
||||
/// How the marker and the next parameter's marker may pass each other (see [`overlap_bounds`]).
|
||||
overlap_next: MarkerOverlap,
|
||||
}
|
||||
|
||||
impl SliderSectionParam {
|
||||
@@ -2007,7 +1961,6 @@ impl SliderSectionParam {
|
||||
pair_with_next: false,
|
||||
dash_to_next: false,
|
||||
between_neighbors: false,
|
||||
overlap_next: MarkerOverlap::Never,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2025,52 +1978,11 @@ impl SliderSectionParam {
|
||||
self.dash_to_next = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
||||
self.overlap_next = overlap;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The span the marker at `index` may move within where markers may overlap their next (see [`MarkerOverlap`]).
|
||||
fn overlap_bounds(positions: &[f64], overlaps_next: &[MarkerOverlap], index: usize) -> (f64, f64) {
|
||||
let overlap = |i: Option<usize>| i.and_then(|i| overlaps_next.get(i)).copied().unwrap_or_default();
|
||||
let position = |i: Option<usize>| i.and_then(|i| positions.get(i)).copied();
|
||||
let (previous, before_previous, next, after_next) = (index.checked_sub(1), index.checked_sub(2), Some(index + 1), Some(index + 2));
|
||||
let mut lower = 0_f64;
|
||||
let mut upper = 1_f64;
|
||||
|
||||
// A neighbor bounds the marker unless they overlap
|
||||
if overlap(previous) == MarkerOverlap::Never
|
||||
&& let Some(previous) = position(previous)
|
||||
{
|
||||
lower = lower.max(previous);
|
||||
}
|
||||
if overlap(Some(index)) == MarkerOverlap::Never
|
||||
&& let Some(next) = position(next)
|
||||
{
|
||||
upper = upper.min(next);
|
||||
}
|
||||
|
||||
// Past a neighbor overlapping only its next, the marker beyond bounds it too, unless either overlaps freely
|
||||
let bounds_beyond = |near: MarkerOverlap, far: MarkerOverlap| (near == MarkerOverlap::NextOnly || far == MarkerOverlap::NextOnly) && near != MarkerOverlap::Freely && far != MarkerOverlap::Freely;
|
||||
if bounds_beyond(overlap(previous), overlap(before_previous))
|
||||
&& let Some(before_previous) = position(before_previous)
|
||||
{
|
||||
lower = lower.max(before_previous);
|
||||
}
|
||||
if bounds_beyond(overlap(Some(index)), overlap(next))
|
||||
&& let Some(after_next) = position(after_next)
|
||||
{
|
||||
upper = upper.min(after_next);
|
||||
}
|
||||
|
||||
(lower, upper)
|
||||
}
|
||||
|
||||
/// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row
|
||||
/// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display.
|
||||
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do, except where they may overlap.
|
||||
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do.
|
||||
fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) {
|
||||
// Snapshot exposure and values before the mutable-borrow loop
|
||||
let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) {
|
||||
@@ -2098,7 +2010,6 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let mut marker_scales = Vec::new();
|
||||
let mut marker_positions = Vec::new();
|
||||
let mut marker_between = Vec::new();
|
||||
let mut marker_overlaps = Vec::new();
|
||||
let mut marker_colors_and_links = Vec::new();
|
||||
for (i, param) in params.iter().enumerate() {
|
||||
let (exposed, value) = exposure_and_value[i];
|
||||
@@ -2111,21 +2022,13 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
marker_default_positions.push(param.scale.position(param.default_value));
|
||||
marker_scales.push(param.scale);
|
||||
marker_between.push(param.between_neighbors);
|
||||
marker_overlaps.push(if next_has_marker { param.overlap_next } else { MarkerOverlap::Never });
|
||||
marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker));
|
||||
}
|
||||
|
||||
// Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence.
|
||||
// A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span.
|
||||
let cyclic = params.iter().any(|param| param.scale.cyclic());
|
||||
let overlapping = marker_overlaps.iter().any(|&overlap| overlap != MarkerOverlap::Never);
|
||||
if overlapping {
|
||||
// Markers allowed to overlap are held only past those they can't pass, each bounded by markers earlier in the list
|
||||
for i in 0..marker_positions.len() {
|
||||
let (lower, _) = overlap_bounds(&marker_positions, &marker_overlaps, i);
|
||||
marker_positions[i] = marker_positions[i].max(lower);
|
||||
}
|
||||
} else if !cyclic {
|
||||
if !cyclic {
|
||||
let mut floor = 0.;
|
||||
for (position, &between) in marker_positions.iter_mut().zip(&marker_between) {
|
||||
if between {
|
||||
@@ -2146,8 +2049,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let slider_markers: Vec<SliderMarker> = marker_positions
|
||||
.iter()
|
||||
.zip(&marker_colors_and_links)
|
||||
.zip(marker_between.iter().zip(&marker_overlaps))
|
||||
.map(|((&position, &(handle_color, paired, dashed)), (&between, &overlap))| {
|
||||
.zip(&marker_between)
|
||||
.map(|((&position, &(handle_color, paired, dashed)), &between)| {
|
||||
let mut marker = SliderMarker::new(position, 0.5, handle_color);
|
||||
if paired {
|
||||
marker = marker.pair_with_next();
|
||||
@@ -2158,7 +2061,6 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
if between {
|
||||
marker = marker.between_neighbors();
|
||||
}
|
||||
marker = marker.overlap_next(overlap);
|
||||
marker
|
||||
})
|
||||
.collect();
|
||||
@@ -2180,7 +2082,6 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let marker_scales = marker_scales.clone();
|
||||
let marker_positions = marker_positions.clone();
|
||||
let marker_between = marker_between.clone();
|
||||
let marker_overlaps = marker_overlaps.clone();
|
||||
move |update: &SliderInputUpdate| {
|
||||
let i = match update {
|
||||
SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize,
|
||||
@@ -2195,13 +2096,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
// The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the
|
||||
// nearest markers that bound it, which a marker placed between its neighbors never does
|
||||
let bounding = |j: usize| between || !marker_between[j];
|
||||
let (left, right) = if overlapping {
|
||||
overlap_bounds(&marker_positions, &marker_overlaps, i)
|
||||
} else {
|
||||
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
||||
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
||||
(left, right)
|
||||
};
|
||||
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
||||
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
||||
|
||||
let scale_position = match update {
|
||||
SliderInputUpdate::MoveMarker { position, .. } if between => {
|
||||
@@ -2481,14 +2377,13 @@ fn value_slider(
|
||||
}
|
||||
|
||||
/// A row with a range slider and a 60px number input for the number at `parameter_widgets_info`. The slider's 0..1 position maps
|
||||
/// to the number through `position_of` and `value_at`, a typed number is stored as `typed_value` gives it, and double-click restores `default`.
|
||||
/// to the number through `position_of` and `value_at`, and double-click restores `default`.
|
||||
fn slider_row(
|
||||
parameter_widgets_info: ParameterWidgetsInfo,
|
||||
number_props: NumberInput,
|
||||
default: Option<f64>,
|
||||
position_of: impl Fn(f64) -> f64,
|
||||
value_at: impl Fn(f64) -> f64 + 'static + Send + Sync,
|
||||
typed_value: impl Fn(f64) -> f64 + 'static + Send + Sync,
|
||||
) -> Vec<WidgetInstance> {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
@@ -2521,7 +2416,7 @@ fn slider_row(
|
||||
number_props
|
||||
.value(Some(current))
|
||||
.sizing(WidgetSizing::fixed(60))
|
||||
.on_update(update_value_at_index(move |x: &NumberInput| tagged_value(typed_value(x.value.unwrap_or_default())), node_id, index))
|
||||
.on_update(update_value_at_index(move |x: &NumberInput| tagged_value(x.value.unwrap_or_default()), node_id, index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
@@ -2530,26 +2425,13 @@ fn slider_row(
|
||||
}
|
||||
|
||||
/// A slider row running linearly across `slider`'s bounds.
|
||||
pub(crate) fn slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||
pub(crate) fn range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||
slider_row(
|
||||
parameter_widgets_info,
|
||||
number_props,
|
||||
slider.default,
|
||||
move |value| slider.position(value),
|
||||
move |position| slider.value(position),
|
||||
|value| value,
|
||||
)
|
||||
}
|
||||
|
||||
/// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them.
|
||||
pub(crate) fn wrapping_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||
slider_row(
|
||||
parameter_widgets_info,
|
||||
number_props,
|
||||
slider.default,
|
||||
move |value| slider.position(slider.wrapped(value)),
|
||||
move |position| slider.value(position),
|
||||
move |value| slider.wrapped(value),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2626,105 +2508,6 @@ pub(crate) fn threshold_inspector(node_id: NodeId, context: &mut NodeInspectorCo
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn blend_if_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::blending_nodes::blend_if::blend_if::*;
|
||||
|
||||
let channel = enum_choice::<BlendIfChannel>()
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, ChannelInput, true, context))
|
||||
.inspector_row();
|
||||
|
||||
let channel_value = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ChannelInput).cloned()) {
|
||||
Some(TaggedValue::BlendIfChannel(channel)) => channel,
|
||||
_ => BlendIfChannel::Gray,
|
||||
};
|
||||
let ([content, underlying], track_color): ([[ParameterRef; 4]; 2], Color) = match channel_value {
|
||||
BlendIfChannel::Gray => (
|
||||
[
|
||||
[
|
||||
ContentFalloffStartInput.into(),
|
||||
ContentRangeStartInput.into(),
|
||||
ContentRangeEndInput.into(),
|
||||
ContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
UnderlyingFalloffStartInput.into(),
|
||||
UnderlyingRangeStartInput.into(),
|
||||
UnderlyingRangeEndInput.into(),
|
||||
UnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::WHITE,
|
||||
),
|
||||
BlendIfChannel::Red => (
|
||||
[
|
||||
[
|
||||
RedContentFalloffStartInput.into(),
|
||||
RedContentRangeStartInput.into(),
|
||||
RedContentRangeEndInput.into(),
|
||||
RedContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
RedUnderlyingFalloffStartInput.into(),
|
||||
RedUnderlyingRangeStartInput.into(),
|
||||
RedUnderlyingRangeEndInput.into(),
|
||||
RedUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::RED,
|
||||
),
|
||||
BlendIfChannel::Green => (
|
||||
[
|
||||
[
|
||||
GreenContentFalloffStartInput.into(),
|
||||
GreenContentRangeStartInput.into(),
|
||||
GreenContentRangeEndInput.into(),
|
||||
GreenContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
GreenUnderlyingFalloffStartInput.into(),
|
||||
GreenUnderlyingRangeStartInput.into(),
|
||||
GreenUnderlyingRangeEndInput.into(),
|
||||
GreenUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::GREEN,
|
||||
),
|
||||
BlendIfChannel::Blue => (
|
||||
[
|
||||
[
|
||||
BlueContentFalloffStartInput.into(),
|
||||
BlueContentRangeStartInput.into(),
|
||||
BlueContentRangeEndInput.into(),
|
||||
BlueContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
BlueUnderlyingFalloffStartInput.into(),
|
||||
BlueUnderlyingRangeStartInput.into(),
|
||||
BlueUnderlyingRangeEndInput.into(),
|
||||
BlueUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::BLUE,
|
||||
),
|
||||
};
|
||||
|
||||
// Each side's range runs along its channel's levels as a black split handle joined to a white one, with the fully shown range dashed between them
|
||||
let track = Gradient::from(vec![Color::BLACK, track_color]);
|
||||
let mut layout = vec![channel];
|
||||
for [falloff_start, range_start, range_end, falloff_end] in [content, underlying] {
|
||||
let params = [
|
||||
SliderSectionParam::new(falloff_start, Color::BLACK, 0., MarkerScale::LevelPercent).pair_with_next(),
|
||||
SliderSectionParam::new(range_start, Color::BLACK, 0., MarkerScale::LevelPercent)
|
||||
.dash_to_next()
|
||||
.overlap_next(MarkerOverlap::Freely),
|
||||
SliderSectionParam::new(range_end, Color::WHITE, 100., MarkerScale::LevelPercent).pair_with_next(),
|
||||
SliderSectionParam::new(falloff_end, Color::WHITE, 100., MarkerScale::LevelPercent),
|
||||
];
|
||||
build_shared_slider_section(node_id, context, &track, ¶ms, &mut layout);
|
||||
}
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::raster::vibrance::*;
|
||||
|
||||
@@ -2734,8 +2517,8 @@ pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
||||
max: 100.,
|
||||
default: Some(0.),
|
||||
};
|
||||
let vibrance = slider_widget(ParameterWidgetsInfo::new(node_id, VibranceInput, true, context), number_input.clone(), slider);
|
||||
let saturation = slider_widget(ParameterWidgetsInfo::new(node_id, SaturationInput, true, context), number_input, slider);
|
||||
let vibrance = range_slider_widget(ParameterWidgetsInfo::new(node_id, VibranceInput, true, context), number_input.clone(), slider);
|
||||
let saturation = range_slider_widget(ParameterWidgetsInfo::new(node_id, SaturationInput, true, context), number_input, slider);
|
||||
|
||||
vec![LayoutGroup::row(vibrance), LayoutGroup::row(saturation)]
|
||||
}
|
||||
@@ -3095,7 +2878,7 @@ pub(crate) fn sample_polyline_inspector(node_id: NodeId, context: &mut NodeInspe
|
||||
pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::raster::exposure::*;
|
||||
|
||||
let exposure = slider_widget(
|
||||
let exposure = range_slider_widget(
|
||||
ParameterWidgetsInfo::new(node_id, ExposureInput, true, context),
|
||||
NumberInput::default().min(-20.).max(20.),
|
||||
SliderRange {
|
||||
@@ -3104,7 +2887,7 @@ pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
||||
default: Some(0.),
|
||||
},
|
||||
);
|
||||
let offset = slider_widget(
|
||||
let offset = range_slider_widget(
|
||||
ParameterWidgetsInfo::new(node_id, OffsetInput, true, context),
|
||||
NumberInput::default().min(-0.5).max(0.5),
|
||||
SliderRange {
|
||||
@@ -3120,7 +2903,6 @@ pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
||||
Some(1.),
|
||||
|gamma| MarkerScale::Gamma.position(gamma),
|
||||
|position| MarkerScale::Gamma.value(position),
|
||||
|gamma| gamma,
|
||||
);
|
||||
|
||||
vec![LayoutGroup::row(exposure), LayoutGroup::row(offset), LayoutGroup::row(gamma_correction)]
|
||||
@@ -3304,80 +3086,6 @@ 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::*;
|
||||
|
||||
// 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) => graph_modification_utils::gradient_curvature_values(document_node),
|
||||
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 make that form
|
||||
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, gradient_form, tooltip) in [
|
||||
("Linear", GradientForm::Linear, "Sets both curvatures to 0, making straight contours."),
|
||||
(
|
||||
"Radial",
|
||||
GradientForm::Radial,
|
||||
"Sets the start curvature to -1 and the end curvature to 0.5, making circles around the start.",
|
||||
),
|
||||
] {
|
||||
let [start, end] = gradient_form.curvatures();
|
||||
form.push(
|
||||
TextButton::new(label)
|
||||
.tooltip_description(tooltip)
|
||||
.emphasized(curvatures.and_then(GradientForm::from_curvatures) == Some(gradient_form))
|
||||
.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 parameters would get without this panel
|
||||
let options = |index: usize| {
|
||||
let registry = graphene_std::registry::NODE_METADATA.lock().ok();
|
||||
let field = registry.as_ref().and_then(|registry| registry.get(&IDENTIFIER)).and_then(|metadata| metadata.fields.get(index));
|
||||
field.map(ParameterOptions::from).unwrap_or_default()
|
||||
};
|
||||
let mut row = |index: usize, ty: Type| {
|
||||
context
|
||||
.call_widget_override(&node_id, index)
|
||||
.unwrap_or_else(|| inspector_row_from_type(node_id, index, &ty, options(index), context).unwrap_or_else(|rows| rows))
|
||||
};
|
||||
|
||||
let mut layout = vec![LayoutGroup::row(form)];
|
||||
layout.extend(row(StartCurvatureInput::INDEX, concrete!(f64)));
|
||||
layout.extend(row(EndCurvatureInput::INDEX, concrete!(f64)));
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
@@ -3535,7 +3243,18 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
options = ParameterOptions::from(field);
|
||||
options = ParameterOptions {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
};
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
@@ -3924,25 +3643,9 @@ pub(crate) fn fill_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
let entries = [GradientForm::Linear, GradientForm::Radial]
|
||||
.iter()
|
||||
.map(|&gradient_form| {
|
||||
let [start, end] = gradient_form.curvatures();
|
||||
RadioEntryData::new(format!("{:?}", gradient_form))
|
||||
.label(gradient_form.to_string())
|
||||
.on_update(move |_| 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_update(update_value(move |_| TaggedValue::GradientForm(gradient_form), node_id, GradientFormInput))
|
||||
.on_commit(commit_value)
|
||||
})
|
||||
.collect();
|
||||
@@ -4036,61 +3739,6 @@ pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
|
||||
}
|
||||
|
||||
pub(crate) fn sharpen_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::blending_nodes::filters::sharpen::*;
|
||||
|
||||
// Edges Only compares against the four nearest neighbors in place of the blur, so it doesn't read the radius
|
||||
let edges_only = get_document_node(node_id, context)
|
||||
.ok()
|
||||
.and_then(|document_node| document_node.input(EdgesOnlyInput).and_then(|input| input.as_value()))
|
||||
.is_some_and(|tagged| matches!(tagged, TaggedValue::Bool(true)));
|
||||
|
||||
let number_input = NumberInput::default().mode_range().unit("%").min(0.).range_max(Some(500.));
|
||||
let amount = number_widget(ParameterWidgetsInfo::new(node_id, AmountInput, true, context), number_input);
|
||||
|
||||
let number_input = NumberInput::default().mode_range().unit(" px").min(0.).range_max(Some(250.)).disabled(edges_only);
|
||||
let radius = number_widget(ParameterWidgetsInfo::new(node_id, RadiusInput, true, context), number_input);
|
||||
|
||||
let number_input = NumberInput::default().mode_range().min(0.).range_max(Some(255.));
|
||||
let threshold = number_widget(ParameterWidgetsInfo::new(node_id, ThresholdInput, true, context), number_input);
|
||||
|
||||
let edges_only = bool_widget(ParameterWidgetsInfo::new(node_id, EdgesOnlyInput, true, context), CheckboxInput::default());
|
||||
|
||||
vec![LayoutGroup::row(amount), LayoutGroup::row(radius), LayoutGroup::row(threshold), LayoutGroup::row(edges_only)]
|
||||
}
|
||||
|
||||
pub(crate) fn displace_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::blending_nodes::distortions::displace::*;
|
||||
|
||||
// Each mode shows only the maps and distances it reads, and a wired mode shows both sets
|
||||
let mode = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ModeInput)) {
|
||||
Some(TaggedValue::DisplaceMode(mode)) => Some(*mode),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let mut layout = vec![enum_choice::<DisplaceMode>().for_socket(ParameterWidgetsInfo::new(node_id, ModeInput, true, context)).inspector_row()];
|
||||
if !matches!(mode, Some(DisplaceMode::XAndY)) {
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, DisplacementInput, true, context), ColorInput::default()));
|
||||
|
||||
let number_input = NumberInput::default().mode_range().unit("°").range_min(Some(-180.)).range_max(Some(180.));
|
||||
layout.push(LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, AngleInput, true, context), number_input)));
|
||||
|
||||
let number_input = NumberInput::default().unit(" px");
|
||||
layout.push(LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), number_input)));
|
||||
}
|
||||
if !matches!(mode, Some(DisplaceMode::Angle)) {
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, XDisplacementInput, true, context), ColorInput::default()));
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, YDisplacementInput, true, context), ColorInput::default()));
|
||||
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, false, false));
|
||||
}
|
||||
|
||||
let edge_mode = enum_choice::<GradientSpread>()
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, EdgeModeInput, true, context))
|
||||
.inspector_row();
|
||||
layout.push(edge_mode);
|
||||
layout
|
||||
}
|
||||
|
||||
pub struct ParameterWidgetsInfo<'a> {
|
||||
document_id: DocumentId,
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
|
||||
@@ -212,6 +212,23 @@ pub struct NodeEvaluationError {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendClickTargets {
|
||||
#[serde(rename = "nodeClickTargets")]
|
||||
pub node_click_targets: Vec<String>,
|
||||
#[serde(rename = "layerClickTargets")]
|
||||
pub layer_click_targets: Vec<String>,
|
||||
#[serde(rename = "connectorClickTargets")]
|
||||
pub connector_click_targets: Vec<String>,
|
||||
#[serde(rename = "iconClickTargets")]
|
||||
pub icon_click_targets: Vec<String>,
|
||||
#[serde(rename = "allNodesBoundingBox")]
|
||||
pub all_nodes_bounding_box: String,
|
||||
#[serde(rename = "importExportNames")]
|
||||
pub import_export_names: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Direction {
|
||||
|
||||
@@ -5,7 +5,6 @@ use crate::messages::prelude::*;
|
||||
pub struct OverlaysMessageContext<'a> {
|
||||
pub visibility_settings: OverlaysVisibilitySettings,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
pub graph_open: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
@@ -26,7 +25,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
|
||||
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
|
||||
|
||||
if visibility_settings.all() && !context.graph_open {
|
||||
if visibility_settings.all() {
|
||||
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
|
||||
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::consts::{
|
||||
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLACK, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_WHITE_05, COLOR_OVERLAY_YELLOW,
|
||||
COLOR_OVERLAY_YELLOW_DULL, COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, CURVATURE_COMB_DEFAULT_SCALE,
|
||||
DOWEL_PIN_RADIUS, GRADIENT_LINE_WIDTH, GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT, GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH, GRADIENT_STOP_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH,
|
||||
PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
|
||||
DOWEL_PIN_RADIUS, GRADIENT_MIDPOINT_DIAMOND_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET,
|
||||
SKEW_TRIANGLE_SIZE,
|
||||
};
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::hex_to_rgba_u8;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -24,7 +24,7 @@ use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::misc::point_to_dvec2;
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, Color, NodeParameter};
|
||||
use graphene_std::{ATTR_TRANSFORM, NodeParameter};
|
||||
use kurbo::{self, BezPath, ParamCurve};
|
||||
use kurbo::{Affine, PathSeg};
|
||||
use std::borrow::Cow;
|
||||
@@ -404,12 +404,6 @@ impl OverlayContext {
|
||||
self.record(move |overlays| overlays.dashed_polygon(&polygon, stroke_color.as_deref(), color_fill.as_deref(), dash_width, dash_gap_width, dash_offset));
|
||||
}
|
||||
|
||||
/// Strokes the open path through these points, unlike [`Self::dashed_polygon`], which closes it.
|
||||
pub fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
let (points, color) = (points.to_vec(), owned(color));
|
||||
self.record(move |overlays| overlays.dashed_polyline(&points, color.as_deref(), dash_width, dash_gap_width, dash_offset));
|
||||
}
|
||||
|
||||
pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.line(start, end, color.as_deref(), thickness));
|
||||
@@ -434,12 +428,6 @@ impl OverlayContext {
|
||||
self.record(move |overlays| overlays.manipulator_handle(position, selected, color.as_deref()));
|
||||
}
|
||||
|
||||
/// Draws a handle like [`Self::manipulator_handle`] outlined in `color`, and filled with it too where `selected`.
|
||||
pub fn colored_manipulator_handle(&mut self, position: DVec2, selected: bool, color: &str) {
|
||||
let color = color.to_owned();
|
||||
self.record(move |overlays| overlays.filled_manipulator_handle(position, if selected { &color } else { COLOR_OVERLAY_WHITE }, &color));
|
||||
}
|
||||
|
||||
pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.manipulator_anchor(position, selected, color.as_deref()));
|
||||
@@ -450,15 +438,8 @@ impl OverlayContext {
|
||||
self.record(move |overlays| overlays.gradient_color_stop(position, emphasis, &color, small));
|
||||
}
|
||||
|
||||
/// Draws a gradient midpoint's diamond filled with `color`, taller across the gradient line at `angle` than it is wide, bordered like a color stop's dot.
|
||||
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
|
||||
let color = color.to_owned();
|
||||
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, &color, angle));
|
||||
}
|
||||
|
||||
/// Draws a line in a gradient's own colors, from its color `stops` at fractions of the way from `start` to `end`, outlined in white and then black like its color stops.
|
||||
pub fn gradient_line(&mut self, start: DVec2, end: DVec2, stops: Vec<(f64, Color)>) {
|
||||
self.record(move |overlays| overlays.gradient_line(start, end, &stops));
|
||||
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
|
||||
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, angle));
|
||||
}
|
||||
|
||||
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
|
||||
@@ -804,24 +785,6 @@ impl OverlayContextInternal {
|
||||
self.stroke_in_view(&stroke, Self::parse_color(stroke_color), &path);
|
||||
}
|
||||
|
||||
fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
let mut points = points.iter().map(|&point| self.snap_to_physical_pixel_center(point));
|
||||
let Some(first) = points.next() else { return };
|
||||
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(kurbo::Point::new(first.x, first.y));
|
||||
for point in points {
|
||||
path.line_to(kurbo::Point::new(point.x, point.y));
|
||||
}
|
||||
|
||||
let mut stroke = kurbo::Stroke::new(1.);
|
||||
if let Some(dash_width) = dash_width {
|
||||
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap_width.unwrap_or(1.)]);
|
||||
}
|
||||
|
||||
self.stroke_in_view(&stroke, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), &path);
|
||||
}
|
||||
|
||||
fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
|
||||
self.dashed_line(start, end, color, thickness, None, None, None)
|
||||
}
|
||||
@@ -846,17 +809,16 @@ impl OverlayContextInternal {
|
||||
}
|
||||
|
||||
fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
|
||||
self.filled_manipulator_handle(position, fill, color.unwrap_or(COLOR_OVERLAY_BLUE));
|
||||
}
|
||||
|
||||
fn filled_manipulator_handle(&mut self, position: DVec2, fill: &str, stroke: &str) {
|
||||
let transform = self.get_transform();
|
||||
let position = self.snap_to_physical_pixel_center(position);
|
||||
|
||||
let circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.);
|
||||
|
||||
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &circle);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(stroke), None, &circle);
|
||||
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &circle);
|
||||
}
|
||||
|
||||
fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
|
||||
@@ -898,7 +860,7 @@ impl OverlayContextInternal {
|
||||
GizmoEmphasis::Active => 1.,
|
||||
};
|
||||
let stroke_width = radius_offset * 2. + 1.;
|
||||
let radius = (GRADIENT_STOP_RADIUS + radius_offset) * if small { 0.5 } else { 1. };
|
||||
let radius = (MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1. + radius_offset) * if small { 0.5 } else { 1. };
|
||||
|
||||
let mut draw_circle = |radius: f64, width: Option<f64>, color: &str| {
|
||||
let circle = kurbo::Circle::new((position.x, position.y), radius);
|
||||
@@ -916,59 +878,33 @@ impl OverlayContextInternal {
|
||||
draw_circle(radius, Some(stroke_width), COLOR_OVERLAY_WHITE);
|
||||
}
|
||||
|
||||
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
|
||||
let position = position.round() - DVec2::splat(0.5);
|
||||
let transform = self.get_transform() * kurbo::Affine::translate((position.x, position.y)) * kurbo::Affine::rotate(angle);
|
||||
|
||||
// Grown for emphasis with a thicker white border, as a color stop's dot is
|
||||
let radius_offset = match emphasis {
|
||||
GizmoEmphasis::Regular => 0.,
|
||||
GizmoEmphasis::Hovered => 0.5,
|
||||
GizmoEmphasis::Active => 1.,
|
||||
};
|
||||
let stroke_width = radius_offset * 2. + 1.;
|
||||
|
||||
// Taller across the gradient line than it is wide along it
|
||||
let (half_width, half_height) = (GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH + radius_offset, GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT + radius_offset);
|
||||
let mut diamond = BezPath::new();
|
||||
diamond.move_to((half_width, 0.));
|
||||
diamond.line_to((0., half_height));
|
||||
diamond.line_to((-half_width, 0.));
|
||||
diamond.line_to((0., -half_height));
|
||||
diamond.close_path();
|
||||
|
||||
// The black border shows half a pixel past the white one, as around a color stop's dot
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(stroke_width + 1.), transform, Self::parse_color(COLOR_OVERLAY_BLACK), None, &diamond);
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color), None, &diamond);
|
||||
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &diamond);
|
||||
}
|
||||
|
||||
fn gradient_line(&mut self, start: DVec2, end: DVec2, stops: &[(f64, Color)]) {
|
||||
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
|
||||
let transform = self.get_transform();
|
||||
let position = position.round() - DVec2::splat(0.5);
|
||||
|
||||
// Centered on whole pixels, the even widths have crisp edges
|
||||
let [start, end] = [start, end].map(|point| self.snap_to_physical_pixel(point));
|
||||
let line = kurbo::Line::new((start.x, start.y), (end.x, end.y));
|
||||
// Rotate diamond points by the gradient line angle
|
||||
let (sin, cos) = angle.sin_cos();
|
||||
let rotate = |dx: f64, dy: f64| DVec2::new(dx * cos - dy * sin, dx * sin + dy * cos);
|
||||
|
||||
// Bordered like a color stop's dot, by a pixel of white and then half a pixel of black
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH + 3.), transform, Self::parse_color(COLOR_OVERLAY_BLACK), None, &line);
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH + 2.), transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &line);
|
||||
let top = rotate(0., -GRADIENT_MIDPOINT_DIAMOND_RADIUS);
|
||||
let right = rotate(GRADIENT_MIDPOINT_DIAMOND_RADIUS, 0.);
|
||||
let bottom = rotate(0., GRADIENT_MIDPOINT_DIAMOND_RADIUS);
|
||||
let left = rotate(-GRADIENT_MIDPOINT_DIAMOND_RADIUS, 0.);
|
||||
|
||||
// Opaque like the stops' dots
|
||||
let stops = stops.iter().map(|&(offset, color)| {
|
||||
let [red, green, blue, _] = color.to_gamma_srgb_channels();
|
||||
peniko::ColorStop {
|
||||
offset: offset as f32,
|
||||
color: peniko::color::DynamicColor::from_alpha_color(peniko::Color::new([red, green, blue, 1.])),
|
||||
}
|
||||
});
|
||||
let mut gradient = peniko::Gradient::new_linear((start.x, start.y), (end.x, end.y));
|
||||
gradient.stops = peniko::ColorStops(stops.collect());
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(kurbo::Point::new(position.x + top.x, position.y + top.y));
|
||||
path.line_to(kurbo::Point::new(position.x + right.x, position.y + right.y));
|
||||
path.line_to(kurbo::Point::new(position.x + bottom.x, position.y + bottom.y));
|
||||
path.line_to(kurbo::Point::new(position.x + left.x, position.y + left.y));
|
||||
path.close_path();
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH), transform, &gradient, None, &line);
|
||||
let (fill, stroke_width) = match emphasis {
|
||||
GizmoEmphasis::Regular => (COLOR_OVERLAY_WHITE, 1.),
|
||||
GizmoEmphasis::Hovered => (COLOR_OVERLAY_WHITE, 2.),
|
||||
GizmoEmphasis::Active => (COLOR_OVERLAY_BLUE, 1.),
|
||||
};
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &path);
|
||||
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
|
||||
}
|
||||
|
||||
fn resize_handle(&mut self, position: DVec2, rotation: f64) {
|
||||
|
||||
@@ -22,6 +22,7 @@ pub struct ResourceMessageHandler {
|
||||
pub embedded: EmbeddedResources,
|
||||
#[serde(skip)]
|
||||
pending_resolves: HashSet<ResourceId>,
|
||||
/// Resources that failed to load, which rendering no longer waits on, even during a retry.
|
||||
#[serde(skip)]
|
||||
failed_resolves: HashSet<ResourceId>,
|
||||
}
|
||||
@@ -218,6 +219,8 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
ResourceMessage::ResolveFailed { resource_id } => {
|
||||
self.pending_resolves.remove(&resource_id);
|
||||
self.failed_resolves.insert(resource_id);
|
||||
|
||||
// Rendering stops waiting on the resource and draws a fallback in its place
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
@@ -233,6 +236,20 @@ impl ResourceMessageHandler {
|
||||
self.registry.is_empty() && self.embedded.is_empty()
|
||||
}
|
||||
|
||||
/// Whether a resource lacks its data and hasn't failed to load, which rendering waits for.
|
||||
pub fn awaiting_resources(&self) -> bool {
|
||||
self.registry.unresolved().any(|info| !self.failed_resolves.contains(&info.id))
|
||||
}
|
||||
|
||||
/// Changes whenever a resource gains, loses, or changes its data. Summed per resource since the registry's order isn't stable. O(resolved resources).
|
||||
pub fn resolved_hash(&self) -> u64 {
|
||||
self.registry.resolved().fold(0, |sum, info| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(info.id, info.hash).hash(&mut hasher);
|
||||
sum.wrapping_add(hasher.finish())
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn embed_resources(&mut self, resources_load_handle: Box<dyn LoadResource>) {
|
||||
let embedded = self
|
||||
.registry
|
||||
@@ -258,18 +275,6 @@ impl ResourceMessageHandler {
|
||||
self.registry.delete(&id);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn awaiting_resources(&self) -> bool {
|
||||
self.registry.unresolved().any(|info| !self.failed_resolves.contains(&info.id))
|
||||
}
|
||||
|
||||
pub fn resolved_hash(&self) -> u64 {
|
||||
self.registry.resolved().fold(0, |sum, info| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(info.id, info.hash).hash(&mut hasher);
|
||||
sum.wrapping_add(hasher.finish())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
|
||||
|
||||
use super::test_support::open_demo;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use glam::DVec2;
|
||||
use graphene_std::uuid::NodeId;
|
||||
@@ -20,32 +20,20 @@ const DEMOS: [&str; 8] = [
|
||||
const REPETITIONS: u32 = 200;
|
||||
|
||||
#[test]
|
||||
fn wire_anchors_lie_on_the_ports_of_every_demo_node() {
|
||||
fn wire_anchors_match_the_ports_of_every_demo_node() {
|
||||
for demo in DEMOS {
|
||||
let document = open_demo(demo);
|
||||
let interface = &document.network_interface;
|
||||
|
||||
for node_id in interface.document_network().nodes.keys() {
|
||||
// A redirect dot's wires attach at its center, between the gutters they're grabbed from
|
||||
let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body");
|
||||
let is_redirect_dot = interface.is_redirect_dot(node_id, &[]);
|
||||
let on_port = |wanted: Part, anchor: Option<DVec2>| {
|
||||
let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target));
|
||||
match (port, anchor) {
|
||||
(Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2.,
|
||||
(Some(port), Some(anchor)) => port.contains(anchor),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
|
||||
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
|
||||
for index in 0..interface.number_of_inputs(node_id, &[]) {
|
||||
let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]);
|
||||
assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}");
|
||||
let input = InputConnector::node_at_index(*node_id, index);
|
||||
assert_eq!(interface.input_position(&input, &[]), ports.input_port_position(index), "{demo}: input {index} of node {node_id}");
|
||||
}
|
||||
for index in 0..interface.number_of_outputs(node_id, &[]) {
|
||||
let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]);
|
||||
assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}");
|
||||
let output = OutputConnector::node(*node_id, index);
|
||||
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,7 +60,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
|
||||
let start = Instant::now();
|
||||
for _ in 0..REPETITIONS {
|
||||
for node_id in &node_ids {
|
||||
std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
|
||||
std::hint::black_box(interface.node_click_targets(node_id, &[]));
|
||||
}
|
||||
}
|
||||
let all_click_targets = start.elapsed() / REPETITIONS;
|
||||
|
||||
@@ -35,6 +35,7 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
|
||||
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.set_absolute_position(*position);
|
||||
}
|
||||
interface.invalidate_positions(network_path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,14 +172,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
|
||||
interface.finish_drag(&[]);
|
||||
|
||||
let kept = interface.positions(node_ids.iter().copied(), &[]);
|
||||
let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
|
||||
let Some((_, indices, graph)) = interface.layout_graph(&[]) else {
|
||||
panic!("the root network is laid out")
|
||||
};
|
||||
let fresh = graph_layout::Layout::new(&graph);
|
||||
for (other, position) in kept {
|
||||
assert_eq!(
|
||||
Some(position),
|
||||
laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
|
||||
indices.get(&other).map(|index| fresh.node(*index).position),
|
||||
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -975,7 +975,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
|
||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||
let fill_node = &network.nodes[&node_id];
|
||||
|
||||
assert_eq!(fill_node.inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape");
|
||||
assert_eq!(fill_node.inputs.len(), 7, "the legacy Fill should upgrade to the 7-input shape");
|
||||
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
|
||||
assert!(
|
||||
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
|
||||
@@ -1033,13 +1033,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
|
||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||
let fill_node = &network.nodes[&node_id];
|
||||
|
||||
assert_eq!(fill_node.inputs.len(), 8, "the eight-input Fill should come out in the modern shape, which also has eight inputs");
|
||||
let curvatures = [graphene_std::vector::fill::StartCurvatureInput::INDEX, graphene_std::vector::fill::EndCurvatureInput::INDEX].map(|index| fill_node.inputs[index].as_value().cloned());
|
||||
assert_eq!(
|
||||
curvatures,
|
||||
[0., 0.].map(|curvature| Some(TaggedValue::Number(curvature))),
|
||||
"the linear form should become its curvatures"
|
||||
);
|
||||
assert_eq!(fill_node.inputs.len(), 7, "the eight-input Fill should fold down to the 7-input shape");
|
||||
|
||||
let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
|
||||
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
|
||||
|
||||
@@ -53,8 +53,6 @@ pub struct DocumentMetadata {
|
||||
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>,
|
||||
/// The bounding box of the frames that each layer's effects paint anywhere in, in document pixels, for the layers with such effects.
|
||||
pub layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>,
|
||||
/// 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.
|
||||
@@ -366,7 +364,7 @@ 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, the frames its effects paint anywhere in, and how far they paint past it. Only the first item of a
|
||||
/// 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| {
|
||||
@@ -374,8 +372,7 @@ impl DocumentMetadata {
|
||||
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
||||
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
|
||||
});
|
||||
let frames = self.layer_effects_frames.get(&layer).copied();
|
||||
let [min, max] = [stroked, self.bounding_box_document(layer), frames].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||
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])
|
||||
@@ -754,25 +751,6 @@ mod tests {
|
||||
assert_eq!((min.x, max.x), (0., 110.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_with_effects_hold_the_frames_the_effects_paint_in() {
|
||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||
let mut square = BezPath::new();
|
||||
square.move_to((-30., -30.));
|
||||
square.line_to((30., -30.));
|
||||
square.line_to((30., 30.));
|
||||
square.line_to((-30., 30.));
|
||||
square.close_path();
|
||||
|
||||
// A layer 30 across each way from its middle, with effects painting anywhere in a frame reaching 40 from it, and 2 past that
|
||||
let mut metadata = DocumentMetadata::default();
|
||||
metadata.click_targets.insert(layer, vec![Arc::new(ClickTarget::new_with_path(square, 0.))]);
|
||||
metadata.layer_effects_frames.insert(layer, [DVec2::splat(-40.), DVec2::splat(40.)]);
|
||||
metadata.layer_effects_reach.insert(layer, 2.);
|
||||
|
||||
assert_eq!(metadata.bounding_box_document_with_stroke_and_effects(layer), Some([DVec2::splat(-42.), DVec2::splat(42.)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
|
||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||
|
||||
@@ -22,7 +22,6 @@ mod layout;
|
||||
mod layout_pass;
|
||||
mod memo_network;
|
||||
mod mutations;
|
||||
mod node_parts;
|
||||
mod queries;
|
||||
mod reconcile;
|
||||
mod resolved_types;
|
||||
@@ -37,7 +36,6 @@ mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use layout_pass::NetworkLayout;
|
||||
pub use node_parts::{Part, PartTarget};
|
||||
pub use reconcile::{ReconcileError, Reconciled};
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
@@ -54,7 +52,7 @@ use crate::consts::{
|
||||
STACK_VERTICAL_GAP,
|
||||
};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
|
||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||
|
||||
@@ -93,7 +93,7 @@ impl NodeNetworkInterface {
|
||||
EditorDelta::NodeMetadata { network, node_id, change } => {
|
||||
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
|
||||
match change {
|
||||
NodeMetadataChange::NodeType(node_type) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()),
|
||||
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
|
||||
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
|
||||
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
|
||||
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
|
||||
|
||||
@@ -88,15 +88,34 @@ impl NodeNetworkInterface {
|
||||
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
|
||||
}
|
||||
|
||||
/// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed.
|
||||
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
|
||||
let generation = self.with_layout(network_path, NetworkLayout::generation)?;
|
||||
let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
|
||||
if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
|
||||
cache.unload();
|
||||
}
|
||||
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
|
||||
self.load_import_export_ports(network_path);
|
||||
|
||||
cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports))
|
||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in import_export_ports");
|
||||
return None;
|
||||
};
|
||||
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
|
||||
log::error!("Could not load import export ports in import_export_ports");
|
||||
return None;
|
||||
};
|
||||
Some(ports)
|
||||
}
|
||||
|
||||
/// Reads the import/export ports through &self, loading them first if needed.
|
||||
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
|
||||
self.network_metadata(network_path)?
|
||||
.transient_metadata
|
||||
.import_export_ports
|
||||
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
|
||||
}
|
||||
|
||||
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in load_import_export_ports");
|
||||
return;
|
||||
};
|
||||
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
|
||||
}
|
||||
|
||||
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
|
||||
@@ -107,13 +126,78 @@ impl NodeNetworkInterface {
|
||||
transient.import_export_ports.unload();
|
||||
}
|
||||
|
||||
/// The combined bounds of every node in the network, in node graph space.
|
||||
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
self.with_layout(network_path, NetworkLayout::bounds)
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in all_nodes_bounding_box");
|
||||
return None;
|
||||
};
|
||||
|
||||
let bounding_box = network_metadata
|
||||
.transient_metadata
|
||||
.all_nodes_bounding_box
|
||||
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
|
||||
if bounding_box.is_none() {
|
||||
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
|
||||
}
|
||||
bounding_box
|
||||
}
|
||||
|
||||
/// The combined bounds of every node in the network, in node graph space.
|
||||
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let network_metadata = self.network_metadata(network_path)?;
|
||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
||||
|
||||
Some(
|
||||
nodes
|
||||
.iter()
|
||||
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
|
||||
.reduce(Quad::combine_bounds)
|
||||
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
|
||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
|
||||
return;
|
||||
};
|
||||
transient.all_nodes_bounding_box.unload();
|
||||
transient.import_export_clearance.unload();
|
||||
self.unload_import_export_ports(network_path);
|
||||
}
|
||||
|
||||
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||
self.with_layout(network_path, NetworkLayout::clearance)
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in import_export_clearance");
|
||||
return None;
|
||||
};
|
||||
|
||||
network_metadata
|
||||
.transient_metadata
|
||||
.import_export_clearance
|
||||
.with_loaded_or(|| self.compute_import_export_clearance(network_path), |clearance| *clearance)
|
||||
}
|
||||
|
||||
/// The horizontal extents of the nodes in the network, with the redirect dots measured by their centers apart from the rest.
|
||||
fn compute_import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||
let network_metadata = self.network_metadata(network_path)?;
|
||||
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
||||
|
||||
let mut clearance = ImportExportClearance::default();
|
||||
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
|
||||
let Some([top_left, bottom_right]) = self.node_bounding_box(node_id, network_path) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
let center = (top_left.x + bottom_right.x) / 2.;
|
||||
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
||||
} else {
|
||||
clearance.node_sides = widen(clearance.node_sides, top_left.x, bottom_right.x);
|
||||
}
|
||||
}
|
||||
|
||||
Some(clearance)
|
||||
}
|
||||
|
||||
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
|
||||
@@ -280,10 +364,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
|
||||
self.layer_width_and_name_width(node_id, network_path).map(|(layer_width, _)| layer_width)
|
||||
}
|
||||
|
||||
pub(super) fn layer_width_and_name_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(u32, f64)> {
|
||||
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
|
||||
log::error!("Could not get nested node_metadata in layer_width");
|
||||
return None;
|
||||
@@ -296,7 +376,7 @@ impl NodeNetworkInterface {
|
||||
node_metadata
|
||||
.transient_metadata
|
||||
.layer_width
|
||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |widths| *widths)
|
||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
|
||||
}
|
||||
|
||||
/// Unloads layer width if the node is a layer.
|
||||
@@ -395,7 +475,7 @@ impl NodeNetworkInterface {
|
||||
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||
let thick = vertical_end && vertical_start;
|
||||
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
||||
|
||||
let path_string = vector_wire.to_svg();
|
||||
let center_path_string = center_line.to_svg();
|
||||
@@ -443,7 +523,7 @@ impl NodeNetworkInterface {
|
||||
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||
let thick = vertical_end && vertical_start;
|
||||
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, wire_style);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
||||
Some((vector_wire, center_line, thick))
|
||||
}
|
||||
|
||||
@@ -469,10 +549,17 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// The node's body, ports, and handles, built where it is drawn now.
|
||||
/// The box around the node's body where it sits in its grid cell, in node graph space.
|
||||
pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
||||
self.compute_node_click_targets(node_id, network_path)
|
||||
}
|
||||
|
||||
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
|
||||
self.compute_node_click_targets(node_id, network_path).as_ref().map(read)
|
||||
}
|
||||
|
||||
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?;
|
||||
Some([body.min, body.max])
|
||||
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
|
||||
.flatten()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
use super::template::{NodeTemplate, NodeTemplateImplementation};
|
||||
use super::template::NodeTemplateImplementation;
|
||||
use super::{InputConnector, OutputConnector, catalog};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
||||
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
|
||||
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await;
|
||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
||||
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
||||
|
||||
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
|
||||
let custom = NodeId::new();
|
||||
let blend = NodeId::new();
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
|
||||
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]);
|
||||
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
||||
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
||||
panic!("the Blend should name a table entry")
|
||||
|
||||
+7
-145
@@ -2,7 +2,7 @@ use super::{
|
||||
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
|
||||
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
|
||||
};
|
||||
use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
use crate::consts::{GRID_SIZE, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
|
||||
@@ -330,6 +330,7 @@ async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
|
||||
}
|
||||
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
|
||||
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
|
||||
network_interface.invalidate_positions(&[]);
|
||||
|
||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
|
||||
|
||||
@@ -3118,7 +3119,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let path = [subgraph];
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
|
||||
@@ -3399,63 +3400,6 @@ async fn visibility_and_lock_toggles_made_in_an_open_transaction_undo_together()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn middle_clicking_a_node_in_the_graph_toggles_its_visibility_but_middle_dragging_only_pans() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected").to_node();
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
|
||||
let is_visible = |editor: &EditorTestUtils| editor.active_document().network_interface.is_visible(&layer, &[]);
|
||||
let graph_pan = |editor: &EditorTestUtils| {
|
||||
editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.network_metadata(&[])
|
||||
.unwrap()
|
||||
.persistent_metadata
|
||||
.navigation_metadata
|
||||
.node_graph_ptz
|
||||
.pan
|
||||
};
|
||||
let layer_in_viewport = |editor: &EditorTestUtils| {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let [min, max] = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
|
||||
let node_graph_to_viewport = network_interface.network_metadata(&[]).unwrap().persistent_metadata.navigation_metadata.node_graph_to_viewport;
|
||||
|
||||
(0..=(max.x - min.x) as i32)
|
||||
.map(|x| node_graph_to_viewport.transform_point2(DVec2::new(min.x + x as f64, (min.y + max.y) / 2.)))
|
||||
.find(|&point| network_interface.node_from_click(point, &[]) == Some(layer))
|
||||
.expect("the layer should be pressable")
|
||||
};
|
||||
let pointer_state = |position: DVec2, mouse_keys: MouseKeys| EditorPointerState {
|
||||
editor_position: position,
|
||||
mouse_keys,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Pressed and released with a wobble too small to count as a drag
|
||||
let start = layer_in_viewport(&editor);
|
||||
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
|
||||
assert!(is_visible(&editor), "pressing the middle button shouldn't toggle the layer yet");
|
||||
editor.mouseup(pointer_state(start + DVec2::new(2., 0.), MouseKeys::empty()), ModifierKeys::empty()).await;
|
||||
assert!(!is_visible(&editor), "a middle click on the layer should hide it");
|
||||
|
||||
// Dragged away and back before the release
|
||||
let start = layer_in_viewport(&editor);
|
||||
let pan_before = graph_pan(&editor);
|
||||
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
|
||||
editor.move_mouse(start.x + 40., start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
|
||||
assert_ne!(graph_pan(&editor), pan_before, "a middle drag should pan the graph");
|
||||
editor.move_mouse(start.x, start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
|
||||
editor.mouseup(pointer_state(start, MouseKeys::empty()), ModifierKeys::empty()).await;
|
||||
assert!(!is_visible(&editor), "a middle drag shouldn't toggle the layer, even if released where it was pressed");
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert!(is_visible(&editor), "one undo should revert the middle click");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
@@ -3562,7 +3506,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
|
||||
|
||||
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
||||
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
editor.handle_message(NodeGraphMessage::AddImport).await;
|
||||
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
||||
@@ -4097,30 +4041,18 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_new_subgraph_is_its_own_definition() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
|
||||
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
|
||||
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cannot_preview_node_without_outputs() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
|
||||
assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
|
||||
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
|
||||
|
||||
// Attempting to toggle preview on a node without outputs should not enable previewing
|
||||
network_interface.toggle_preview(subgraph, &[]);
|
||||
network_interface.toggle_preview(custom_node, &[]);
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||
}
|
||||
|
||||
@@ -4284,73 +4216,3 @@ async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
assert_invariants(&editor, "after grouping a group");
|
||||
}
|
||||
|
||||
fn indent_below_parent(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> Option<i32> {
|
||||
let interface = &editor.active_document().network_interface;
|
||||
let parent = layer.parent(interface.document_metadata())?;
|
||||
Some(interface.position(&parent.to_node(), &[])?.x - interface.position(&layer.to_node(), &[])?.x)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reordering_the_layers_of_a_group_keeps_them_indented_below_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
||||
for x in [0., 50., 100.] {
|
||||
editor.draw_rect(x, 0., x + 40., 40.).await;
|
||||
}
|
||||
|
||||
let artboard = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the artboard should be a layer");
|
||||
let top_two = artboard.children(editor.active_document().metadata()).take(2).map(LayerNodeIdentifier::to_node).collect();
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: top_two }).await;
|
||||
group_selected_layers(&mut editor).await;
|
||||
|
||||
let group = artboard
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the group should be the top layer of the artboard");
|
||||
for insert_index in [0, 2] {
|
||||
let moved = group.children(editor.active_document().metadata()).nth(1 - insert_index / 2).expect("the group should hold two layers");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![moved.to_node()] }).await;
|
||||
editor.handle_message(DocumentMessage::MoveSelectedLayersTo { parent: group, insert_index }).await;
|
||||
|
||||
for layer in group.children(editor.active_document().metadata()).chain([group]) {
|
||||
assert_eq!(indent_below_parent(&editor, layer), Some(LAYER_INDENT_OFFSET), "moving a layer to index {insert_index} of the group");
|
||||
}
|
||||
}
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn releasing_a_drag_of_a_layer_in_a_stack_leaves_every_layer_where_the_drag_drew_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
||||
for x in [0., 50., 100., 150.] {
|
||||
editor.draw_rect(x, 0., x + 40., 40.).await;
|
||||
}
|
||||
let artboard = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the artboard should be a layer");
|
||||
let third = artboard.children(editor.active_document().metadata()).nth(2).expect("the artboard should hold four layers");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third.to_node()] }).await;
|
||||
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let layers: Vec<NodeId> = interface.document_network().nodes.keys().copied().filter(|node_id| interface.is_layer(node_id, &[])).collect();
|
||||
for keep_upstream in [false, true] {
|
||||
for offset in [IVec2::new(0, 3), IVec2::new(0, -2), IVec2::new(5, 0)] {
|
||||
let before = interface.positions(layers.iter().copied(), &[]);
|
||||
interface.drag_selected_nodes(offset, keep_upstream, &[]);
|
||||
let dragging = interface.positions(layers.iter().copied(), &[]);
|
||||
interface.finish_drag(&[]);
|
||||
|
||||
assert_ne!(dragging, before, "dragging by {offset} keeping upstream: {keep_upstream} should move the layers");
|
||||
|
||||
assert_eq!(interface.positions(layers.iter().copied(), &[]), dragging, "dragging by {offset} keeping upstream: {keep_upstream}");
|
||||
}
|
||||
}
|
||||
}
|
||||
-14
@@ -62,21 +62,11 @@ pub enum NodeMetadataChange {
|
||||
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
|
||||
/// merge independently, so a concurrent move and a concurrent layer toggle both survive.
|
||||
NodeType(NodeTypePersistentMetadata),
|
||||
/// Where a node that stays a layer or stays a node sits. Encodes to `ui::position` alone.
|
||||
Position(NodeTypePersistentMetadata),
|
||||
DisplayName(String),
|
||||
Locked(bool),
|
||||
Pinned(bool),
|
||||
}
|
||||
|
||||
impl NodeMetadataChange {
|
||||
/// The change from `before` to `after`, writing whether the node is a layer only when that changes.
|
||||
pub fn placement(before: &NodeTypePersistentMetadata, after: NodeTypePersistentMetadata) -> Self {
|
||||
let is_layer = |node_type: &NodeTypePersistentMetadata| matches!(node_type, NodeTypePersistentMetadata::Layer(_));
|
||||
if is_layer(before) == is_layer(&after) { Self::Position(after) } else { Self::NodeType(after) }
|
||||
}
|
||||
}
|
||||
|
||||
/// One field of a network's persistent metadata. The navigation transform and width are absent
|
||||
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -329,10 +319,6 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
|
||||
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
|
||||
]
|
||||
}
|
||||
NodeMetadataChange::Position(node_type) => vec![node_attribute(
|
||||
node_attr::ui::POSITION,
|
||||
Some(serialize_attribute(node_attr::ui::POSITION, &position_from_runtime(node_type))?),
|
||||
)],
|
||||
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
|
||||
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
|
||||
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
|
||||
|
||||
+1
-28
@@ -3,7 +3,6 @@ use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange
|
||||
use super::storage_metadata::StorageMetadataView;
|
||||
use super::{InputConnector, NodeTemplate};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use document_graph_storage::attr::node as node_attr;
|
||||
use document_graph_storage::delta::compute_deltas;
|
||||
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -185,7 +184,7 @@ async fn per_field_metadata_edits_match_the_diff() {
|
||||
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
|
||||
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
|
||||
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
|
||||
metadata_change(node, NodeMetadataChange::Position(metadata.node_type_metadata.clone())),
|
||||
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())),
|
||||
EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
||||
network: None,
|
||||
node_id: node,
|
||||
@@ -284,32 +283,6 @@ async fn unchanged_writes_emit_nothing() {
|
||||
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moving_a_layer_writes_only_its_position() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 40., 40.).await;
|
||||
let layer = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the rectangle should be a layer")
|
||||
.to_node();
|
||||
|
||||
let working = convert(&editor);
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
editor.active_document_mut().network_interface.shift_node(&layer, glam::IVec2::new(3, 5), &[]);
|
||||
|
||||
let emitted = committed_deltas(&mut editor);
|
||||
let written: Vec<String> = construct(&editor, &emitted, &working)
|
||||
.into_iter()
|
||||
.filter_map(|op| match op {
|
||||
RegistryDelta::ChangeNodeAttribute { delta, .. } => Some(delta.key),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(written, [node_attr::ui::POSITION]);
|
||||
}
|
||||
|
||||
/// Structural writes go through the store too, so inserting and deleting a node must be recorded
|
||||
/// without the caller saying anything about it.
|
||||
#[tokio::test]
|
||||
|
||||
+190
-3
@@ -46,6 +46,193 @@ impl NodeNetworkInterface {
|
||||
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
|
||||
}
|
||||
|
||||
pub(crate) fn compute_node_ports(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Ports> {
|
||||
let Some(node_position) = self.position(node_id, network_path) else {
|
||||
log::error!("Could not get node position in compute_node_ports for node {node_id}");
|
||||
return None;
|
||||
};
|
||||
let document_node = self.document_node(node_id, network_path)?;
|
||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||
let mut ports = Ports::new();
|
||||
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
ports.insert_dot_ports(node_top_left + DVec2::new(0., GRID_SIZE as f64));
|
||||
} else if !self.is_layer(node_id, network_path) {
|
||||
let mut input_row_count = 0;
|
||||
for (input_index, input) in document_node.inputs.iter().enumerate() {
|
||||
if input.is_exposed() {
|
||||
ports.insert_node_input(input_index, input_row_count, node_top_left);
|
||||
}
|
||||
if input_index == 0 || input.is_exposed() {
|
||||
input_row_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
|
||||
for output_index in start_index..self.number_of_outputs(node_id, network_path) {
|
||||
ports.insert_node_output(output_index, node_top_left);
|
||||
}
|
||||
} else {
|
||||
ports.insert_layer_input(0, node_top_left);
|
||||
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
|
||||
ports.insert_layer_input(1, node_top_left);
|
||||
}
|
||||
ports.insert_layer_output(node_top_left);
|
||||
}
|
||||
|
||||
Some(ports)
|
||||
}
|
||||
|
||||
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
|
||||
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
||||
let Some(node_position) = self.position(node_id, network_path) else {
|
||||
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
|
||||
return None;
|
||||
};
|
||||
let node_metadata = self.node_metadata(node_id, network_path)?;
|
||||
let port_click_targets = self.compute_node_ports(node_id, network_path)?;
|
||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||
|
||||
// A redirect dot is centered on the grid point at the connector height of an ordinary node's first row.
|
||||
// Its body also covers the gutters beside it holding its ports, so every press near it moves the dot unless it lands on an available port.
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
const DOT_HALF_WIDTH: f64 = 15.;
|
||||
const DOT_HALF_HEIGHT: f64 = 8.;
|
||||
|
||||
let center = node_top_left + DVec2::new(0., GRID_SIZE as f64);
|
||||
let path = rounded_rectangle_path(
|
||||
center - DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
||||
center + DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
||||
[DOT_HALF_HEIGHT; 4],
|
||||
);
|
||||
|
||||
return Some(DocumentNodeClickTargets {
|
||||
node_click_target: ClickTarget::new_with_path(path, 0.),
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Node,
|
||||
});
|
||||
}
|
||||
|
||||
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
|
||||
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
|
||||
let width = 5 * GRID_SIZE;
|
||||
// Offset down by half a grid so the click target sits below the top connector strip.
|
||||
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
|
||||
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
|
||||
|
||||
let radius = 3.;
|
||||
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
|
||||
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Node,
|
||||
}
|
||||
} else {
|
||||
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
|
||||
log::error!("Could not get layer width in compute_node_click_targets");
|
||||
0
|
||||
});
|
||||
let width = layer_width_cells * GRID_SIZE;
|
||||
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
|
||||
let locked = self.is_locked(node_id, network_path);
|
||||
|
||||
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
|
||||
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
|
||||
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
|
||||
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
|
||||
|
||||
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
|
||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
|
||||
[3.; 4],
|
||||
);
|
||||
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
|
||||
let lock_click_target = if locked {
|
||||
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
|
||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
|
||||
[3.; 4],
|
||||
);
|
||||
Some(ClickTarget::new_with_path(path, 0.))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
|
||||
const GRIP_WIDTH: f64 = 8.;
|
||||
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
|
||||
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||
[0.; 4],
|
||||
);
|
||||
let grip_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
|
||||
// so the rest of the layer still drills into the subgraph on double-click
|
||||
|
||||
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
|
||||
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
|
||||
/// `.thumbnail` (70px) + its 1px side margins (= 72)
|
||||
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
|
||||
/// `.details` margin-left
|
||||
const DETAILS_LEFT_MARGIN: f64 = 8.;
|
||||
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
|
||||
/// Distance from layer's right edge to visibility's left edge (= 12)
|
||||
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
|
||||
const FONT_SIZE: f64 = 14.;
|
||||
|
||||
let display_name = self.display_name(node_id, network_path);
|
||||
let name_click_target = if display_name.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
|
||||
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
|
||||
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
|
||||
let name_width = text_width(&display_name, FONT_SIZE);
|
||||
let name_right = (name_left + name_width).min(name_right_max);
|
||||
if name_right > name_left {
|
||||
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
|
||||
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
|
||||
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
|
||||
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
|
||||
Some(ClickTarget::new_with_path(path, 0.))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// The layer click target spans the layer and its chain background
|
||||
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
|
||||
|
||||
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
|
||||
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
|
||||
const CORNER_RADIUS: f64 = 10.;
|
||||
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
|
||||
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
|
||||
visibility_click_target,
|
||||
lock_click_target,
|
||||
grip_click_target,
|
||||
name_click_target,
|
||||
})),
|
||||
}
|
||||
};
|
||||
|
||||
Some(document_node_click_targets)
|
||||
}
|
||||
|
||||
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
|
||||
/// Laid out as the frontend draws them, just past the connector.
|
||||
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
|
||||
@@ -152,9 +339,9 @@ impl NodeNetworkInterface {
|
||||
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
|
||||
}
|
||||
|
||||
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons, and the width of its name. Cached
|
||||
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached
|
||||
/// because measuring the name's text is slow.
|
||||
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
|
||||
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
|
||||
const GAP_WIDTH: f64 = 8.;
|
||||
const FONT_SIZE: f64 = 14.;
|
||||
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
|
||||
@@ -169,7 +356,7 @@ impl NodeNetworkInterface {
|
||||
let icon_overhang_width = GRID_SIZE as f64 / 2.;
|
||||
|
||||
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
|
||||
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
|
||||
((layer_width_pixels / 24.).ceil() as u32).max(8)
|
||||
}
|
||||
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
|
||||
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
|
||||
|
||||
+116
-59
@@ -24,6 +24,81 @@ impl NodeNetworkInterface {
|
||||
all_selected_nodes
|
||||
}
|
||||
|
||||
pub fn collect_frontend_click_targets(&self, network_path: &[NodeId]) -> FrontendClickTargets {
|
||||
let mut all_node_click_targets = Vec::new();
|
||||
let mut connector_click_targets = Vec::new();
|
||||
let mut icon_click_targets = Vec::new();
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in collect_frontend_click_targets");
|
||||
return FrontendClickTargets::default();
|
||||
};
|
||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
||||
self.with_import_export_ports(network_path, |import_export_click_targets| {
|
||||
for port in import_export_click_targets.click_targets() {
|
||||
if let ClickTargetType::Path(path) = port.target_type() {
|
||||
connector_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
});
|
||||
nodes.into_iter().for_each(|node_id| {
|
||||
self.with_node_click_targets(&node_id, network_path, |node_click_targets| {
|
||||
let mut node_path = String::new();
|
||||
|
||||
if let ClickTargetType::Path(path) = node_click_targets.node_click_target.target_type() {
|
||||
node_path.push_str(path.to_svg().as_str())
|
||||
}
|
||||
all_node_click_targets.push((node_id, node_path));
|
||||
for port in node_click_targets.port_click_targets.click_targets() {
|
||||
if let ClickTargetType::Path(path) = port.target_type() {
|
||||
connector_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
|
||||
// Visibility button (eye icon)
|
||||
if let ClickTargetType::Path(path) = layer_metadata.visibility_click_target.target_type() {
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
// Lock button (padlock icon), only when the layer is locked
|
||||
if let Some(lock_click_target) = &layer_metadata.lock_click_target
|
||||
&& let ClickTargetType::Path(path) = lock_click_target.target_type()
|
||||
{
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
// Drag grip (dotted symbol)
|
||||
if let ClickTargetType::Path(path) = layer_metadata.grip_click_target.target_type() {
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
let mut layer_click_targets = Vec::new();
|
||||
let mut node_click_targets = Vec::new();
|
||||
all_node_click_targets.into_iter().for_each(|(node_id, path)| {
|
||||
if self.is_layer(&node_id, network_path) {
|
||||
layer_click_targets.push(path);
|
||||
} else {
|
||||
node_click_targets.push(path);
|
||||
}
|
||||
});
|
||||
|
||||
let bounds = self.all_nodes_bounding_box(network_path).unwrap_or([DVec2::ZERO, DVec2::ZERO]);
|
||||
let all_nodes_bounding_box = rectangle_path(bounds[0], bounds[1]).to_svg();
|
||||
|
||||
let import_export_names = self
|
||||
.import_export_name_bounds(network_path)
|
||||
.into_iter()
|
||||
.map(|(_, [name_min, name_max])| rectangle_path(name_min, name_max).to_svg())
|
||||
.collect();
|
||||
FrontendClickTargets {
|
||||
node_click_targets,
|
||||
layer_click_targets,
|
||||
connector_click_targets,
|
||||
icon_click_targets,
|
||||
all_nodes_bounding_box,
|
||||
import_export_names,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) {
|
||||
self.document_metadata.document_to_viewport = transform;
|
||||
}
|
||||
@@ -48,24 +123,6 @@ impl NodeNetworkInterface {
|
||||
Some(&mut navigation.node_graph_ptz)
|
||||
}
|
||||
|
||||
/// The first of the node's parts, its body last, that `find` picks something from. Each part is given in node graph space where the node sits in its
|
||||
/// grid cell, and an input by its index rather than the row a node draws it in.
|
||||
pub(crate) fn find_node_part<R>(&self, node_id: &NodeId, network_path: &[NodeId], mut find: impl FnMut(Part, &PartTarget) -> Option<R>) -> Option<R> {
|
||||
let rows_are_inputs = self.is_layer(node_id, network_path) || self.is_redirect_dot(node_id, network_path);
|
||||
let inputs = &self.document_node(node_id, network_path)?.inputs;
|
||||
|
||||
self.with_layout(network_path, |layout| {
|
||||
layout.find_part(node_id, |target| {
|
||||
let part = match target.part {
|
||||
Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? as u32),
|
||||
part => part,
|
||||
};
|
||||
find(part, target)
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
|
||||
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
@@ -76,13 +133,16 @@ impl NodeNetworkInterface {
|
||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||
// Each node is pressed where it's drawn, even while gliding into its grid cell
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
let reaching = self.nodes_reaching(point, network_path);
|
||||
let clicked_nodes = self.with_layout(network_path, |layout| {
|
||||
reaching
|
||||
.into_iter()
|
||||
.filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id))))
|
||||
.collect::<Vec<_>>()
|
||||
})?;
|
||||
let clicked_nodes = self
|
||||
.nodes_reaching(point, network_path)
|
||||
.iter()
|
||||
.filter(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id))
|
||||
}) == Some(true)
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
|
||||
let drawing_layer = |node_id: &NodeId| {
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
@@ -105,18 +165,25 @@ impl NodeNetworkInterface {
|
||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
|
||||
let wanted = match click_target_type {
|
||||
LayerClickTargetTypes::Visibility => Part::Visibility,
|
||||
LayerClickTargetTypes::Lock => Part::Lock,
|
||||
LayerClickTargetTypes::Grip => Part::Grip,
|
||||
LayerClickTargetTypes::Name => Part::Name,
|
||||
};
|
||||
|
||||
self.nodes_reaching(point, network_path).into_iter().find(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(()))
|
||||
.is_some()
|
||||
})
|
||||
self.nodes_reaching(point, network_path)
|
||||
.iter()
|
||||
.filter_map(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata {
|
||||
match click_target_type {
|
||||
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.next()
|
||||
}
|
||||
|
||||
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
|
||||
@@ -202,11 +269,13 @@ impl NodeNetworkInterface {
|
||||
.iter()
|
||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||
.filter_map(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.find_node_part(node_id, network_path, |part, target| match part {
|
||||
Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)),
|
||||
_ => None,
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata
|
||||
.port_click_targets
|
||||
.clicked_input_port_from_point(point - glide_offsets.node(node_id))
|
||||
.map(|port| InputConnector::node_at_index(*node_id, port))
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
||||
.or_else(|| {
|
||||
@@ -233,11 +302,13 @@ impl NodeNetworkInterface {
|
||||
.iter()
|
||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||
.filter_map(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.find_node_part(node_id, network_path, |part, target| match part {
|
||||
Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)),
|
||||
_ => None,
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata
|
||||
.port_click_targets
|
||||
.clicked_output_port_from_point(point - glide_offsets.node(node_id))
|
||||
.map(|output_index| OutputConnector::node(*node_id, output_index))
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.next()
|
||||
.or_else(|| {
|
||||
@@ -355,17 +426,3 @@ impl NodeNetworkInterface {
|
||||
(layer_widths, chain_widths, has_left_input_wire)
|
||||
}
|
||||
}
|
||||
|
||||
/// The input drawn in `row` of a node, where the primary input's row is drawn even while it has no port.
|
||||
fn input_in_row(inputs: &[NodeInput], row: usize) -> Option<usize> {
|
||||
let mut current_row = 0;
|
||||
for (index, input) in inputs.iter().enumerate() {
|
||||
if input.is_exposed() && current_row == row {
|
||||
return Some(index);
|
||||
}
|
||||
if index == 0 || input.is_exposed() {
|
||||
current_row += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -6,6 +6,10 @@
|
||||
use super::*;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
pub(crate) fn invalidate_positions(&mut self, network_path: &[NodeId]) {
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
}
|
||||
|
||||
/// Unloads the network's import and export ports.
|
||||
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
|
||||
self.unload_import_export_ports(network_path);
|
||||
@@ -13,5 +17,6 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
self.try_unload_layer_width(node_id, network_path);
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
|
||||
@@ -144,6 +145,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Sets the position of a layer to a stack position
|
||||
@@ -157,6 +159,8 @@ impl NodeNetworkInterface {
|
||||
} else if node.set_stack_position(y_offset) {
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Sets the position of a node to a stack position without changing its y offset
|
||||
@@ -367,6 +371,7 @@ impl NodeNetworkInterface {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
|
||||
if node.shift_absolute_position(position - current_position) {
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+36
-158
@@ -1,9 +1,7 @@
|
||||
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
|
||||
use super::*;
|
||||
use glam::UVec2;
|
||||
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
|
||||
use std::cell::RefCell;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
const REACH_MARGIN: f64 = 16.;
|
||||
|
||||
@@ -11,53 +9,13 @@ const REACH_MARGIN: f64 = 16.;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NetworkLayout {
|
||||
revision: u64,
|
||||
generation: u64,
|
||||
node_ids: Vec<NodeId>,
|
||||
indices: HashMap<NodeId, NodeIndex>,
|
||||
graph: Graph,
|
||||
shapes: Vec<NodeShape>,
|
||||
layout: Layout,
|
||||
bounds: [DVec2; 2],
|
||||
clearance: ImportExportClearance,
|
||||
}
|
||||
|
||||
/// Counts every layout made, so whatever is derived from one can tell when it was replaced, even without a new revision.
|
||||
static LAYOUT_GENERATIONS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
impl NetworkLayout {
|
||||
fn new(revision: u64, laid_out: LaidOutNodes, graph: Graph, layout: Layout) -> Self {
|
||||
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
|
||||
let mut network_layout = Self {
|
||||
revision,
|
||||
generation: LAYOUT_GENERATIONS.fetch_add(1, Ordering::Relaxed),
|
||||
node_ids,
|
||||
indices,
|
||||
graph,
|
||||
shapes,
|
||||
layout,
|
||||
bounds: [DVec2::ZERO; 2],
|
||||
clearance: ImportExportClearance::default(),
|
||||
};
|
||||
network_layout.measure_bounds_and_clearance();
|
||||
network_layout
|
||||
}
|
||||
|
||||
fn into_parts(self) -> (LaidOutNodes, Graph, Layout) {
|
||||
let Self {
|
||||
node_ids,
|
||||
indices,
|
||||
shapes,
|
||||
graph,
|
||||
layout,
|
||||
..
|
||||
} = self;
|
||||
(LaidOutNodes { node_ids, indices, shapes }, graph, layout)
|
||||
}
|
||||
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
|
||||
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
|
||||
Some(self.node(node_id)?.position)
|
||||
}
|
||||
@@ -95,33 +53,6 @@ impl NetworkLayout {
|
||||
self.node(layer).map_or(0, |node| node.chain_length)
|
||||
}
|
||||
|
||||
/// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network.
|
||||
pub fn bounds(&self) -> [DVec2; 2] {
|
||||
self.bounds
|
||||
}
|
||||
|
||||
/// What the imports and exports keep their distance from horizontally.
|
||||
pub(crate) fn clearance(&self) -> ImportExportClearance {
|
||||
self.clearance
|
||||
}
|
||||
|
||||
/// The node's body where it sits in its grid cell, in node graph space.
|
||||
pub fn body(&self, node_id: &NodeId) -> Option<PartTarget> {
|
||||
Some(self.placed(*self.indices.get(node_id)?).body())
|
||||
}
|
||||
|
||||
/// The first of the node's parts, its body last, that `find` picks something from.
|
||||
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&PartTarget) -> Option<R>) -> Option<R> {
|
||||
let placed = self.placed(*self.indices.get(node_id)?);
|
||||
let mut found = None;
|
||||
placed.parts(|target| {
|
||||
if found.is_none() {
|
||||
found = find(&target);
|
||||
}
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Whether `point`, in node graph space, lies within the box around everything the node draws.
|
||||
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
|
||||
let Some(index) = self.indices.get(node_id) else { return false };
|
||||
@@ -131,38 +62,6 @@ impl NetworkLayout {
|
||||
point.cmpge(min).all() && point.cmplt(max).all()
|
||||
}
|
||||
|
||||
fn placed(&self, index: NodeIndex) -> PlacedNode<'_> {
|
||||
let node_layout = self.layout.node(index);
|
||||
PlacedNode {
|
||||
node: &self.graph[index],
|
||||
shape: &self.shapes[index.index()],
|
||||
position: node_layout.position,
|
||||
chain_length: node_layout.chain_length,
|
||||
}
|
||||
}
|
||||
|
||||
/// Measures the combined bounds of the node bodies, and the horizontal extents the imports and exports keep clear of, with redirect dots measured by their centers.
|
||||
fn measure_bounds_and_clearance(&mut self) {
|
||||
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
||||
|
||||
let mut bounds: Option<[DVec2; 2]> = None;
|
||||
let mut clearance = ImportExportClearance::default();
|
||||
for index in (0..self.graph.nodes.len()).map(|index| NodeIndex::from(index as u32)) {
|
||||
let body = self.placed(index).body();
|
||||
bounds = Some(bounds.map_or([body.min, body.max], |[min, max]| [min.min(body.min), max.max(body.max)]));
|
||||
|
||||
if self.graph[index].kind == NodeKind::Waypoint {
|
||||
let center = (body.min.x + body.max.x) / 2.;
|
||||
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
||||
} else {
|
||||
clearance.node_sides = widen(clearance.node_sides, body.min.x, body.max.x);
|
||||
}
|
||||
}
|
||||
|
||||
self.bounds = bounds.unwrap_or_default();
|
||||
self.clearance = clearance;
|
||||
}
|
||||
|
||||
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
|
||||
Some(self.layout.node(*self.indices.get(node_id)?))
|
||||
}
|
||||
@@ -187,14 +86,12 @@ struct DragOrigin {
|
||||
keep_upstream: bool,
|
||||
node_ids: Vec<NodeId>,
|
||||
indices: HashMap<NodeId, NodeIndex>,
|
||||
shapes: Vec<NodeShape>,
|
||||
start: Graph,
|
||||
drag: Drag,
|
||||
}
|
||||
|
||||
impl DragOrigin {
|
||||
fn new(laid_out: LaidOutNodes, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
||||
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
|
||||
fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
||||
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
|
||||
Self {
|
||||
revision,
|
||||
@@ -202,7 +99,6 @@ impl DragOrigin {
|
||||
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
|
||||
node_ids,
|
||||
indices,
|
||||
shapes,
|
||||
start,
|
||||
}
|
||||
}
|
||||
@@ -258,6 +154,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
transient.layout.unload();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
|
||||
@@ -281,14 +178,9 @@ impl NodeNetworkInterface {
|
||||
.filter(|((before, after), _)| before.placement != after.placement)
|
||||
.map(|((_, after), node_id)| (*node_id, after.placement))
|
||||
.collect();
|
||||
let laid_out = LaidOutNodes {
|
||||
node_ids: std::mem::take(&mut origin.node_ids),
|
||||
indices: std::mem::take(&mut origin.indices),
|
||||
shapes: std::mem::take(&mut origin.shapes),
|
||||
};
|
||||
(moved_placements, laid_out, moved)
|
||||
(moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved)
|
||||
});
|
||||
let Some((moved_placements, laid_out, graph)) = finished else { return };
|
||||
let Some((moved_placements, node_ids, indices, graph)) = finished else { return };
|
||||
|
||||
let mut stored_all = true;
|
||||
for (node_id, placement) in moved_placements {
|
||||
@@ -297,7 +189,13 @@ impl NodeNetworkInterface {
|
||||
|
||||
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
|
||||
let layout = Layout::new(&graph);
|
||||
network_metadata.transient_metadata.layout.store(NetworkLayout::new(store::revision(), laid_out, graph, layout));
|
||||
network_metadata.transient_metadata.layout.store(NetworkLayout {
|
||||
revision: store::revision(),
|
||||
layout,
|
||||
graph,
|
||||
node_ids,
|
||||
indices,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,15 +208,16 @@ impl NodeNetworkInterface {
|
||||
let transient = self.network_transient_mut(network_path)?;
|
||||
let drag = transient.drag.take()?;
|
||||
transient.layout.unload();
|
||||
self.invalidate_positions(network_path);
|
||||
Some(drag)
|
||||
}
|
||||
|
||||
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
|
||||
let mut origin = drag.origin.borrow_mut();
|
||||
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
|
||||
let (laid_out, start) = self.layout_graph(network_path)?;
|
||||
let (node_ids, indices, start) = self.layout_graph(network_path)?;
|
||||
let start_layout = Layout::new(&start);
|
||||
*origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
||||
*origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
||||
}
|
||||
origin.as_mut().map(read)
|
||||
}
|
||||
@@ -328,8 +227,8 @@ impl NodeNetworkInterface {
|
||||
let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
|
||||
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
|
||||
|
||||
let (laid_out, graph, layout) = cached.into_parts();
|
||||
Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision))
|
||||
let NetworkLayout { node_ids, indices, graph, layout, .. } = cached;
|
||||
Some(DragOrigin::new(node_ids, indices, graph, layout, dragged, keep_upstream, revision))
|
||||
}
|
||||
|
||||
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
|
||||
@@ -347,38 +246,40 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
if node.set_node_type(node_type) {
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
|
||||
let (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
||||
let (node_ids, indices, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
||||
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
|
||||
let (graph, mut layout) = origin.drag.moved(drag.offset);
|
||||
layout.snap_chains(&graph);
|
||||
let laid_out = LaidOutNodes {
|
||||
node_ids: origin.node_ids.clone(),
|
||||
indices: origin.indices.clone(),
|
||||
shapes: origin.shapes.clone(),
|
||||
};
|
||||
(laid_out, graph, layout)
|
||||
(origin.node_ids.clone(), origin.indices.clone(), graph, layout)
|
||||
})?,
|
||||
None => {
|
||||
let (laid_out, graph) = self.layout_graph(network_path)?;
|
||||
let (node_ids, indices, graph) = self.layout_graph(network_path)?;
|
||||
let layout = Layout::new(&graph);
|
||||
(laid_out, graph, layout)
|
||||
(node_ids, indices, graph, layout)
|
||||
}
|
||||
};
|
||||
|
||||
Some(NetworkLayout::new(revision, laid_out, graph, layout))
|
||||
Some(NetworkLayout {
|
||||
revision,
|
||||
layout,
|
||||
graph,
|
||||
node_ids,
|
||||
indices,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> {
|
||||
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, Graph)> {
|
||||
let network = self.nested_network(network_path)?;
|
||||
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
|
||||
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
|
||||
|
||||
let (nodes, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?;
|
||||
let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?;
|
||||
let wires = node_ids
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -396,10 +297,10 @@ impl NodeNetworkInterface {
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires }))
|
||||
Some((node_ids, indices, Graph { nodes, wires }))
|
||||
}
|
||||
|
||||
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> {
|
||||
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> {
|
||||
let metadata = self.node_metadata(node_id, network_path)?;
|
||||
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
|
||||
@@ -413,40 +314,17 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
|
||||
let (layer_width, name_width) = if is_layer {
|
||||
self.layer_width_and_name_width(node_id, network_path).unwrap_or_default()
|
||||
} else {
|
||||
(0, 0.)
|
||||
};
|
||||
let (kind, size) = match (is_layer, is_redirect_dot) {
|
||||
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)),
|
||||
(true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)),
|
||||
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
|
||||
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
|
||||
};
|
||||
|
||||
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
|
||||
let node = Node {
|
||||
Some(Node {
|
||||
placement,
|
||||
kind,
|
||||
size: size.as_ivec2(),
|
||||
chainable: !is_redirect_dot && !primary_output_hidden,
|
||||
chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path),
|
||||
held: false,
|
||||
};
|
||||
let shape = NodeShape {
|
||||
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
|
||||
outputs: self.number_of_outputs(node_id, network_path) as u32,
|
||||
primary_input_hidden: self.document_node(node_id, network_path)?.inputs.first().is_some_and(|input| !input.is_exposed()),
|
||||
primary_output_hidden,
|
||||
name_width,
|
||||
locked: self.is_locked(node_id, network_path),
|
||||
};
|
||||
Some((node, shape))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The nodes of a network in the order the layout indexes them, with what each draws beyond its size in the layout.
|
||||
pub(crate) struct LaidOutNodes {
|
||||
pub(crate) node_ids: Vec<NodeId>,
|
||||
pub(crate) indices: HashMap<NodeId, NodeIndex>,
|
||||
shapes: Vec<NodeShape>,
|
||||
}
|
||||
+17
-6
@@ -94,9 +94,11 @@ impl NodeNetworkInterface {
|
||||
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
|
||||
}
|
||||
|
||||
// Update the outward wires for all nodes in the encapsulating network
|
||||
// Update the outward wires and bounding box for all nodes in the encapsulating network
|
||||
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
|
||||
encapsulating_transient.outward_wires.unload();
|
||||
encapsulating_transient.all_nodes_bounding_box.unload();
|
||||
encapsulating_transient.import_export_clearance.unload();
|
||||
}
|
||||
|
||||
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
|
||||
@@ -139,6 +141,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
// Update the metadata for the encapsulating node
|
||||
self.unload_outward_wires(encapsulating_network_path);
|
||||
self.unload_all_nodes_bounding_box(encapsulating_network_path);
|
||||
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
|
||||
}
|
||||
if affects_document_structure {
|
||||
@@ -176,6 +179,7 @@ impl NodeNetworkInterface {
|
||||
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
|
||||
// Update the metadata for the encapsulating node
|
||||
self.unload_outward_wires(encapsulating_network_path);
|
||||
self.unload_all_nodes_bounding_box(encapsulating_network_path);
|
||||
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
|
||||
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
|
||||
}
|
||||
@@ -568,7 +572,8 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Lightweight version of `set_input` for bulk import operations.
|
||||
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
||||
/// or per-node cache invalidation. Call `load_structure` once after all import wiring is complete.
|
||||
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
|
||||
/// `unload_all_nodes_bounding_box` once after all import wiring is complete.
|
||||
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
|
||||
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
|
||||
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
|
||||
@@ -668,6 +673,8 @@ impl NodeNetworkInterface {
|
||||
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
|
||||
// Exposing or hiding a value input changes the node's port count
|
||||
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
|
||||
// A nested network draws its interior ports from the encapsulating node's inputs
|
||||
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
|
||||
let nested_path = [network_path, &[*node_id]].concat();
|
||||
@@ -897,6 +904,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
self.transaction_modified();
|
||||
}
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
self.unload_outward_wires(network_path);
|
||||
}
|
||||
|
||||
@@ -919,6 +927,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
|
||||
previous_entry
|
||||
}
|
||||
@@ -1083,6 +1092,7 @@ impl NodeNetworkInterface {
|
||||
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
|
||||
}
|
||||
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
|
||||
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
|
||||
return;
|
||||
@@ -1116,10 +1126,10 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
let reconnected_offset = reconnect_to_input.as_ref().and_then(NodeInput::as_node).and_then(|reconnected| {
|
||||
let offset = self.relative_offset(node_id, network_path).or_else(|| self.relative_offset(&reconnected, network_path))?;
|
||||
Some((reconnected, offset))
|
||||
});
|
||||
let reconnected_offset = reconnect_to_input
|
||||
.as_ref()
|
||||
.and_then(NodeInput::as_node)
|
||||
.and_then(|reconnected| Some((reconnected, self.relative_offset(&reconnected, network_path)?)));
|
||||
|
||||
let mut exports_fed_by_import = Vec::new();
|
||||
|
||||
@@ -1355,6 +1365,7 @@ impl NodeNetworkInterface {
|
||||
transient.layer_width.unload();
|
||||
|
||||
self.transaction_modified();
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
self.invalidate_import_export(network_path);
|
||||
self.load_structure();
|
||||
}
|
||||
|
||||
@@ -1,231 +0,0 @@
|
||||
//! The areas of a laid out node that react to the pointer, in node graph pixels. A hit test scans each node's reach, a box around
|
||||
//! everything the node draws, and builds the exact parts of only the nodes it lands in.
|
||||
|
||||
use crate::consts::{GRID_SIZE, HALF_GRID_SIZE};
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_layout::{CHAIN_WIDTH, Node, NodeKind};
|
||||
|
||||
const GRID: f64 = GRID_SIZE as f64;
|
||||
const HALF_GRID: f64 = HALF_GRID_SIZE as f64;
|
||||
/// How far a port on a node's side reaches outward, away from the node, and inward over it.
|
||||
const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
|
||||
const SIDE_PORT_INWARD_REACH: f64 = 8.;
|
||||
const SIDE_PORT_HALF_HEIGHT: f64 = 12.;
|
||||
const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||
/// A waypoint's body also covers the gutters beside it, so a press near it moves it unless it lands on a port.
|
||||
const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
|
||||
/// A waypoint's wires attach at its center but are grabbed from a round gutter on either side of it.
|
||||
const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
|
||||
const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
|
||||
const GRIP_WIDTH: f64 = 8.;
|
||||
const NAME_LEFT_OFFSET: f64 = HALF_GRID + 3. * GRID + 8.;
|
||||
|
||||
/// What a node draws beyond the size the layout gives it.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct NodeShape {
|
||||
/// How many inputs have a port, which doesn't count a hidden primary input.
|
||||
pub inputs: u32,
|
||||
pub outputs: u32,
|
||||
/// Whether a node's primary input has no port, though its row is still drawn.
|
||||
pub primary_input_hidden: bool,
|
||||
pub primary_output_hidden: bool,
|
||||
/// The width of a layer's name in pixels.
|
||||
pub name_width: f64,
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Part {
|
||||
Body,
|
||||
/// The input drawn in this grid row of a node, or a layer's stack input at 0 and side input at 1.
|
||||
Input(u32),
|
||||
Output(u32),
|
||||
Visibility,
|
||||
Lock,
|
||||
Grip,
|
||||
Name,
|
||||
}
|
||||
|
||||
/// A rounded rectangle of a node that reacts to the pointer.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PartTarget {
|
||||
pub min: DVec2,
|
||||
pub max: DVec2,
|
||||
pub corner_radius: f64,
|
||||
pub part: Part,
|
||||
}
|
||||
|
||||
impl PartTarget {
|
||||
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
|
||||
Self {
|
||||
min: center - half_size,
|
||||
max: center + half_size,
|
||||
corner_radius,
|
||||
part,
|
||||
}
|
||||
}
|
||||
|
||||
/// A port on the left side of a node, reaching further out than over the node.
|
||||
fn input_port(center: DVec2, input: u32) -> Self {
|
||||
Self {
|
||||
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||
corner_radius: 4.,
|
||||
part: Part::Input(input),
|
||||
}
|
||||
}
|
||||
|
||||
/// A port on the right side of a node, reaching further out than over the node.
|
||||
fn output_port(center: DVec2, output: u32) -> Self {
|
||||
Self {
|
||||
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||
corner_radius: 4.,
|
||||
part: Part::Output(output),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the rounded rectangle shares any area with the box from `min` to `max`.
|
||||
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
|
||||
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let radius = self.clamped_radius();
|
||||
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
|
||||
gap == DVec2::ZERO || gap.length_squared() < radius * radius
|
||||
}
|
||||
|
||||
/// Whether `point` is inside the rounded rectangle.
|
||||
pub fn contains(&self, point: DVec2) -> bool {
|
||||
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let radius = self.clamped_radius();
|
||||
let inner = point.clamp(self.min + radius, self.max - radius);
|
||||
point.distance_squared(inner) <= radius * radius
|
||||
}
|
||||
|
||||
fn clamped_radius(&self) -> f64 {
|
||||
self.corner_radius.min((self.max - self.min).min_element() / 2.)
|
||||
}
|
||||
}
|
||||
|
||||
/// A node as drawn at `position`, in grid cells, with the chain it is drawn beside if it is a layer.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PlacedNode<'a> {
|
||||
pub node: &'a Node,
|
||||
pub shape: &'a NodeShape,
|
||||
pub position: IVec2,
|
||||
pub chain_length: u32,
|
||||
}
|
||||
|
||||
impl PlacedNode<'_> {
|
||||
/// The body: a layer with its chain span, a node below its top connector strip, or the pill around a waypoint.
|
||||
pub fn body(&self) -> PartTarget {
|
||||
let top_left = self.top_left();
|
||||
let size = self.node.size.as_dvec2() * GRID;
|
||||
|
||||
match self.node.kind {
|
||||
NodeKind::Waypoint => PartTarget::around(top_left + DVec2::new(0., GRID), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
|
||||
NodeKind::Layer => PartTarget {
|
||||
min: top_left - DVec2::new(self.chain_width(), 0.),
|
||||
max: top_left + size,
|
||||
corner_radius: 10.,
|
||||
part: Part::Body,
|
||||
},
|
||||
NodeKind::Node => {
|
||||
let body_top_left = top_left + DVec2::new(0., HALF_GRID);
|
||||
PartTarget {
|
||||
min: body_top_left,
|
||||
max: body_top_left + size - DVec2::new(0., GRID),
|
||||
corner_radius: 3.,
|
||||
part: Part::Body,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls `visit` with each part, the body last.
|
||||
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
|
||||
match self.node.kind {
|
||||
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
|
||||
NodeKind::Layer => self.layer_parts(&mut visit),
|
||||
NodeKind::Node => self.node_ports(&mut visit),
|
||||
}
|
||||
visit(self.body());
|
||||
}
|
||||
|
||||
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||
let center = self.top_left() + DVec2::new(0., GRID);
|
||||
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
|
||||
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
|
||||
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
|
||||
}
|
||||
|
||||
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||
let top_left = self.top_left();
|
||||
let width = self.node.size.x as f64 * GRID;
|
||||
let row_center = |row: u32| GRID * (row as f64 + 1.);
|
||||
|
||||
let first_input_row = u32::from(self.shape.primary_input_hidden);
|
||||
for row in first_input_row..first_input_row + self.shape.inputs {
|
||||
visit(PartTarget::input_port(top_left + DVec2::new(0., row_center(row)), row));
|
||||
}
|
||||
for output in u32::from(self.shape.primary_output_hidden)..self.shape.outputs {
|
||||
visit(PartTarget::output_port(top_left + DVec2::new(width, row_center(output)), output));
|
||||
}
|
||||
}
|
||||
|
||||
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||
let top_left = self.top_left();
|
||||
let size = self.node.size.as_dvec2() * GRID;
|
||||
|
||||
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, size.y + 8.), STACK_PORT_HALF_SIZE, 4., Part::Input(0)));
|
||||
if self.has_side_input() {
|
||||
visit(PartTarget::input_port(top_left + DVec2::new(0., GRID), 1));
|
||||
}
|
||||
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, -8.), STACK_PORT_HALF_SIZE, 4., Part::Output(0)));
|
||||
|
||||
let icon_half_size = DVec2::splat(HALF_GRID);
|
||||
visit(PartTarget::around(top_left + DVec2::new(size.x, GRID), icon_half_size, 3., Part::Visibility));
|
||||
if self.shape.locked {
|
||||
visit(PartTarget::around(top_left + DVec2::new(size.x - GRID, GRID), icon_half_size, 3., Part::Lock));
|
||||
}
|
||||
|
||||
let icons_width = if self.shape.locked { GRID } else { 0. };
|
||||
let grip_right = top_left.x + size.x - HALF_GRID - icons_width;
|
||||
let handle_top = top_left.y + HALF_GRID;
|
||||
let handle_bottom = top_left.y + GRID + HALF_GRID;
|
||||
visit(PartTarget {
|
||||
min: DVec2::new(grip_right - GRIP_WIDTH, handle_top),
|
||||
max: DVec2::new(grip_right, handle_bottom),
|
||||
corner_radius: 0.,
|
||||
part: Part::Grip,
|
||||
});
|
||||
|
||||
let name_left = top_left.x + NAME_LEFT_OFFSET;
|
||||
let name_right = (name_left + self.shape.name_width).min(grip_right - GRIP_WIDTH);
|
||||
if name_right > name_left {
|
||||
visit(PartTarget {
|
||||
min: DVec2::new(name_left, handle_top),
|
||||
max: DVec2::new(name_right, handle_bottom),
|
||||
corner_radius: 3.,
|
||||
part: Part::Name,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn top_left(&self) -> DVec2 {
|
||||
self.position.as_dvec2() * GRID
|
||||
}
|
||||
|
||||
fn has_side_input(&self) -> bool {
|
||||
self.shape.inputs > 1
|
||||
}
|
||||
|
||||
fn chain_width(&self) -> f64 {
|
||||
if self.has_side_input() { (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID } else { 0. }
|
||||
}
|
||||
}
|
||||
@@ -802,7 +802,7 @@ impl NodeNetworkInterface {
|
||||
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
||||
}
|
||||
|
||||
/// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
|
||||
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
|
||||
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
||||
self.reference(node_id, network_path)
|
||||
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
||||
@@ -875,16 +875,16 @@ impl NodeNetworkInterface {
|
||||
node.set_widget_override(index, widget_override);
|
||||
}
|
||||
|
||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
|
||||
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
||||
.unwrap_or_else(|| "Subgraph".to_string())
|
||||
.unwrap_or_else(|| "Custom Node".to_string())
|
||||
}
|
||||
|
||||
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
||||
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
||||
.unwrap_or_else(|| "Subgraph".to_string())
|
||||
.unwrap_or_else(|| "Custom Node".to_string())
|
||||
}
|
||||
|
||||
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
|
||||
@@ -328,10 +328,7 @@ fn field_deltas(
|
||||
}
|
||||
|
||||
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
||||
deltas.push(metadata(NodeMetadataChange::placement(
|
||||
¤t_metadata.node_type_metadata,
|
||||
target_metadata.node_type_metadata.clone(),
|
||||
)));
|
||||
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
|
||||
}
|
||||
if current_metadata.display_name != target_metadata.display_name {
|
||||
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
||||
|
||||
+6
-7
@@ -229,14 +229,13 @@ impl NodeMut<'_> {
|
||||
|
||||
/// Whether the node is displayed as a layer or a node, together with its position.
|
||||
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
|
||||
if self.metadata.node_type_metadata == node_type {
|
||||
return false;
|
||||
}
|
||||
|
||||
let change = NodeMetadataChange::placement(&self.metadata.node_type_metadata, node_type.clone());
|
||||
let changed = self.metadata.node_type_metadata != node_type;
|
||||
self.metadata.node_type_metadata = node_type;
|
||||
self.deltas.metadata(change);
|
||||
true
|
||||
if changed {
|
||||
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
|
||||
self.deltas.metadata(change);
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.
|
||||
|
||||
@@ -200,11 +200,10 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||
}
|
||||
|
||||
/// Update how far each layer's effects paint past its content, and the frames they paint anywhere in.
|
||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>, new_layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>) {
|
||||
/// 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.mark_changed();
|
||||
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
||||
self.document_metadata.layer_effects_frames = new_layer_effects_frames;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,14 +38,6 @@ pub struct NodeTemplate {
|
||||
}
|
||||
|
||||
impl NodeTemplate {
|
||||
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
|
||||
pub fn empty_subgraph() -> Self {
|
||||
Self {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
||||
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
||||
self.inputs.get(P::INDEX)
|
||||
|
||||
@@ -3,7 +3,12 @@ use graphene_std::ParameterRef;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||
|
||||
/// An axis-aligned rectangle spanning the two opposite corners, with per-corner radii ordered top left, top right, bottom right, bottom left.
|
||||
/// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets.
|
||||
pub fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(DEFAULT_ACCURACY)
|
||||
}
|
||||
|
||||
/// Same as [`rectangle_path`] but with per-corner radii ordered top left, top right, bottom right, bottom left.
|
||||
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
|
||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||
if radii.iter().all(|radius| *radius == 0.) {
|
||||
@@ -14,6 +19,16 @@ pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -
|
||||
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
|
||||
}
|
||||
|
||||
/// Ellipse inscribed in the box spanning the two opposite corners.
|
||||
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
|
||||
|
||||
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
|
||||
path.close_path();
|
||||
path
|
||||
}
|
||||
|
||||
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ChainNodeCopy {
|
||||
@@ -277,6 +292,13 @@ pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
|
||||
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
|
||||
}
|
||||
|
||||
/// The corners of the click target for a layer's top output or bottom input, which reaches only 8 px toward the connector it faces in a stack.
|
||||
fn stack_port_bounds(center: DVec2) -> [DVec2; 2] {
|
||||
const HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||
|
||||
[center - HALF_SIZE, center + HALF_SIZE]
|
||||
}
|
||||
|
||||
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
|
||||
const CORNER_RADIUS: f64 = 4.;
|
||||
|
||||
@@ -310,6 +332,13 @@ impl Ports {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn click_targets(&self) -> impl Iterator<Item = &ClickTarget> {
|
||||
self.input_ports
|
||||
.iter()
|
||||
.map(|(_, click_target)| click_target)
|
||||
.chain(self.output_ports.iter().map(|(_, click_target)| click_target))
|
||||
}
|
||||
|
||||
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
|
||||
self.input_ports.iter()
|
||||
}
|
||||
@@ -319,15 +348,51 @@ impl Ports {
|
||||
}
|
||||
|
||||
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
||||
self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true))));
|
||||
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true)));
|
||||
self.input_anchors.push((input_index, center));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
|
||||
self.input_ports.push((input_index, click_target));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
|
||||
self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false))));
|
||||
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false)));
|
||||
self.output_anchors.push((output_index, center));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
|
||||
self.output_ports.push((output_index, click_target));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_node_input(&mut self, input_index: usize, row_index: usize, node_top_left: DVec2) {
|
||||
// The center of the click target is always 24 px down from the top left corner of the node
|
||||
let center = node_top_left + DVec2::new(0., 24. + 24. * row_index as f64);
|
||||
self.insert_input_port_at_center(input_index, center);
|
||||
}
|
||||
|
||||
pub(crate) fn insert_node_output(&mut self, output_index: usize, node_top_left: DVec2) {
|
||||
// The center of the click target is always 24 px down from the top left corner of the node
|
||||
let center = node_top_left + DVec2::new(5. * 24., 24. + 24. * output_index as f64);
|
||||
self.insert_output_port_at_center(output_index, center);
|
||||
}
|
||||
|
||||
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
|
||||
// The primary input sits beneath the layer's thumbnail, and the secondary input on its left side
|
||||
if input_index == 0 {
|
||||
let center = node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.);
|
||||
self.insert_custom_input_port(input_index, port_click_target(stack_port_bounds(center)));
|
||||
} else {
|
||||
self.insert_input_port_at_center(input_index, node_top_left + DVec2::new(0., 24. * 1.));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
|
||||
// The center of the click target is 8 px above the layer, over its thumbnail
|
||||
let center = node_top_left + DVec2::new(2. * 24., -8.);
|
||||
self.insert_custom_output_port(0, port_click_target(stack_port_bounds(center)));
|
||||
}
|
||||
|
||||
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
|
||||
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||
}
|
||||
@@ -336,12 +401,37 @@ impl Ports {
|
||||
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||
}
|
||||
|
||||
/// Adds the input and output of a redirect dot. Its wires both attach at its center, but they're grabbed from the gutters on either side of its body.
|
||||
pub(crate) fn insert_dot_ports(&mut self, center: DVec2) {
|
||||
const GUTTER_OFFSET: f64 = 10.;
|
||||
const GUTTER_RADIUS: f64 = 5.;
|
||||
|
||||
let gutter = |x_offset: f64| {
|
||||
let gutter_center = center + DVec2::new(x_offset, 0.);
|
||||
ClickTarget::new_with_path(ellipse_path(gutter_center - DVec2::splat(GUTTER_RADIUS), gutter_center + DVec2::splat(GUTTER_RADIUS)), 0.)
|
||||
};
|
||||
self.insert_custom_input_port(0, gutter(-GUTTER_OFFSET));
|
||||
self.insert_custom_output_port(0, gutter(GUTTER_OFFSET));
|
||||
self.input_anchors.push((0, center));
|
||||
self.output_anchors.push((0, center));
|
||||
}
|
||||
|
||||
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
|
||||
self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
||||
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||
return Some(*anchor);
|
||||
}
|
||||
self.input_ports
|
||||
.iter()
|
||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||
}
|
||||
|
||||
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
|
||||
self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
||||
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||
return Some(*anchor);
|
||||
}
|
||||
self.output_ports
|
||||
.iter()
|
||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -657,12 +747,16 @@ impl<T> TransientCache<T> {
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct NodeNetworkTransientMetadata {
|
||||
pub selected_nodes: SelectedNodes,
|
||||
/// Cache for the bounding box around all nodes in node graph space.
|
||||
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
|
||||
/// Cache for what the imports and exports keep their distance from, unloaded along with `all_nodes_bounding_box`.
|
||||
pub(crate) import_export_clearance: TransientCache<ImportExportClearance>,
|
||||
/// Cache for all outward wire connections
|
||||
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
|
||||
pub(crate) layout: TransientCache<NetworkLayout>,
|
||||
pub(crate) drag: Option<super::layout_pass::DragPreview>,
|
||||
/// The import and export connector click targets, with the generation of the layout they were placed by.
|
||||
pub(crate) import_export_ports: TransientCache<(u64, Ports)>,
|
||||
/// All export connector click targets
|
||||
pub(crate) import_export_ports: TransientCache<Ports>,
|
||||
|
||||
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
|
||||
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
|
||||
@@ -1079,8 +1173,40 @@ impl From<LegacyNodePosition> for NodePosition {
|
||||
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct DocumentNodeTransientMetadata {
|
||||
/// Width in grid units from the left edge of the layer's thumbnail to its left end, and the measured width of its name, cached since text measurement is slow. Only loaded for layers.
|
||||
pub(crate) layer_width: TransientCache<(u32, f64)>,
|
||||
/// Width in grid units from the left edge of the layer's thumbnail to its left end, cached since text measurement is slow. Only loaded for layers.
|
||||
pub(crate) layer_width: TransientCache<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DocumentNodeClickTargets {
|
||||
/// In order to keep the displayed position of the node in sync with the click target, the displayed position of a node is derived from the top left of the click target
|
||||
/// Ensure node_click_target is kept in sync when modifying a node property that changes its size. Currently this is alias, inputs, is_layer, and metadata
|
||||
pub node_click_target: ClickTarget,
|
||||
/// Stores all port click targets in node graph space.
|
||||
pub port_click_targets: Ports,
|
||||
// Click targets that are specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
|
||||
pub node_type_metadata: NodeTypeClickTargets,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NodeTypeClickTargets {
|
||||
Layer(Box<LayerClickTargets>),
|
||||
Node, // No transient click targets are stored exclusively for nodes
|
||||
}
|
||||
|
||||
/// All fields in TransientLayerMetadata should automatically be updated by using the network interface API
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LayerClickTargets {
|
||||
/// Cache for all visibility buttons. Should be automatically updated when update_click_target is called
|
||||
pub visibility_click_target: ClickTarget,
|
||||
/// Cache for the lock icon button, only present when the layer is locked.
|
||||
pub lock_click_target: Option<ClickTarget>,
|
||||
/// Cache for the grip icon, which is next to the visibility button.
|
||||
pub grip_click_target: ClickTarget,
|
||||
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
|
||||
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
|
||||
/// `None` for layers whose display name is empty.
|
||||
pub name_click_target: Option<ClickTarget>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
|
||||
@@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|identifier| identifier.implementation_name_from_identifier())
|
||||
.unwrap_or("Subgraph".to_string())
|
||||
.unwrap_or("Custom Node".to_string())
|
||||
}
|
||||
|
||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
|
||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
|
||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, Point, Shape};
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
@@ -125,27 +125,23 @@ fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -
|
||||
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
|
||||
}
|
||||
|
||||
/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the
|
||||
/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
|
||||
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
|
||||
/// The center line that cleaves a thick layer-stack wire. Its ends reach past the wire (1.5px toward the output
|
||||
/// connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
|
||||
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> BezPath {
|
||||
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
|
||||
return BezPath::new();
|
||||
}
|
||||
|
||||
let wire = build_vector_wire(output_position, input_position, true, true, graph_wire_style);
|
||||
let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else {
|
||||
return BezPath::new();
|
||||
};
|
||||
|
||||
// The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead
|
||||
// The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots
|
||||
let sign = (input_position.y - output_position.y).signum();
|
||||
let output_trim = 1.5;
|
||||
let input_trim = 1.;
|
||||
let start = output_position + DVec2::new(0., output_trim * sign);
|
||||
let end = input_position - DVec2::new(0., input_trim * sign);
|
||||
|
||||
let mut center_line = BezPath::new();
|
||||
center_line.move_to(start - Vec2::new(0., 1.5 * sign));
|
||||
center_line.line_to(start);
|
||||
for element in wire.elements().iter().skip(1) {
|
||||
center_line.push(*element);
|
||||
}
|
||||
center_line.line_to(end + Vec2::new(0., 2. * sign));
|
||||
center_line.move_to(dvec2_to_point(start));
|
||||
center_line.line_to(dvec2_to_point(end));
|
||||
center_line
|
||||
}
|
||||
|
||||
@@ -584,7 +580,7 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use kurbo::{Affine, ParamCurveNearest};
|
||||
use kurbo::{Affine, Vec2};
|
||||
|
||||
#[test]
|
||||
fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() {
|
||||
@@ -607,30 +603,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_center_line_of_a_stack_wire_runs_inside_it() {
|
||||
let ends = [
|
||||
(DVec2::new(48., 12.), DVec2::new(48., 84.)),
|
||||
(DVec2::new(240., 12.), DVec2::new(48., 132.)),
|
||||
(DVec2::new(48., 0.), DVec2::new(0., 27.)),
|
||||
];
|
||||
let half_wire_width = 4.;
|
||||
|
||||
for (output, input) in ends {
|
||||
for style in [GraphWireStyle::Direct, GraphWireStyle::GridAligned] {
|
||||
let wire = build_vector_wire(output, input, true, true, style);
|
||||
let center_line = build_thick_wire_center_line(output, input, true, true, style);
|
||||
|
||||
let samples = center_line.segments().flat_map(|segment| (0..=10).map(move |step| segment.eval(f64::from(step) / 10.)));
|
||||
for sample in samples {
|
||||
let distance = wire
|
||||
.segments()
|
||||
.map(|segment| segment.nearest(sample, DEFAULT_ACCURACY).distance_sq.sqrt())
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
assert!(distance <= half_wire_width, "the center line from {output} to {input} drawn {style:?} leaves its wire at {sample:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -181,6 +181,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphic_nodes::graphic::ExtractElementNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::read_attribute_gradient_form::IDENTIFIER,
|
||||
aliases: &["graphic_nodes::graphic::ReadAttributeGradientTypeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
|
||||
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
|
||||
@@ -297,6 +301,10 @@ 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"],
|
||||
@@ -531,9 +539,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ChannelMixerNode",
|
||||
],
|
||||
},
|
||||
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
|
||||
NodeReplacement {
|
||||
node: graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::ColorOverlayNode",
|
||||
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
|
||||
@@ -541,7 +548,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::adjustments::ColorOverlayNode",
|
||||
"raster_nodes::generate_curves::ColorOverlayNode",
|
||||
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
"raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -646,13 +652,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_raster_nodes::std_nodes::MandelbrotNode", "graphene_std::raster::MandelbrotNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::blending_nodes::masks::mask::IDENTIFIER,
|
||||
aliases: &[
|
||||
"raster_nodes::std_nodes::MaskNode",
|
||||
"graphene_raster_nodes::std_nodes::MaskNode",
|
||||
"graphene_std::raster::MaskNode",
|
||||
"graphene_std::raster::MaskImageNode",
|
||||
],
|
||||
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::posterize::IDENTIFIER,
|
||||
@@ -1279,15 +1280,12 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if *new == graphene_std::vector::weld::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Merge by Distance");
|
||||
}
|
||||
if *new == graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
|
||||
// Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
||||
// Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
||||
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
|
||||
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
|
||||
.network_interface
|
||||
@@ -1681,52 +1679,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Gradient Form" node was replaced by "Gradient Curvature", with its two curvatures taking 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)) => GradientForm::Radial.curvatures(),
|
||||
Some(TaggedValue::GradientForm(GradientForm::Linear)) => GradientForm::Linear.curvatures(),
|
||||
_ => {
|
||||
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
|
||||
GradientForm::Linear.curvatures()
|
||||
}
|
||||
};
|
||||
|
||||
// The curvatures stay shown in the graph where an exposed or wired form was
|
||||
let exposed = old_inputs.get(1).is_some_and(NodeInput::is_exposed);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), exposed), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), exposed), 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";
|
||||
@@ -1809,8 +1761,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
})
|
||||
.collect();
|
||||
|
||||
migrate_custom_node_subgraphs(document);
|
||||
|
||||
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
|
||||
let nodes = document
|
||||
.network_interface
|
||||
@@ -1939,13 +1889,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
continue;
|
||||
};
|
||||
|
||||
// The primary input comes before the Clip toggle where there is one, and the noise settings follow it in the current inputs' order
|
||||
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
|
||||
if let Some(clip_index) = clip_index {
|
||||
if *clip_index == 1
|
||||
&& let Some(primary) = old_inputs.first()
|
||||
{
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), primary.clone(), network_path);
|
||||
}
|
||||
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
|
||||
}
|
||||
@@ -1957,11 +1902,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
|
||||
move_mandelbrot_to_old_origin(document, node_id, network_path);
|
||||
}
|
||||
|
||||
// Only a Noise Pattern old enough to have the Clip toggle is surely from before it wrote gamma-encoded grays
|
||||
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
|
||||
read_noise_through_gamma_correction(document, node_id, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||
@@ -2034,9 +1974,6 @@ fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
if downstream_consumers.is_empty() {
|
||||
return Some(());
|
||||
}
|
||||
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
|
||||
|
||||
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
|
||||
@@ -2138,48 +2075,6 @@ fn move_mandelbrot_to_old_origin(document: &mut DocumentMessageHandler, mandelbr
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Keeps an old Noise Pattern's look now that it writes its value as the gray at that gamma-encoded level rather than as linear light,
|
||||
/// with a Gamma Correction at its default gamma of 2.2 turning the new gray back into about the old one wherever the pattern was read.
|
||||
fn read_noise_through_gamma_correction(document: &mut DocumentMessageHandler, noise_node_id: &NodeId, network_path: &[NodeId]) -> Option<()> {
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*noise_node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
if downstream_consumers.is_empty() {
|
||||
return Some(());
|
||||
}
|
||||
let was_in_chain = document.network_interface.is_chain(noise_node_id, network_path);
|
||||
let position = document.network_interface.position(noise_node_id, network_path);
|
||||
|
||||
let gamma_correction_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER))?.default_node_template();
|
||||
let gamma_correction_id = NodeId::new();
|
||||
document.network_interface.insert_node(gamma_correction_id, gamma_correction_template, network_path);
|
||||
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(gamma_correction_id, 0), NodeInput::node(*noise_node_id, 0), network_path);
|
||||
for consumer in &downstream_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(gamma_correction_id, 0), network_path);
|
||||
}
|
||||
|
||||
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
|
||||
if !document.network_interface.is_visible(noise_node_id, network_path) {
|
||||
document.network_interface.set_visibility(&gamma_correction_id, network_path, false);
|
||||
}
|
||||
|
||||
// The Gamma Correction takes the pattern's place, and the pattern moves before it
|
||||
if was_in_chain {
|
||||
document.network_interface.force_set_upstream_to_chain(&gamma_correction_id, network_path);
|
||||
} else if let Some(position) = position {
|
||||
document.network_interface.set_absolute_position(&gamma_correction_id, position, network_path);
|
||||
document.network_interface.set_absolute_position(noise_node_id, position + IVec2::new(-7, 0), network_path);
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -2306,18 +2201,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 3;
|
||||
}
|
||||
|
||||
// 'Mask' gained its mode, density, feather, and invert inputs when it learned to mask any graphic, which take the definition's defaults
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::masks::mask::IDENTIFIER) && inputs_count == 2 {
|
||||
let definition = resolve_document_node_type(&reference)?;
|
||||
let mut template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
|
||||
for (index, input) in old_inputs.into_iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
inputs_count = 6;
|
||||
}
|
||||
|
||||
// Split the legacy combined "Blending" node into a chain of separate Blend Mode, Opacity (now also covers fill), and Clip nodes.
|
||||
// `NODE_REPLACEMENTS` rewrites the old `Blending` proto identifier (and its older aliases) to `blend_mode::IDENTIFIER`, so a leftover
|
||||
// 5-input shape on a Blend Mode node identifies an old Blending node that still needs structural splitting. Sub-nodes whose values
|
||||
@@ -2487,44 +2370,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 5;
|
||||
}
|
||||
|
||||
// 'Drop Shadow', 'Inner Shadow', and 'Outer Glow' gained a blend mode after their color, set to Normal to keep compositing them as before
|
||||
use graphene_std::blending_nodes::effects::{drop_shadow, inner_shadow, outer_glow};
|
||||
let lacks_blend_mode = |identifier: ProtoNodeIdentifier, count: usize| reference == DefinitionIdentifier::ProtoNode(identifier) && inputs_count == count;
|
||||
if lacks_blend_mode(drop_shadow::IDENTIFIER, 8) || lacks_blend_mode(inner_shadow::IDENTIFIER, 7) || lacks_blend_mode(outer_glow::IDENTIFIER, 7) {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for (index, input) in old_inputs.into_iter().enumerate() {
|
||||
let index = if index < 2 { index } else { index + 1 };
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
let normal = NodeInput::value(TaggedValue::BlendMode(graphene_std::blending::BlendMode::Normal), false);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), normal, network_path);
|
||||
|
||||
inputs_count += 1;
|
||||
}
|
||||
|
||||
// 'Outer Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth
|
||||
if reference == DefinitionIdentifier::ProtoNode(outer_glow::IDENTIFIER) && inputs_count == 8 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for (index, input) in old_inputs.into_iter().take(8).enumerate() {
|
||||
let index = if index == 7 { 10 } else { index };
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
let smooth = [TaggedValue::Number(0.), TaggedValue::Number(0.), TaggedValue::Integer(0)];
|
||||
for (index, value) in (7..).zip(smooth) {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(value, false), network_path);
|
||||
}
|
||||
|
||||
inputs_count = 11;
|
||||
}
|
||||
|
||||
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
|
||||
// 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_form, _has_transform, _transform).
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
|
||||
@@ -2532,18 +2377,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
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)?;
|
||||
|
||||
// The 7-input shape's own gradient metadata defaults, which the steps after this one read until the legacy fill's values replace them below
|
||||
let metadata_defaults = [
|
||||
TaggedValue::GradientForm(GradientForm::Linear),
|
||||
TaggedValue::Bool(false),
|
||||
TaggedValue::DAffine2(glam::DAffine2::IDENTITY),
|
||||
];
|
||||
for (index, value) in (4..).zip(metadata_defaults) {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(value, false), network_path);
|
||||
}
|
||||
|
||||
// Content: no change
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
|
||||
@@ -2687,11 +2520,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 7;
|
||||
}
|
||||
|
||||
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field. The modern shape is also 8 inputs,
|
||||
// so this era is told apart by its form at 4 or its spread at 5, either of which may be wired, where the modern shape holds curvatures.
|
||||
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
|
||||
let is_spread_method_fill = inputs_count == 8 && (matches!(value_at(4), Some(TaggedValue::GradientForm(_))) || matches!(value_at(5), Some(TaggedValue::GradientSpread(_))));
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && is_spread_method_fill {
|
||||
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 8 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
@@ -2714,36 +2544,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 7;
|
||||
}
|
||||
|
||||
// The Fill node gives its gradient paint the curvatures of a form in place of its `_gradient_form` input, and they stay shown in the graph where the form was
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 7 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
// Content, paint, and backups keep their places, and the transform inputs move past the second curvature
|
||||
for (index, input) in old_inputs.iter().enumerate().take(7) {
|
||||
let index = match index {
|
||||
4 => continue,
|
||||
5.. => index + 1,
|
||||
_ => index,
|
||||
};
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
|
||||
let form = old_inputs.get(4);
|
||||
let curvatures = match form.and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::GradientForm(form)) => form.curvatures(),
|
||||
_ => GradientForm::Linear.curvatures(),
|
||||
};
|
||||
let exposed = form.is_some_and(NodeInput::is_exposed);
|
||||
for (index, curvature) in (4..).zip(curvatures) {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(TaggedValue::Number(curvature), exposed), network_path);
|
||||
}
|
||||
|
||||
inputs_count = 8;
|
||||
}
|
||||
|
||||
// Upgrade Stroke node to reorder parameters and add "Align" (#2644)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -2804,6 +2604,7 @@ 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()) {
|
||||
@@ -3148,18 +2949,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 3;
|
||||
}
|
||||
|
||||
// Make Opaque gained a Strength input, set to 100% to keep making the content fully opaque
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::make_opaque::IDENTIFIER) && inputs_count == 1 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(100.), false), network_path);
|
||||
inputs_count = 2;
|
||||
}
|
||||
|
||||
// The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -4199,20 +3988,6 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
}
|
||||
}
|
||||
|
||||
// The removed Read Attribute Gradient Form node, under either of its names, degrades to a passthrough of its content
|
||||
if let Some(DefinitionIdentifier::ProtoNode(identifier)) = document.network_interface.reference(node_id, network_path)
|
||||
&& ["::ReadAttributeGradientFormNode", "::ReadAttributeGradientTypeNode"]
|
||||
.iter()
|
||||
.any(|name| identifier.as_str().ends_with(name))
|
||||
{
|
||||
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)?;
|
||||
if let Some(content) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), content.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// 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",
|
||||
@@ -4231,25 +4006,6 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button.
|
||||
/// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed.
|
||||
fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) {
|
||||
let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into()));
|
||||
let subgraphs: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node)
|
||||
.map(|(node_id, _, path)| (*node_id, path))
|
||||
.collect();
|
||||
|
||||
for (node_id, network_path) in subgraphs {
|
||||
reset_default_display_name(document, &node_id, &network_path, "Custom Node");
|
||||
reset_default_display_name(document, &node_id, &network_path, "Untitled Node");
|
||||
document.network_interface.set_reference(&node_id, &network_path, None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
||||
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
||||
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
@@ -4802,45 +4558,6 @@ mod tests {
|
||||
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let from_catalog = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let document = editor.active_document_mut();
|
||||
let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else {
|
||||
panic!("the subgraph should name a definitions table entry")
|
||||
};
|
||||
|
||||
// A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made
|
||||
let from_merging = NodeId::new();
|
||||
let instance = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Definition(shared),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(from_merging, instance, &[]);
|
||||
document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into()));
|
||||
document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]);
|
||||
document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]);
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
for node_id in [from_catalog, from_merging] {
|
||||
assert!(
|
||||
matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))),
|
||||
"the subgraph should still exist"
|
||||
);
|
||||
assert_eq!(interface.reference(&node_id, &[]), None);
|
||||
assert_eq!(interface.display_name(&node_id, &[]), "Subgraph");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_rasterize_node_on_the_export_compiles() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
@@ -4975,40 +4692,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// Read Attribute Gradient Form, under either of its names, opens as a passthrough of its content
|
||||
#[test]
|
||||
fn read_attribute_gradient_form_opens_as_a_passthrough() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let content = NodeInput::value(TaggedValue::Color(Color::RED), false);
|
||||
let name = NodeInput::value(TaggedValue::String("gradient_form".into()), false);
|
||||
let identifiers = ["graphic_nodes::graphic::ReadAttributeGradientFormNode", "graphic_nodes::graphic::ReadAttributeGradientTypeNode"];
|
||||
|
||||
let nodes = identifiers
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, &identifier)| {
|
||||
let node_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![content.clone(), name.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
(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");
|
||||
for (index, identifier) in identifiers.iter().enumerate() {
|
||||
let node = opened.network_interface.document_node(&NodeId(index as u64), &[]).expect("the node should still exist");
|
||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), "{identifier}");
|
||||
assert_eq!(node.inputs, [content.clone()], "{identifier}");
|
||||
}
|
||||
}
|
||||
|
||||
// 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() {
|
||||
@@ -5571,204 +5254,6 @@ mod tests {
|
||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_form_nodes_become_gradient_curvature_presets() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
|
||||
// Curvatures stay shown in the graph where an exposed form was
|
||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
||||
for (identifier, form, curvatures, exposed) in [
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], false),
|
||||
("math_nodes::GradientTypeNode", GradientForm::Linear, [0., 0.], false),
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], true),
|
||||
] {
|
||||
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), exposed), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&form_id];
|
||||
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
|
||||
|
||||
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(
|
||||
[curvature(1), curvature(2)],
|
||||
curvatures.map(|curvature| Some(TaggedValue::Number(curvature))),
|
||||
"{form:?} should become its curvature presets"
|
||||
);
|
||||
assert_eq!(
|
||||
[1, 2].map(|index| node.inputs[index].is_exposed()),
|
||||
[exposed; 2],
|
||||
"{form:?} exposed {exposed} should leave its curvatures so"
|
||||
);
|
||||
assert_eq!(node.inputs.len(), 3, "{form:?} should take the curvature node's gradient and two curvatures");
|
||||
}
|
||||
}
|
||||
|
||||
// An eight-input Fill from when the spread was an input of its own, here wired, opens with its form's curvatures and keeps its placement
|
||||
#[test]
|
||||
fn eight_input_fills_with_a_wired_spread_take_their_form_as_curvatures() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use glam::DAffine2;
|
||||
|
||||
let (source_id, fill_id) = (NodeId(1), NodeId(2));
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
|
||||
let ramp = || NodeInput::value(TaggedValue::GradientRamp(GradientRamp::default()), false);
|
||||
let old_inputs = vec![
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
ramp(),
|
||||
NodeInput::value(TaggedValue::Color(Color::BLACK), false),
|
||||
ramp(),
|
||||
NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false),
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
NodeInput::value(TaggedValue::DAffine2(placement), false),
|
||||
];
|
||||
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let source = NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(source_id, source, &[]);
|
||||
let fill = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::vector::fill::IDENTIFIER),
|
||||
inputs: old_inputs,
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(fill_id, fill, &[]);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(fill_id, 5), NodeInput::node(source_id, 0), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&fill_id];
|
||||
let values: Vec<_> = node.inputs[4..].iter().map(|input| input.as_value().cloned()).collect();
|
||||
let expected = [TaggedValue::Number(-1.), TaggedValue::Number(0.5), TaggedValue::Bool(true), TaggedValue::DAffine2(placement)].map(Some);
|
||||
assert_eq!(values, expected, "the form should become its curvatures before the placement");
|
||||
}
|
||||
|
||||
// A Fill that held the radial form in its input before the transform ones opens with that form's curvatures, painting as a Fill given the form now does
|
||||
#[tokio::test]
|
||||
async fn fills_of_the_radial_form_paint_the_same_once_migrated() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graphene_std::graphic::extend;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::vector::fill;
|
||||
use graphene_std::vector::style::Gradient;
|
||||
use graphene_std::vector_types::gradient_standard::GradientShape;
|
||||
use graphene_std::{Appearance, Cover, Graphic};
|
||||
|
||||
// The SVG of the document's one layer, its IDs numbered by their order of appearance, and the shape the CPU samples its fill's gradient as
|
||||
async fn painted(editor: &mut EditorTestUtils) -> (String, Option<GradientShape>) {
|
||||
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
||||
let layer = instrumented
|
||||
.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime)
|
||||
.next()
|
||||
.expect("the layer is extended onto the root");
|
||||
|
||||
let mut render = SvgRender::new();
|
||||
layer.element().render_svg(&mut render, &RenderParams::default());
|
||||
let mut markup = format!("{}{}", render.svg_defs, render.svg.to_svg_string());
|
||||
let mut index = 0;
|
||||
while let Some(found) = markup.find(r#"id=""#) {
|
||||
let start = found + r#"id=""#.len();
|
||||
let id = markup[start..start + markup[start..].find('"').unwrap_or_default()].to_string();
|
||||
markup = markup.replace(&format!(r#"id="{id}""#), &format!(r#"ID="{index}""#)).replace(&format!("#{id}"), &format!("#{index}"));
|
||||
index += 1;
|
||||
}
|
||||
|
||||
let shape = match layer.element() {
|
||||
Graphic::VectorList(vectors) => match vectors
|
||||
.attribute::<Appearance>(graphene_std::list::ATTR_APPEARANCE, 0)
|
||||
.and_then(|appearance| appearance.first_paint_of(Cover::Fill))
|
||||
{
|
||||
Some(Graphic::Gradient(gradient)) => Some(GradientShape::new(
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_START_CURVATURE),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_END_CURVATURE),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_MODEL),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_TRANSFORM),
|
||||
)),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
(markup.replace(r#"ID=""#, r#"id=""#), shape)
|
||||
}
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(10., 20., 110., 70.).await;
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("the rectangle is a layer");
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: Gradient::from(vec![Color::BLACK, Color::WHITE]),
|
||||
gradient_form: Some(GradientForm::Radial),
|
||||
gradient_settings: Default::default(),
|
||||
transform: Some(placement),
|
||||
})
|
||||
.await;
|
||||
|
||||
// The radial form's curvatures draw the unit circle it always drew, and the CPU samples it as the form
|
||||
let (curved_svg, curved_shape) = painted(&mut editor).await;
|
||||
assert!(curved_svg.contains(r#"gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1""#), "{curved_svg}");
|
||||
assert_eq!(curved_shape, Some(GradientShape::Radial));
|
||||
|
||||
// The same document saved with the form, under the name it had before 'Gradient Type' became 'Gradient Form', in place of the curvatures
|
||||
let document = editor.active_document_mut();
|
||||
let fill_id = NodeGraphLayer::new(layer, &document.network_interface)
|
||||
.upstream_node_id_from_protonode(fill::IDENTIFIER)
|
||||
.expect("the layer has a Fill");
|
||||
let inputs = document.network_interface.document_network().nodes[&fill_id].inputs.clone();
|
||||
let curvatures = [4, 5].map(|index| inputs[index].as_value().cloned());
|
||||
assert_eq!(curvatures, GradientForm::Radial.curvatures().map(|curvature| Some(TaggedValue::Number(curvature))));
|
||||
|
||||
let form = NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false);
|
||||
let mut old_inputs = NodeTemplate {
|
||||
inputs: [&inputs[..4], &[form], &inputs[6..]].concat(),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_inputs(&fill_id, &[], &mut old_inputs);
|
||||
let serialized = document.serialize_document();
|
||||
assert_eq!(serialized.matches(r#"{"GradientForm":"Radial"}"#).count(), 1, "the form should be saved once");
|
||||
let serialized = serialized.replace(r#"{"GradientForm":"Radial"}"#, r#"{"GradientType":"Radial"}"#);
|
||||
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
|
||||
document_name: Some("Migrated".into()),
|
||||
document_path: None,
|
||||
document_serialized_content: serialized,
|
||||
})
|
||||
.await;
|
||||
let (migrated_svg, migrated_shape) = painted(&mut editor).await;
|
||||
assert_eq!(migrated_svg, curved_svg);
|
||||
assert_eq!(migrated_shape, curved_shape);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
@@ -6228,123 +5713,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadows_and_glows_from_before_their_blend_mode_open_blending_normally() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::blending_nodes::effects::{drop_shadow, inner_shadow, outer_glow};
|
||||
|
||||
let saved_nodes = [(drop_shadow::IDENTIFIER, 8), (inner_shadow::IDENTIFIER, 7), (outer_glow::IDENTIFIER, 7)];
|
||||
let template = |identifier: &ProtoNodeIdentifier| {
|
||||
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier.clone())).expect("the definition should exist");
|
||||
definition.default_node_template()
|
||||
};
|
||||
|
||||
// Each node as saved before the blend mode, with each number marked by its index so the shift shows
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
|
||||
let mut inputs = template(identifier).inputs;
|
||||
// Outer Glow's grain inputs came later, ahead of its contour
|
||||
if *identifier == outer_glow::IDENTIFIER {
|
||||
inputs.drain(7..10);
|
||||
}
|
||||
inputs.remove(2);
|
||||
inputs.truncate(*count);
|
||||
for (input_index, input) in inputs.iter_mut().enumerate() {
|
||||
if matches!(input.as_value(), Some(TaggedValue::Number(_))) {
|
||||
*input = NodeInput::value(TaggedValue::Number(input_index as f64), false);
|
||||
}
|
||||
}
|
||||
|
||||
let node_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(identifier.clone()),
|
||||
inputs,
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(NodeId(index as u64 + 1), node_template, &[]);
|
||||
}
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
|
||||
for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
|
||||
let node = opened.network_interface.document_node(&NodeId(index as u64 + 1), &[]).expect("the node should still exist");
|
||||
let name = identifier.as_str();
|
||||
assert_eq!(node.inputs.len(), template(identifier).inputs.len(), "{name} should take the current shape");
|
||||
assert_eq!(node.inputs[2], NodeInput::value(TaggedValue::BlendMode(BlendMode::Normal), false), "{name} should blend normally");
|
||||
// Outer Glow's contour, its last saved input, moves past its grain to the end
|
||||
let shifted = if *identifier == outer_glow::IDENTIFIER { *count } else { count + 1 };
|
||||
for (input_index, input) in node.inputs.iter().enumerate().take(shifted).skip(3) {
|
||||
if let Some(TaggedValue::Number(number)) = input.as_value() {
|
||||
assert_eq!(*number, (input_index - 1) as f64, "{name} should move its input {} past the blend mode", input_index - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outer_glows_from_before_their_grain_open_smooth() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::blending_nodes::effects::outer_glow;
|
||||
|
||||
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(outer_glow::IDENTIFIER)).expect("the Outer Glow definition should exist");
|
||||
let template = definition.default_node_template();
|
||||
|
||||
// One saved before its blend mode and one saved after it, but before its grain
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
for (index, before_blend_mode) in [true, false].into_iter().enumerate() {
|
||||
let mut inputs = template.inputs.clone();
|
||||
inputs.drain(7..10);
|
||||
if before_blend_mode {
|
||||
inputs.remove(2);
|
||||
}
|
||||
|
||||
let node_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(outer_glow::IDENTIFIER),
|
||||
inputs,
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(NodeId(index as u64 + 1), node_template, &[]);
|
||||
}
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
|
||||
let smooth = [TaggedValue::Number(0.), TaggedValue::Number(0.), TaggedValue::Integer(0)].map(|value| NodeInput::value(value, false));
|
||||
for index in 0..2 {
|
||||
let node = opened.network_interface.document_node(&NodeId(index + 1), &[]).expect("the node should still exist");
|
||||
assert_eq!(node.inputs.len(), 11);
|
||||
assert_eq!(node.inputs[7..10], smooth, "the glow should open without grain");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::raster_nodes::adjustments::make_opaque;
|
||||
|
||||
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(make_opaque::IDENTIFIER)).expect("the Make Opaque definition should exist");
|
||||
let mut inputs = definition.default_node_template().inputs;
|
||||
inputs.truncate(1);
|
||||
let content = inputs.clone();
|
||||
|
||||
// Saved with its content alone, before its strength
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let node_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(make_opaque::IDENTIFIER),
|
||||
inputs,
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(NodeId(1), node_template, &[]);
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
|
||||
let node = opened.network_interface.document_node(&NodeId(1), &[]).expect("the node should still exist");
|
||||
assert_eq!(node.inputs[..1], content, "Make Opaque should keep its content");
|
||||
assert_eq!(node.inputs[1..], [NodeInput::value(TaggedValue::Number(100.), false)], "Make Opaque should open at full strength");
|
||||
}
|
||||
|
||||
// Serialize, Sample Image, and Empty Image nodes open as As String, Passthrough, and Image nodes, keeping their wires and Serialize's stored text
|
||||
#[test]
|
||||
fn removed_nodes_open_as_their_stand_ins() {
|
||||
@@ -6896,9 +6264,6 @@ mod tests {
|
||||
assert_eq!(value(read, 1), Some(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5))));
|
||||
read = upstream(read, 0).expect("the origin transform should read the pattern");
|
||||
}
|
||||
if pattern == noise {
|
||||
read = upstream(read, 0).expect("the Gamma Correction should read the pattern");
|
||||
}
|
||||
assert_eq!(read, pattern);
|
||||
}
|
||||
|
||||
@@ -6912,130 +6277,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// Noise Pattern once wrote its value as linear light, so whatever read an old one reads it through a Gamma Correction giving back about the old gray
|
||||
#[tokio::test]
|
||||
async fn old_noise_patterns_are_read_through_a_gamma_correction() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::raster_nodes::adjustments::gamma_correction;
|
||||
use graphene_std::raster_nodes::std_nodes::noise_pattern;
|
||||
use graphene_std::transform_nodes::transform;
|
||||
|
||||
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
// Old patterns read by two nodes and the export, in a layer's chain, disabled, and unread, plus a current one in the new look
|
||||
let read_thrice = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 0).await;
|
||||
let readers = [
|
||||
editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 0).await,
|
||||
editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 5).await,
|
||||
];
|
||||
let chained = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 15, 20).await;
|
||||
let layer = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 20, 20).await;
|
||||
let disabled = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 30).await;
|
||||
let disabled_reader = editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 30).await;
|
||||
let disabled_primary = editor.create_node_by_name_at(proto(transform::IDENTIFIER), -10, 30).await;
|
||||
let unread = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 40).await;
|
||||
let unread_clipped = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 45).await;
|
||||
let current = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 50).await;
|
||||
let current_reader = editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 50).await;
|
||||
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
for reader in readers {
|
||||
interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(read_thrice, 0), &[]);
|
||||
}
|
||||
interface.create_wire(&OutputConnector::primary_output(read_thrice), &InputConnector::Export(0), &[]);
|
||||
interface.set_to_node_or_layer(&layer, &[], true);
|
||||
interface.create_wire(&OutputConnector::primary_output(chained), &InputConnector::layer_secondary_input(layer), &[]);
|
||||
interface.set_input(&InputConnector::node_at_index(disabled_reader, 0), NodeInput::node(disabled, 0), &[]);
|
||||
interface.set_input(&InputConnector::node_at_index(disabled, 0), NodeInput::node(disabled_primary, 0), &[]);
|
||||
interface.set_visibility(&disabled, &[], false);
|
||||
interface.set_input(&InputConnector::node_at_index(current_reader, 0), NodeInput::node(current, 0), &[]);
|
||||
assert!(interface.is_chain(&chained, &[]), "the pattern should be in the layer's chain: fixture is wrong");
|
||||
|
||||
// A pattern exported from a subgraph
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 60).await;
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
||||
let nested = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 10, 0).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(nested),
|
||||
input_connector: InputConnector::Export(0),
|
||||
})
|
||||
.await;
|
||||
|
||||
// Save the old patterns as an older editor did, with their Clip toggle off except on one of the unread ones
|
||||
let document = editor.active_document_mut();
|
||||
let old_patterns = [
|
||||
(read_thrice, vec![], false),
|
||||
(chained, vec![], false),
|
||||
(disabled, vec![], false),
|
||||
(unread, vec![], false),
|
||||
(unread_clipped, vec![], true),
|
||||
(nested, vec![subgraph], false),
|
||||
];
|
||||
for (node_id, network_path, clip) in old_patterns {
|
||||
let mut inputs = document.network_interface.document_node(&node_id, &network_path).unwrap().inputs.clone();
|
||||
inputs.insert(1, NodeInput::value(TaggedValue::Bool(clip), false));
|
||||
let mut legacy = NodeTemplate { inputs, ..Default::default() };
|
||||
legacy.normalize_input_metadata();
|
||||
document.network_interface.replace_inputs(&node_id, &network_path, &mut legacy);
|
||||
}
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
let upstream = |connector: InputConnector, network_path: &[NodeId]| interface.upstream_output_connector(&connector, network_path).and_then(|output| output.node_id());
|
||||
|
||||
// The Gamma Correction a reader of `pattern` reads instead, at the default gamma and reading the pattern
|
||||
let gamma_correction_between = |pattern: NodeId, reader: InputConnector, network_path: &[NodeId]| {
|
||||
let inserted = upstream(reader, network_path).expect("the reader should read a node");
|
||||
assert_eq!(interface.reference(&inserted, network_path), Some(proto(gamma_correction::IDENTIFIER)));
|
||||
|
||||
let node = interface.document_node(&inserted, network_path).unwrap();
|
||||
assert_eq!(node.input_value(gamma_correction::GammaInput), Some(&TaggedValue::Number(2.2)));
|
||||
assert_eq!(node.input_value(gamma_correction::InverseInput), Some(&TaggedValue::Bool(false)));
|
||||
assert_eq!(upstream(InputConnector::node_at_index(inserted, 0), network_path), Some(pattern));
|
||||
inserted
|
||||
};
|
||||
|
||||
// Every reader of the pattern read three times shares one Gamma Correction, which takes the pattern's place with the pattern before it
|
||||
let shared = gamma_correction_between(read_thrice, InputConnector::Export(0), &[]);
|
||||
for reader in readers {
|
||||
assert_eq!(upstream(InputConnector::node_at_index(reader, 0), &[]), Some(shared));
|
||||
}
|
||||
let position = |node_id: NodeId| interface.position(&node_id, &[]).expect("the node should have a position");
|
||||
assert_eq!(position(read_thrice) + IVec2::new(7, 0), position(shared));
|
||||
|
||||
let in_chain = gamma_correction_between(chained, InputConnector::layer_secondary_input(layer), &[]);
|
||||
assert!(interface.is_chain(&in_chain, &[]) && interface.is_chain(&chained, &[]), "the layer's chain should hold both");
|
||||
|
||||
// Only a disabled pattern's Gamma Correction is disabled too, and the pattern keeps the primary input it passes through
|
||||
let behind_disabled = gamma_correction_between(disabled, InputConnector::node_at_index(disabled_reader, 0), &[]);
|
||||
assert!(!interface.is_visible(&behind_disabled, &[]) && interface.is_visible(&shared, &[]));
|
||||
assert_eq!(upstream(InputConnector::node_at_index(disabled, 0), &[]), Some(disabled_primary));
|
||||
|
||||
gamma_correction_between(nested, InputConnector::Export(0), &[subgraph]);
|
||||
assert_eq!(upstream(InputConnector::node_at_index(current_reader, 0), &[]), Some(current));
|
||||
|
||||
// Unread patterns gain nothing reading them, clipped or not
|
||||
let read = |pattern: NodeId| interface.document_network().nodes.values().any(|node| node.inputs.iter().any(|input| input.as_node() == Some(pattern)));
|
||||
assert!(!read(unread) && !read(unread_clipped));
|
||||
|
||||
// Reopening the upgraded document, as restoring an autosave does, inserts no more
|
||||
let gamma_corrections = |document: &DocumentMessageHandler| {
|
||||
let implementation = DocumentNodeImplementation::ProtoNode(gamma_correction::IDENTIFIER);
|
||||
let nodes = document.network_interface.document_network().recursive_nodes();
|
||||
nodes.filter(|(_, node, _)| node.implementation == implementation).count()
|
||||
};
|
||||
assert_eq!(gamma_corrections(&opened), 4);
|
||||
let reopened = load_legacy_document(opened.serialize_document(), &HashMapResourceStorage::new(), false).expect("the upgraded document should open");
|
||||
assert_eq!(gamma_corrections(&reopened), 4);
|
||||
}
|
||||
|
||||
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
||||
#[tokio::test]
|
||||
async fn marbled_mandelbrot_renders_after_migration() {
|
||||
|
||||
@@ -989,6 +989,16 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
} => {
|
||||
let document_id = self.active_document_id.expect("Tried to render non-existent document");
|
||||
let document = self.documents.get_mut(&document_id).expect("Tried to render non-existent document");
|
||||
|
||||
// An export now would capture the fallbacks drawn in place of fonts and images still loading
|
||||
if document.resources.awaiting_resources() {
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Unable to export document".to_string(),
|
||||
description: "The document's fonts or images are still loading. Try again once they finish.".to_string(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let export_config = ExportConfig {
|
||||
name,
|
||||
file_type,
|
||||
@@ -1025,7 +1035,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
return;
|
||||
};
|
||||
|
||||
// Skip rendering while a resource is still loading, so its error isn't shown in the meantime.
|
||||
// Skip rendering while a resource is still loading, so its fallback isn't drawn in the meantime.
|
||||
// Each load queues `RunDocumentGraph` when it succeeds or fails, so the render goes ahead once none are left.
|
||||
if document.resources.awaiting_resources() {
|
||||
return;
|
||||
|
||||
@@ -217,7 +217,7 @@ impl DrawingToolState {
|
||||
Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: graphene_std::vector::Gradient::from(&ramp),
|
||||
gradient_form: None,
|
||||
gradient_form: Default::default(),
|
||||
gradient_settings: (&ramp).into(),
|
||||
transform: None,
|
||||
}),
|
||||
|
||||
@@ -1,454 +0,0 @@
|
||||
//! Geometry of the Gradient tool's gizmos, in gradient space, where the gradient line runs from the start point at the origin to the end
|
||||
//! point at (1, 0). Each end's contour passes through its endpoint with its center on the line, set by its curvature, as described
|
||||
//! in [`graphene_std::vector::gradient_standard`].
|
||||
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature};
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
|
||||
/// The farthest a drawn contour bows from its chords between the points it's drawn through, in viewport pixels.
|
||||
const CONTOUR_SAG_TOLERANCE: f64 = 0.25;
|
||||
|
||||
/// The most chords a contour is drawn with.
|
||||
const CONTOUR_MAX_CHORDS: usize = 1024;
|
||||
|
||||
/// One of the gradient line's two ends, each with its own contour.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GradientEnd {
|
||||
Start,
|
||||
End,
|
||||
}
|
||||
|
||||
impl GradientEnd {
|
||||
/// Its index in a `[start, end]` pair of curvatures.
|
||||
pub fn index(self) -> usize {
|
||||
match self {
|
||||
Self::Start => 0,
|
||||
Self::End => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Its endpoint in gradient space.
|
||||
pub fn endpoint(self) -> DVec2 {
|
||||
match self {
|
||||
Self::Start => DVec2::ZERO,
|
||||
Self::End => DVec2::X,
|
||||
}
|
||||
}
|
||||
|
||||
/// Which way along the gradient line points toward the other end, which a positive curvature bows this end's contour toward.
|
||||
fn inward(self) -> f64 {
|
||||
match self {
|
||||
Self::Start => 1.,
|
||||
Self::End => -1.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The center of this end's contour in gradient space for its `curvature`, or `None` for a line.
|
||||
pub fn contour_center(end: GradientEnd, curvature: f64) -> Option<DVec2> {
|
||||
let radius = curvature_radius(curvature);
|
||||
radius.is_finite().then(|| end.endpoint() + DVec2::new(end.inward() * radius, 0.))
|
||||
}
|
||||
|
||||
/// The curvature that centers this end's contour at `axis_position` along the gradient line, as dragging its center dot there does.
|
||||
pub fn center_curvature(end: GradientEnd, axis_position: f64) -> f64 {
|
||||
radius_curvature((axis_position - end.endpoint().x) * end.inward())
|
||||
}
|
||||
|
||||
/// The curvature of this end's contour through `point`, the circle through it and the endpoint with its center on the gradient line,
|
||||
/// which is the line across the gradient line where `point` lies across from the endpoint. `None` at the endpoint itself.
|
||||
pub fn rim_curvature(end: GradientEnd, point: DVec2) -> Option<f64> {
|
||||
let offset = point - end.endpoint();
|
||||
let distance_squared = offset.length_squared();
|
||||
|
||||
// The inverse of the radius `|offset|² / 2 offset.x`, which stays finite where the radius doesn't
|
||||
(distance_squared > 0.).then(|| (2. * offset.x * end.inward() / distance_squared).atan() / FRAC_PI_2)
|
||||
}
|
||||
|
||||
/// The signed radius that resizes this end's contour (from its `curvature`) to bring the place on its rim nearest `grabbed` as near `pointer` as it gets,
|
||||
/// both in the space `unit_to_viewport` maps to, and where that place lands there. `None` for a line or a point, which no resizing moves a place on.
|
||||
pub fn rim_resized_toward(end: GradientEnd, curvature: f64, grabbed: DVec2, pointer: DVec2, unit_to_viewport: DAffine2) -> Option<(f64, DVec2)> {
|
||||
let radius = curvature_radius(curvature);
|
||||
if !radius.is_finite() || radius == 0. {
|
||||
return None;
|
||||
}
|
||||
let inward = DVec2::new(end.inward(), 0.);
|
||||
|
||||
// Each circle through the endpoint is the others scaled about it, so the place keeps its angle around them from the endpoint, measured at the center
|
||||
let to_endpoint = -radius * inward;
|
||||
let to_grabbed = unit_to_viewport.inverse().transform_point2(grabbed) - end.endpoint() - radius * inward;
|
||||
let angle = to_endpoint.perp_dot(to_grabbed).atan2(to_endpoint.dot(to_grabbed));
|
||||
|
||||
// At that angle, the place lies the radius times this from the endpoint, a line the pointer projects onto
|
||||
let direction = unit_to_viewport.transform_vector2(inward - DVec2::from_angle(angle).rotate(inward));
|
||||
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
|
||||
let resized = (pointer - endpoint).dot(direction) / direction.length_squared();
|
||||
resized.is_finite().then(|| (resized, endpoint + resized * direction))
|
||||
}
|
||||
|
||||
/// Whether a gradient with these curvatures has a focus to move: a point for its start contour and a circle for its end contour.
|
||||
pub fn has_focus(curvatures: [f64; 2]) -> bool {
|
||||
let end_radius = curvature_radius(curvatures[1]);
|
||||
curvature_radius(curvatures[0]) == 0. && end_radius.is_finite() && end_radius != 0.
|
||||
}
|
||||
|
||||
/// A gradient line in the gradient space of the line it replaces, with the curvature it gives the end contour.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RefocusedLine {
|
||||
pub start: DVec2,
|
||||
pub end: DVec2,
|
||||
pub end_curvature: f64,
|
||||
}
|
||||
|
||||
/// The line of a gradient whose start point (its focus) moves to `focus` while its end circle from `end_curvature` stays put: from the focus through the
|
||||
/// circle's center to its far side, with the end curvature keeping that circle. A focus on the center keeps `direction`. `None` unless the end is a circle.
|
||||
pub fn refocused_line(focus: DVec2, end_curvature: f64, direction: DVec2) -> Option<RefocusedLine> {
|
||||
let radius = curvature_radius(end_curvature);
|
||||
if !radius.is_finite() || radius == 0. {
|
||||
return None;
|
||||
}
|
||||
let (center, size) = (DVec2::new(1. - radius, 0.), radius.abs());
|
||||
|
||||
let to_center = center - focus;
|
||||
let distance = to_center.length();
|
||||
let direction = if distance > 0. { to_center / distance } else { direction.try_normalize()? };
|
||||
|
||||
Some(RefocusedLine {
|
||||
start: focus,
|
||||
end: center + direction * size,
|
||||
end_curvature: radius_curvature(size / (distance + size)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The transform placing a gradient along `line`, given in the gradient space of the `old` transform. Its frame turns and scales uniformly within
|
||||
/// that space, so a contour that's a circle there keeps its shape, even where `old` stretches it into an ellipse.
|
||||
pub fn transform_along(old: DAffine2, line: RefocusedLine) -> DAffine2 {
|
||||
let x_axis = line.end - line.start;
|
||||
old * DAffine2::from_cols(x_axis, x_axis.perp(), line.start)
|
||||
}
|
||||
|
||||
/// One side of the gradient line, across which its perpendicular axis points one way or the other.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LineSide {
|
||||
Positive,
|
||||
Negative,
|
||||
}
|
||||
|
||||
impl LineSide {
|
||||
/// Which way across the gradient line its perpendicular axis points to reach this side.
|
||||
pub fn sign(self) -> f64 {
|
||||
match self {
|
||||
Self::Positive => 1.,
|
||||
Self::Negative => -1.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The semi-minor axis to this side of this end's circle from its `curvature`, from the circle's center a radius across the gradient line to where
|
||||
/// a handle stretching the gradient across its line sits, in gradient space. `None` for a line or a point.
|
||||
pub fn aspect_axis(end: GradientEnd, curvature: f64, side: LineSide) -> Option<[DVec2; 2]> {
|
||||
let radius = curvature_radius(curvature).abs();
|
||||
let center = contour_center(end, curvature).filter(|_| radius > 0.)?;
|
||||
Some([center, center + DVec2::new(0., side.sign() * radius)])
|
||||
}
|
||||
|
||||
/// The transform stretched across its line so the point `handle` in its gradient space lies as far across the line as `pointer` does
|
||||
/// (in the transform's output space), keeping the line and how far its perpendicular axis leans along it. `None` where it would collapse.
|
||||
pub fn stretched_transform(transform: DAffine2, handle: DVec2, pointer: DVec2) -> Option<DAffine2> {
|
||||
let x_axis = transform.matrix2.x_axis;
|
||||
let along = x_axis.try_normalize()?;
|
||||
let across = along.perp();
|
||||
|
||||
// The handle lies `handle.y` times the perpendicular axis's span across the line
|
||||
let span_across = (pointer - transform.translation).dot(across) / handle.y;
|
||||
if !(span_across.abs() > 1e-9 * x_axis.length()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let y_axis = along * transform.matrix2.y_axis.dot(along) + across * span_across;
|
||||
Some(DAffine2::from_cols(x_axis, y_axis, transform.translation))
|
||||
}
|
||||
|
||||
/// The smallest factor `transform` scales any length by, the least singular value of its linear part.
|
||||
fn least_scale(transform: DAffine2) -> f64 {
|
||||
let [x_axis, y_axis] = [transform.matrix2.x_axis, transform.matrix2.y_axis];
|
||||
let determinant = transform.matrix2.determinant().abs();
|
||||
|
||||
// Of the singular values `√(mean ± √(mean² - determinant²))`, the least is the determinant over the greatest, which avoids cancellation
|
||||
let mean = (x_axis.length_squared() + y_axis.length_squared()) / 2.;
|
||||
let greatest = (mean + (mean * mean - determinant * determinant).max(0.).sqrt()).sqrt();
|
||||
if greatest > 0. { determinant / greatest } else { 0. }
|
||||
}
|
||||
|
||||
/// Points through which this end's contour is drawn in the viewport, from `unit_to_viewport`, as far as `reach` viewport pixels from
|
||||
/// its endpoint along it (or around the whole circle if that's shorter). Empty for a point, or where the transform collapses.
|
||||
pub fn contour_polyline(end: GradientEnd, curvature: f64, unit_to_viewport: DAffine2, reach: f64) -> Vec<DVec2> {
|
||||
let radius = curvature_radius(curvature);
|
||||
let endpoint = end.endpoint();
|
||||
|
||||
let least_scale = least_scale(unit_to_viewport);
|
||||
if radius == 0. || least_scale <= 0. {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// A line runs straight across the gradient line through the endpoint
|
||||
if radius.is_infinite() {
|
||||
let Some(direction) = unit_to_viewport.transform_vector2(DVec2::Y).try_normalize() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let viewport_endpoint = unit_to_viewport.transform_point2(endpoint);
|
||||
return vec![viewport_endpoint - direction * reach, viewport_endpoint + direction * reach];
|
||||
}
|
||||
|
||||
// Sweep from the endpoint both ways around the circle, by the angle reaching `reach` pixels at the least scale
|
||||
let size = radius.abs();
|
||||
let sweep = (reach / (size * least_scale)).min(PI);
|
||||
|
||||
// Uniform steps small enough that each chord stays within the sag tolerance, even at twice the longest axis's scale (which bounds the greatest)
|
||||
let viewport_radius_bound = size * unit_to_viewport.matrix2.x_axis.length().max(unit_to_viewport.matrix2.y_axis.length()) * 2.;
|
||||
let step = (8. * CONTOUR_SAG_TOLERANCE / viewport_radius_bound).sqrt();
|
||||
let chords_each_way = ((sweep / step).ceil() as usize).clamp(4, CONTOUR_MAX_CHORDS / 2);
|
||||
let chords = 2 * chords_each_way;
|
||||
|
||||
// Measured from the endpoint rather than the center, the points stay precise on huge circles
|
||||
(0..=chords)
|
||||
.map(|index| {
|
||||
let angle = sweep * (2. * index as f64 / chords as f64 - 1.);
|
||||
let half_sine = (angle / 2.).sin();
|
||||
let offset = DVec2::new(2. * end.inward() * radius * half_sine * half_sine, size * angle.sin());
|
||||
unit_to_viewport.transform_point2(endpoint + offset)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The distance from `point` to the nearest place on the polyline through `points`, or `None` if it has none.
|
||||
pub fn distance_to_polyline(points: &[DVec2], point: DVec2) -> Option<f64> {
|
||||
if let [only] = points {
|
||||
return Some(only.distance(point));
|
||||
}
|
||||
|
||||
points
|
||||
.windows(2)
|
||||
.map(|pair| {
|
||||
let (start, end) = (pair[0], pair[1]);
|
||||
let along = (point - start).dot(end - start) / (end - start).length_squared();
|
||||
let nearest = if along.is_finite() { start.lerp(end, along.clamp(0., 1.)) } else { start };
|
||||
nearest.distance(point)
|
||||
})
|
||||
.min_by(f64::total_cmp)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Curvatures through circles of each size and bend, both lines, and the points.
|
||||
fn curvatures() -> impl Iterator<Item = f64> {
|
||||
(-20..=20).map(|step| step as f64 * 0.05)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rim_dragged_to_a_point_takes_the_curvature_of_the_circle_through_it() {
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for point in [DVec2::new(0.3, 0.4), DVec2::new(-0.7, 1.2), DVec2::new(2.5, -0.25), DVec2::new(0.5, 3.)] {
|
||||
let curvature = rim_curvature(end, point).unwrap();
|
||||
|
||||
// The contour of that curvature passes through the point, centered on the gradient line
|
||||
let center = contour_center(end, curvature).unwrap();
|
||||
assert!(center.y == 0.);
|
||||
let radius = center.distance(end.endpoint());
|
||||
assert!((center.distance(point) - radius).abs() < 1e-9 * radius.max(1.), "{end:?} through {point}: curvature {curvature}");
|
||||
}
|
||||
|
||||
// Straight across from the endpoint is the line, and either side of it bends toward that side
|
||||
let across = end.endpoint() + DVec2::Y;
|
||||
assert_eq!(rim_curvature(end, across), Some(0.));
|
||||
let inward = DVec2::new(end.inward() * 0.1, 0.);
|
||||
assert!(rim_curvature(end, across + inward).unwrap() > 0.);
|
||||
assert!(rim_curvature(end, across - inward).unwrap() < 0.);
|
||||
|
||||
// The endpoint is on every contour, so it sets none
|
||||
assert_eq!(rim_curvature(end, end.endpoint()), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rim_dragged_along_its_own_contour_keeps_its_curvature() {
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for curvature in curvatures().filter(|curvature| curvature.abs() != 1.) {
|
||||
for point in contour_polyline(end, curvature, DAffine2::IDENTITY, 3.) {
|
||||
// Every point but the endpoint sets the curvature back, as a line's points beside the endpoint do
|
||||
if point.distance(end.endpoint()) < 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let found = rim_curvature(end, point).unwrap();
|
||||
assert!((found - curvature).abs() < 1e-9, "{end:?} curvature {curvature} at {point}: {found}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_center_dragged_along_the_line_takes_the_curvature_centered_there() {
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for curvature in curvatures().filter(|&curvature| curvature != 0.) {
|
||||
let center = contour_center(end, curvature).unwrap();
|
||||
let found = center_curvature(end, center.x);
|
||||
|
||||
// A point is both -1 and 1, which the drag settles at -1
|
||||
let expected = if curvature.abs() == 1. { -1. } else { curvature };
|
||||
assert!((found - expected).abs() < 1e-9, "{end:?} curvature {curvature}: {found}");
|
||||
}
|
||||
|
||||
// Toward the other end bows toward it, and onto the endpoint is a point
|
||||
assert!(center_curvature(end, 0.5) > 0.);
|
||||
assert!(center_curvature(end, end.endpoint().x - end.inward()) < 0.);
|
||||
assert_eq!(center_curvature(end, end.endpoint().x), -1.);
|
||||
}
|
||||
|
||||
// The start contour centered at the end point, and the end contour at the start point, are each the circle of radius 1 between them
|
||||
assert!((center_curvature(GradientEnd::Start, 1.) - 0.5).abs() < 1e-12);
|
||||
assert!((center_curvature(GradientEnd::End, 0.) - 0.5).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// The center and radius of the end circle of a gradient along `line`, in the gradient space `line` is given in.
|
||||
fn end_circle(line: RefocusedLine) -> (DVec2, f64) {
|
||||
let radius = curvature_radius(line.end_curvature);
|
||||
(line.start.lerp(line.end, 1. - radius), radius.abs() * line.start.distance(line.end))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_focus_keeps_the_end_circle_in_place() {
|
||||
// The end circle of radius 0.75 centered at 0.25, with foci inside it, outside it, and behind its center
|
||||
let end_curvature = radius_curvature(0.75);
|
||||
let (center, radius) = (DVec2::new(0.25, 0.), 0.75);
|
||||
for focus in [DVec2::new(0.1, 0.3), DVec2::new(-0.2, -0.4), DVec2::new(3., 2.), DVec2::new(0.9, 0.), DVec2::new(-5., 0.)] {
|
||||
let line = refocused_line(focus, end_curvature, DVec2::X).unwrap();
|
||||
assert_eq!(line.start, focus);
|
||||
|
||||
let (new_center, new_radius) = end_circle(line);
|
||||
assert!(new_center.distance(center) < 1e-12 && (new_radius - radius).abs() < 1e-12, "focus {focus}: {line:?}");
|
||||
|
||||
// The line runs on through the center to the circle's far side
|
||||
assert!((line.end.distance(focus) - (focus.distance(center) + radius)).abs() < 1e-12, "focus {focus}: {line:?}");
|
||||
}
|
||||
|
||||
// A focus off the circle's line still aims the line through its center
|
||||
let line = refocused_line(DVec2::new(0.25, 2.), end_curvature, DVec2::X).unwrap();
|
||||
assert!(line.end.abs_diff_eq(DVec2::new(0.25, -0.75), 1e-12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_focus_on_the_center_keeps_the_direction_and_makes_the_radial_form() {
|
||||
let end_curvature = radius_curvature(0.75);
|
||||
let line = refocused_line(contour_center(GradientEnd::End, end_curvature).unwrap(), end_curvature, DVec2::new(0., 2.)).unwrap();
|
||||
assert_eq!(line.end_curvature, 0.5);
|
||||
assert!(line.end.abs_diff_eq(DVec2::new(0.25, 0.75), 1e-12));
|
||||
assert_eq!(
|
||||
graphene_std::vector::style::GradientForm::from_curvatures([-1., line.end_curvature]),
|
||||
Some(graphene_std::vector::style::GradientForm::Radial)
|
||||
);
|
||||
|
||||
// Only an end circle has a focus to move around
|
||||
assert!(has_focus([-1., 0.5]) && has_focus([1., -0.3]));
|
||||
assert!(!has_focus([0., 0.5]) && !has_focus([-1., 0.]) && !has_focus([-1., 1.]));
|
||||
assert_eq!(refocused_line(DVec2::ZERO, 0., DVec2::X), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refocused_transform_keeps_an_elliptical_end_contour_in_place() {
|
||||
// A radial gradient squashed to half its height and skewed, whose focus moves off its line
|
||||
let old = DAffine2::from_cols(DVec2::new(100., 20.), DVec2::new(-5., 50.), DVec2::new(30., 40.));
|
||||
let line = refocused_line(DVec2::new(0.3, 0.4), 0.5, DVec2::X).unwrap();
|
||||
let new = transform_along(old, line);
|
||||
|
||||
// The end contour's points land on the same ellipse before and after (within its chords' sag), though spread differently around it
|
||||
let before = contour_polyline(GradientEnd::End, 0.5, old, 1e6);
|
||||
let after = contour_polyline(GradientEnd::End, line.end_curvature, new, 1e6);
|
||||
for point in after {
|
||||
assert!(distance_to_polyline(&before, point).unwrap() <= CONTOUR_SAG_TOLERANCE, "{point} left the ellipse");
|
||||
}
|
||||
assert!(new.transform_point2(DVec2::ZERO).abs_diff_eq(old.transform_point2(DVec2::new(0.3, 0.4)), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_end_circle_has_an_aspect_handle_a_radius_to_either_side_of_its_center() {
|
||||
use LineSide::{Negative, Positive};
|
||||
|
||||
// The radial form's end circle around the start point, but not its start point
|
||||
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Positive), Some([DVec2::ZERO, DVec2::Y]));
|
||||
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Negative), Some([DVec2::ZERO, -DVec2::Y]));
|
||||
assert_eq!(aspect_axis(GradientEnd::Start, -1., Positive), None);
|
||||
|
||||
// Each of two crossing circles, and a huge nearly flat one
|
||||
let radius = curvature_radius(0.6);
|
||||
assert_eq!(aspect_axis(GradientEnd::Start, 0.6, Positive), Some([DVec2::new(radius, 0.), DVec2::new(radius, radius)]));
|
||||
assert_eq!(aspect_axis(GradientEnd::End, 0.6, Negative), Some([DVec2::new(1. - radius, 0.), DVec2::new(1. - radius, -radius)]));
|
||||
assert!(aspect_axis(GradientEnd::End, 1e-3, Positive).is_some_and(|[_, handle]| handle.y > 100.));
|
||||
|
||||
// Lines and points have none
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for curvature in [0., 1., -1.] {
|
||||
for side in [Positive, Negative] {
|
||||
assert_eq!(aspect_axis(end, curvature, side), None, "{end:?} curvature {curvature} {side:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stretching_moves_each_aspect_handle_across_the_line_and_keeps_the_line() {
|
||||
// A skewed gradient, its perpendicular axis leaning along the line
|
||||
let transform = DAffine2::from_cols(DVec2::new(80., 60.), DVec2::new(-50., 70.), DVec2::new(10., 20.));
|
||||
let along = transform.matrix2.x_axis.normalize();
|
||||
|
||||
// The radial form's handles and those of two crossing circles of different sizes, each pulled to its own side of the line
|
||||
let axes = [(GradientEnd::End, 0.5), (GradientEnd::Start, 0.6), (GradientEnd::End, 0.3)];
|
||||
let handles = axes
|
||||
.into_iter()
|
||||
.flat_map(|(end, curvature)| [LineSide::Positive, LineSide::Negative].map(|side| (aspect_axis(end, curvature, side).unwrap()[1], side)));
|
||||
for (handle, side) in handles {
|
||||
let pointer = transform.transform_point2(DVec2::new(0.4, side.sign() * 0.7));
|
||||
let stretched = stretched_transform(transform, handle, pointer).unwrap();
|
||||
assert!(stretched.matrix2.determinant() * transform.matrix2.determinant() > 0., "the gradient shouldn't mirror");
|
||||
for point in [DVec2::ZERO, DVec2::X] {
|
||||
assert!(stretched.transform_point2(point).abs_diff_eq(transform.transform_point2(point), 1e-9));
|
||||
}
|
||||
|
||||
// The handle lands as far across the line as the pointer, sliding only across it, and the lean along the line stays
|
||||
let (old_handle, new_handle) = (transform.transform_point2(handle), stretched.transform_point2(handle));
|
||||
assert!(((new_handle - transform.translation).dot(along.perp()) - (pointer - transform.translation).dot(along.perp())).abs() < 1e-9);
|
||||
assert!((new_handle - old_handle).dot(along).abs() < 1e-9);
|
||||
assert!((stretched.matrix2.y_axis.dot(along) - transform.matrix2.y_axis.dot(along)).abs() < 1e-9);
|
||||
|
||||
// Onto the line, it would collapse
|
||||
assert_eq!(stretched_transform(transform, handle, transform.transform_point2(DVec2::new(0.5, 0.))), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contours_are_drawn_through_their_endpoints_out_to_their_reach() {
|
||||
let unit_to_viewport = DAffine2::from_scale_angle_translation(DVec2::new(200., 100.), 0.3, DVec2::new(40., 60.));
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
|
||||
|
||||
// A point draws nothing, and a line is one long chord through the endpoint
|
||||
assert!(contour_polyline(end, 1., unit_to_viewport, 500.).is_empty());
|
||||
let line = contour_polyline(end, 0., unit_to_viewport, 500.);
|
||||
assert_eq!(line.len(), 2);
|
||||
assert!(distance_to_polyline(&line, endpoint).unwrap() < 1e-9);
|
||||
|
||||
// A small circle is drawn whole, closing on itself, and a huge one only as far as its reach, nearly straight
|
||||
let small = contour_polyline(end, 0.5, unit_to_viewport, 500.);
|
||||
assert!(small.first().unwrap().distance(*small.last().unwrap()) < 1e-6);
|
||||
let huge = contour_polyline(end, 1e-6, unit_to_viewport, 500.);
|
||||
let farthest = huge.iter().map(|point| point.distance(endpoint)).fold(0., f64::max);
|
||||
assert!((400. ..=1000.).contains(&farthest), "a huge circle should reach about 500 pixels, not {farthest}");
|
||||
|
||||
for polyline in [small, huge] {
|
||||
assert!(distance_to_polyline(&polyline, endpoint).unwrap() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -346,7 +346,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_curvature::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
||||
@@ -428,17 +428,6 @@ pub fn get_chain_source_gradient_settings(layer: LayerNodeIdentifier, network_in
|
||||
Some(get_chain_source_gradient_ramp(layer, network_interface)?.into())
|
||||
}
|
||||
|
||||
/// The start and end curvatures a 'Gradient Curvature' node holds as values, or `None` when either is fed from the graph or exposed.
|
||||
pub fn gradient_curvature_values(node: &DocumentNode) -> Option<[f64; 2]> {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
|
||||
&TaggedValue::Number(value) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
Some([value(node.input(StartCurvatureInput))?, value(node.input(EndCurvatureInput))?])
|
||||
}
|
||||
|
||||
/// Get the gradient stops of a layer, if any.
|
||||
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
|
||||
// Try to find the gradient stops value that is created by a Fill node first
|
||||
@@ -841,23 +830,9 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
|
||||
}
|
||||
}
|
||||
|
||||
/// A Fill node's curvatures, unless the graph feeds either or exposes it, read like [`gradient_curvature_values`] reads a 'Gradient Curvature' node's.
|
||||
pub fn fill_node_curvatures(fill_node: &DocumentNode) -> Option<[f64; 2]> {
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
|
||||
&TaggedValue::Number(value) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
Some([value(fill_node.input(StartCurvatureInput))?, value(fill_node.input(EndCurvatureInput))?])
|
||||
}
|
||||
|
||||
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
|
||||
pub struct FillNodeGradient {
|
||||
pub stops: Gradient,
|
||||
/// Its curvatures, unless the graph feeds them, as [`fill_node_curvatures`] reads them.
|
||||
pub curvatures: Option<[f64; 2]>,
|
||||
/// The form its curvatures make, which is linear for any that make neither.
|
||||
pub gradient_form: GradientForm,
|
||||
pub settings: GradientSettings,
|
||||
pub transform: DAffine2,
|
||||
@@ -874,8 +849,10 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
};
|
||||
let settings = GradientSettings::from(ramp);
|
||||
let stops = Gradient::from(ramp);
|
||||
let curvatures = fill_node_curvatures(fill_node);
|
||||
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default();
|
||||
let gradient_form = match fill_node.input(fill::GradientFormInput).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::GradientForm(value)) => value,
|
||||
_ => GradientForm::default(),
|
||||
};
|
||||
let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
|
||||
let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
|
||||
let transform = match (has_transform, transform_input) {
|
||||
@@ -886,7 +863,6 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
|
||||
Some(FillNodeGradient {
|
||||
stops,
|
||||
curvatures,
|
||||
gradient_form,
|
||||
settings,
|
||||
transform,
|
||||
@@ -1029,6 +1005,10 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
||||
use graphene_std::vector::fill;
|
||||
let fill_parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(fill::IDENTIFIER);
|
||||
|
||||
let gradient_form = match fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::GradientFormInput)) {
|
||||
Some(TaggedValue::GradientForm(value)) => *value,
|
||||
_ => GradientForm::default(),
|
||||
};
|
||||
let has_transform = matches!(fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::HasTransformInput)), Some(TaggedValue::Bool(true)));
|
||||
let transform = match (has_transform, fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::TransformInput))) {
|
||||
(true, Some(TaggedValue::DAffine2(value))) => *value,
|
||||
@@ -1039,7 +1019,7 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: Gradient::from(ramp),
|
||||
gradient_form: None,
|
||||
gradient_form,
|
||||
gradient_settings: ramp.into(),
|
||||
transform: Some(transform),
|
||||
});
|
||||
|
||||
@@ -3,7 +3,6 @@ pub mod color_selector;
|
||||
pub mod compass_rose;
|
||||
pub mod edit_target;
|
||||
pub mod gizmos;
|
||||
pub mod gradient_gizmos;
|
||||
pub mod graph_modification_utils;
|
||||
pub mod layer_origin_cross;
|
||||
pub mod measure;
|
||||
|
||||
@@ -92,8 +92,6 @@ pub struct PointOptions {
|
||||
pub box_features: Option<BoxFeatures>,
|
||||
/// Whether the grid is left out, as for a turn, which the grid would otherwise step at odd angles.
|
||||
pub ignores_grid: bool,
|
||||
/// Whether the tool marks where a press would land in its own way, so nothing marks it there unless a snap is named.
|
||||
pub marked_by_tool: bool,
|
||||
}
|
||||
|
||||
/// Which features of a gesture make up a box.
|
||||
@@ -124,8 +122,6 @@ pub struct Shown {
|
||||
pub features: Vec<DVec2>,
|
||||
/// The index of the feature the pointer carries.
|
||||
pub lead: usize,
|
||||
/// Whether the tool marks where a press would land, as [`PointOptions::marked_by_tool`] tells.
|
||||
pub marked_by_tool: bool,
|
||||
}
|
||||
|
||||
/// What a kept set of constructions was found for, which it stays good for.
|
||||
@@ -179,8 +175,6 @@ pub struct SnapSession {
|
||||
gesture: Option<Gesture>,
|
||||
/// The targets woken by resting the pointer on them, from the one woken longest ago to the latest.
|
||||
awake: Vec<Awake>,
|
||||
/// Those of them woken during the gesture under way, which go back to sleep when it ends.
|
||||
woken_in_gesture: Vec<Awake>,
|
||||
/// The layers each woken point of its own was found on, by its ID, which it goes back to sleep with.
|
||||
position_sources: HashMap<u64, Vec<LayerId>>,
|
||||
rest: Option<Rest>,
|
||||
@@ -325,7 +319,6 @@ impl SnapSession {
|
||||
features: features.iter().map(|feature| feature.position(parameters)).collect(),
|
||||
lead,
|
||||
outcome,
|
||||
marked_by_tool: options.marked_by_tool,
|
||||
});
|
||||
|
||||
// A crossing, or the grid, can hold the box anywhere along the track that evens out its gaps, so they are measured again where it landed
|
||||
@@ -404,7 +397,6 @@ impl SnapSession {
|
||||
features: vec![position_of(snapped)],
|
||||
lead: 0,
|
||||
outcome,
|
||||
marked_by_tool: false,
|
||||
});
|
||||
|
||||
snapped
|
||||
@@ -503,17 +495,13 @@ impl SnapSession {
|
||||
landed
|
||||
}
|
||||
|
||||
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to. What the gesture woke goes back to sleep with it.
|
||||
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to.
|
||||
pub fn end_gesture(&mut self) {
|
||||
self.gesture = None;
|
||||
self.constructions = None;
|
||||
self.rest = None;
|
||||
self.crossings.clear();
|
||||
self.forget();
|
||||
|
||||
let woken_in_gesture = std::mem::take(&mut self.woken_in_gesture);
|
||||
self.awake.retain(|target| !woken_in_gesture.contains(target));
|
||||
self.forget_targets_gone_to_sleep();
|
||||
}
|
||||
|
||||
/// Forgets what the pointer was last snapped to, as when the pointer is no longer placing anything.
|
||||
@@ -557,14 +545,11 @@ impl SnapSession {
|
||||
if let Awake::Position { id, .. } = target {
|
||||
self.position_sources.insert(id, sources.clone());
|
||||
}
|
||||
if self.gesture.is_some() {
|
||||
self.woken_in_gesture.push(target);
|
||||
}
|
||||
self.awake.push(target);
|
||||
}
|
||||
let over_the_limit = self.awake.len().saturating_sub(AWAKE_LIMIT);
|
||||
self.awake.drain(..over_the_limit);
|
||||
self.forget_targets_gone_to_sleep();
|
||||
self.forget_sources_of_sleeping_positions();
|
||||
self.constructions = None;
|
||||
|
||||
true
|
||||
@@ -578,7 +563,6 @@ impl SnapSession {
|
||||
/// Puts every woken target back to sleep, and keeps the pointer from waking them again until it moves.
|
||||
pub fn sleep_all(&mut self) {
|
||||
self.awake.clear();
|
||||
self.woken_in_gesture.clear();
|
||||
self.position_sources.clear();
|
||||
self.constructions = None;
|
||||
|
||||
@@ -599,12 +583,10 @@ impl SnapSession {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lets go of what is kept about woken targets that have since gone back to sleep.
|
||||
fn forget_targets_gone_to_sleep(&mut self) {
|
||||
fn forget_sources_of_sleeping_positions(&mut self) {
|
||||
let awake = &self.awake;
|
||||
self.position_sources
|
||||
.retain(|id, _| awake.iter().any(|target| matches!(target, Awake::Position { id: awake_id, .. } if awake_id == id)));
|
||||
self.woken_in_gesture.retain(|target| awake.contains(target));
|
||||
}
|
||||
|
||||
/// The woken targets, oldest first.
|
||||
@@ -739,7 +721,7 @@ impl SnapSession {
|
||||
Awake::Anchor { layer, .. } | Awake::Curve { layer, .. } | Awake::Box { layer } => !changed.contains(layer),
|
||||
Awake::Position { id, .. } => position_sources.get(id).is_none_or(|sources| !sources.iter().any(|layer| changed.contains(layer))),
|
||||
});
|
||||
self.forget_targets_gone_to_sleep();
|
||||
self.forget_sources_of_sleeping_positions();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1118,45 +1100,6 @@ mod tests {
|
||||
assert!(session.tick(1000 + WAKE_DWELL_IN_GESTURE));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_gesture_keeps_track_of_only_the_targets_it_woke_that_are_still_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(100., 100., 300., 240.).await;
|
||||
editor.draw_rect(500., 100., 700., 240.).await;
|
||||
let mut session = SnapSession::default();
|
||||
let input = InputPreprocessorMessageHandler::default();
|
||||
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
|
||||
|
||||
// Once the limit has put the first edge back to sleep, resting on it again wakes it a second time
|
||||
let along_edges = [(150., 100.), (300., 140.), (250., 240.), (100., 200.), (550., 100.), (700., 140.), (150., 100.)];
|
||||
for (index, position) in along_edges.into_iter().enumerate() {
|
||||
assert!(rest(&mut session, &editor, position.into(), index as u64 * 2000), "nothing woke at {position:?}");
|
||||
}
|
||||
assert_eq!(session.woken_in_gesture, session.awake);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn what_a_gesture_wakes_goes_back_to_sleep_when_it_ends_while_what_was_woken_before_it_stays_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(100., 100., 300., 240.).await;
|
||||
let mut session = SnapSession::default();
|
||||
|
||||
// The top edge is woken before the gesture, and the right edge during it
|
||||
assert!(rest(&mut session, &editor, DVec2::new(150., 100.), 0));
|
||||
let woken_before = session.awake.clone();
|
||||
|
||||
let input = InputPreprocessorMessageHandler::default();
|
||||
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
|
||||
snap_at_time(&mut session, &editor, DVec2::new(300., 140.), 2000);
|
||||
assert!(session.tick(2000 + WAKE_DWELL_IN_GESTURE));
|
||||
assert_eq!(session.awake.len(), 2);
|
||||
|
||||
session.end_gesture();
|
||||
assert_eq!(session.awake, woken_before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_the_latest_few_woken_targets_stay_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
Loaded 100 of 266 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user