mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-06 08:13:40 -10:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6015864c1f | ||
|
|
64a767b94e | ||
|
|
2e26ebf123 | ||
|
|
df1434ddff | ||
|
|
13bb1687b9 | ||
|
|
674221fbc3 | ||
|
|
1300b4f92a | ||
|
|
c0778752ab | ||
|
|
27cded81af | ||
|
|
d5fdb12320 |
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -176,8 +176,6 @@ jobs:
|
||||
env:
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
# GPU tests made through `for_tests()` fail rather than skip when the software Vulkan driver above can't make a device
|
||||
WGPU_BACKEND: vulkan
|
||||
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
|
||||
run: >-
|
||||
cargo test --workspace --all-features
|
||||
|
||||
@@ -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
+47
-10
@@ -585,7 +585,6 @@ name = "blending-nodes"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"futures",
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
@@ -593,7 +592,6 @@ dependencies = [
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2500,6 +2498,7 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graph-ui-types",
|
||||
"graphene-animation",
|
||||
"graphene-application-io",
|
||||
"graphene-canvas-utils",
|
||||
@@ -2537,6 +2536,44 @@ dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graph-ui"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graph-ui-icons",
|
||||
"graph-ui-types",
|
||||
"graphene-std",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"rendering",
|
||||
"svg-convert",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
"vello_gpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graph-ui-icons"
|
||||
version = "0.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "graph-ui-types"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graph-layout",
|
||||
"graphene-hash",
|
||||
"graphic-types",
|
||||
"serde",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graphene-animation"
|
||||
version = "0.0.0"
|
||||
@@ -2677,6 +2714,7 @@ dependencies = [
|
||||
"math-nodes",
|
||||
"node-macro",
|
||||
"path-bool-nodes",
|
||||
"raster-kernels",
|
||||
"raster-nodes",
|
||||
"rendering",
|
||||
"repeat-nodes",
|
||||
@@ -2874,6 +2912,7 @@ dependencies = [
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graph-layout",
|
||||
"graph-ui",
|
||||
"graphene-hash",
|
||||
"graphene-std",
|
||||
"graphite-proc-macros",
|
||||
@@ -5438,11 +5477,9 @@ dependencies = [
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"graphic-types",
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"node-macro",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5749,6 +5786,8 @@ dependencies = [
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"raster-types",
|
||||
"thiserror 2.0.21",
|
||||
"vector-types",
|
||||
@@ -5773,14 +5812,12 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8079,6 +8116,7 @@ dependencies = [
|
||||
"log",
|
||||
"node-macro",
|
||||
"ollev",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -8086,7 +8124,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",
|
||||
@@ -8101,7 +8139,7 @@ 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",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -8115,7 +8153,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",
|
||||
@@ -8586,7 +8624,6 @@ dependencies = [
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"svg-convert",
|
||||
"thiserror 2.0.21",
|
||||
"vello_gpu",
|
||||
"web-sys",
|
||||
|
||||
+9
-3
@@ -34,6 +34,9 @@ members = [
|
||||
"node-graph/libraries/*",
|
||||
"node-graph/nodes/*",
|
||||
"node-graph/graph-craft",
|
||||
"node-graph/graph-ui",
|
||||
"node-graph/graph-ui/icons",
|
||||
"node-graph/graph-ui/types",
|
||||
"node-graph/graphene-cli",
|
||||
"node-graph/nodes/gstd",
|
||||
"node-graph/interpreted-executor",
|
||||
@@ -112,6 +115,9 @@ vectorize-nodes = { path = "node-graph/nodes/vectorize" }
|
||||
math-nodes = { path = "node-graph/nodes/math" }
|
||||
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
|
||||
graph-craft = { path = "node-graph/graph-craft" }
|
||||
graph-ui = { path = "node-graph/graph-ui" }
|
||||
graph-ui-icons = { path = "node-graph/graph-ui/icons" }
|
||||
graph-ui-types = { path = "node-graph/graph-ui/types" }
|
||||
document-format = { path = "document/format" }
|
||||
document-graph-storage = { path = "document/graph-storage", default-features = false }
|
||||
document-container = { path = "document/container" }
|
||||
@@ -315,6 +321,6 @@ 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" }
|
||||
@@ -234,7 +234,11 @@ impl RenderState {
|
||||
WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true),
|
||||
WgpuCurrentSurfaceTexture::Occluded => return Ok(()),
|
||||
WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
|
||||
WgpuCurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated),
|
||||
WgpuCurrentSurfaceTexture::Outdated => {
|
||||
self.surface.configure(&self.executor.context().device, &self.config);
|
||||
window.request_redraw();
|
||||
return Ok(());
|
||||
}
|
||||
WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
|
||||
WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
|
||||
};
|
||||
@@ -327,7 +331,6 @@ impl RenderState {
|
||||
pub(crate) enum RenderError {
|
||||
OutdatedUITextureError,
|
||||
SurfaceLost,
|
||||
SurfaceOutdated,
|
||||
SurfaceTimeout,
|
||||
SurfaceValidation,
|
||||
}
|
||||
|
||||
@@ -44,6 +44,8 @@ pub enum ConversionError {
|
||||
IndexOverflow(usize),
|
||||
#[error("Node ID {0} is used by more than one node in the document")]
|
||||
DuplicateNodeId(u64),
|
||||
#[error("The transient node {0} cannot be saved")]
|
||||
TransientNode(String),
|
||||
}
|
||||
|
||||
/// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for
|
||||
@@ -559,7 +561,11 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
}
|
||||
|
||||
// Nodes the binary doesn't register, such as in tests, are at their first version
|
||||
let version = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|metadata| metadata.version)).unwrap_or(1);
|
||||
let registered = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|node| (node.version, node.flags)));
|
||||
let (version, flags) = registered.unwrap_or((1, Default::default()));
|
||||
if flags.transient {
|
||||
return Err(ConversionError::TransientNode(identifier_str));
|
||||
}
|
||||
let EncodedDeclaration { id, hash, bytes, proto } =
|
||||
EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
|
||||
|
||||
|
||||
@@ -657,6 +657,41 @@ fn a_node_id_used_in_two_networks_is_rejected() {
|
||||
assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transient_node_is_rejected() {
|
||||
use core_types::registry::{NODE_METADATA, NodeFlags, NodeMetadata};
|
||||
|
||||
let identifier = ProtoNodeIdentifier::new("test::TransientNode");
|
||||
let metadata = NodeMetadata {
|
||||
display_name: "Transient",
|
||||
category: "",
|
||||
icon: None,
|
||||
fields: Vec::new(),
|
||||
description: "",
|
||||
inspector: None,
|
||||
context_features: Vec::new(),
|
||||
flags: NodeFlags {
|
||||
transient: true,
|
||||
..Default::default()
|
||||
},
|
||||
version: 1,
|
||||
output_fields: None,
|
||||
};
|
||||
NODE_METADATA.lock().unwrap().insert(identifier.clone(), metadata);
|
||||
|
||||
let mut network = create_simple_network();
|
||||
network.nodes.insert(
|
||||
NodeId(100),
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
let result = Registry::convert_from_runtime(&network, &crate::NoMetadata, &Default::default(), PeerId(0));
|
||||
assert!(matches!(result, Err(crate::from_runtime::ConversionError::TransientNode(_))));
|
||||
}
|
||||
|
||||
/// A node input referencing a node in a different network can't be remapped to a valid local runtime
|
||||
/// ID, so conversion must reject it rather than emit a dangling reference.
|
||||
#[test]
|
||||
|
||||
@@ -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,8 +1,5 @@
|
||||
//! Migrations of the nodes in `graphene_core`.
|
||||
|
||||
mod fill_v1;
|
||||
mod passthrough_from_read_attribute_gradient_form_node;
|
||||
mod passthrough_from_footprint_value;
|
||||
mod passthrough_from_upload_texture_node;
|
||||
mod renames;
|
||||
mod vary_colors_from_assign_colors;
|
||||
@@ -1,37 +0,0 @@
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// 'Footprint Value' is gone with the footprint input of 'Rasterize', whose migration takes over the inputs of one feeding it. One read
|
||||
/// elsewhere passes on its empty primary input instead, since nothing else takes a footprint.
|
||||
#[migration("math_nodes::FootprintValueNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
||||
pub fn passthrough_from_footprint_value(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(3, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PassthroughFromFootprintValue, &contract());
|
||||
check_undo(&PassthroughFromFootprintValue, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_primary_input_and_drops_the_transform_and_resolution() {
|
||||
let (primary, transform, resolution) = (literal(()), literal(1.), literal(2.));
|
||||
|
||||
let mut fixture = Fixture::new(&PassthroughFromFootprintValue);
|
||||
let footprint_value = fixture.add(decl!("math_nodes::FootprintValueNode"@1), vec![primary.clone(), transform, resolution]);
|
||||
let migrated = fixture.migrate(&PassthroughFromFootprintValue).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, footprint_value), [primary]);
|
||||
}
|
||||
}
|
||||
-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,4 +1 @@
|
||||
//! Migrations of the nodes in `graphene_std`.
|
||||
|
||||
mod rasterize_v1;
|
||||
mod renames;
|
||||
@@ -1,276 +0,0 @@
|
||||
use migration_core::{Declaration, Graph, InputConnector, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Upstream, decl, encode, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
|
||||
const FOOTPRINT: u32 = 1;
|
||||
const RASTERIZE: Declaration = decl!("graphene_std::platform_application_io::RasterizeNode"@1);
|
||||
|
||||
/// Matched at any version, since naming one would order this migration after the one turning 'Footprint Value' into it, which must come after.
|
||||
const PASSTHROUGH: &str = "graphene_core::ops::PassthroughNode";
|
||||
|
||||
/// The default area, a square 1000 px across centered at (500, 500), and its resolution of one pixel per px.
|
||||
const DEFAULT_TRANSFORM: [f64; 6] = [1000., 0., 0., 1000., 500., 500.];
|
||||
const DEFAULT_RESOLUTION: [f64; 2] = [1000., 1000.];
|
||||
|
||||
/// A translation by half a unit, which moves a unit square anchored at its corner to one centered on the origin.
|
||||
const CORNER_TO_CENTER: [f64; 6] = [1., 0., 0., 1., 0.5, 0.5];
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
DVec2([f64; 2]),
|
||||
DAffine2([f64; 6]),
|
||||
Footprint(Footprint),
|
||||
}
|
||||
|
||||
/// Frozen mirror of the removed `Footprint` value, leaving out the render quality 'Rasterize' ignored.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Footprint {
|
||||
transform: [f64; 6],
|
||||
resolution: [u32; 2],
|
||||
}
|
||||
|
||||
/// 'Rasterize' takes its footprint's area as a transform placing a unit square centered on its origin, rather than anchored at its corner,
|
||||
/// then its resolution. A 'Footprint Value' node feeding it, directly or through reroutes, hands over its own inputs and goes once nothing
|
||||
/// else reads it. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph.
|
||||
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
|
||||
pub fn rasterize_v1(node: &Node, graph: &Graph, inputs: &mut Inputs, upstream: &mut Upstream) -> Result<(), MigrationError> {
|
||||
let Some(footprint) = node.inputs().get(FOOTPRINT as usize) else {
|
||||
return Err(MigrationError::invariant("Rasterize has a Footprint input"));
|
||||
};
|
||||
let footprint = through_reroutes(*graph, &footprint.input);
|
||||
|
||||
let (transform, resolution) = match footprint {
|
||||
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(footprint) {
|
||||
Some(Tagged::Footprint(footprint)) => (
|
||||
value(Tagged::DAffine2(centered(footprint.transform)), *exposed),
|
||||
value(Tagged::DVec2(footprint.resolution.map(f64::from)), *exposed),
|
||||
),
|
||||
_ => defaults(*exposed),
|
||||
},
|
||||
NodeInput::Node { id, index: 0 } if graph.declaration(*id) == Some(decl!("math_nodes::FootprintValueNode"@1)) => {
|
||||
let parameters = graph.node(*id).map(|footprint_value| footprint_value.inputs()).and_then(|slots| Some((slots.get(1)?, slots.get(2)?)));
|
||||
let Some((transform, resolution)) = parameters else {
|
||||
return Err(MigrationError::invariant("Footprint Value has Transform and Resolution inputs"));
|
||||
};
|
||||
|
||||
// Each Rasterize node it feeds takes over its inputs, so it's only needed by whatever else reads it
|
||||
let readers = graph.consumers(OutputConnector { node: *id, output: 0 });
|
||||
let only_feeds_rasterize = readers
|
||||
.iter()
|
||||
.all(|reader| matches!(reader, InputConnector::Node { node, input: FOOTPRINT } if graph.declaration(*node) == Some(RASTERIZE)));
|
||||
if only_feeds_rasterize {
|
||||
upstream.remove_node(*id);
|
||||
}
|
||||
|
||||
let multiply = decl!("math_nodes::MultiplyNode"@1);
|
||||
(centered_transform_input(&transform.input, multiply, upstream), resolution.input.clone())
|
||||
}
|
||||
_ => defaults(true),
|
||||
};
|
||||
|
||||
inputs.set(FOOTPRINT, transform);
|
||||
inputs.insert(FOOTPRINT + 1, resolution);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where `input` reads from past any 'Passthrough' nodes rerouting it, which pass their content along unchanged.
|
||||
fn through_reroutes<'a>(graph: Graph<'a>, mut input: &'a NodeInput) -> &'a NodeInput {
|
||||
let mut visited = HashSet::new();
|
||||
|
||||
// A cycle of reroutes leads nowhere else, so revisiting one ends the walk
|
||||
while let NodeInput::Node { id, index: 0 } = input
|
||||
&& visited.insert(*id)
|
||||
&& graph.declaration(*id).is_some_and(|declaration| declaration.identifier == PASSTHROUGH)
|
||||
&& let Some(content) = graph.node(*id).and_then(|node| node.inputs().first())
|
||||
{
|
||||
input = &content.input;
|
||||
}
|
||||
|
||||
input
|
||||
}
|
||||
|
||||
/// The area transform from a 'Footprint Value' node's transform input, through a `multiply` node centering its unit square if it's wired.
|
||||
fn centered_transform_input(transform: &NodeInput, multiply: Declaration, upstream: &mut Upstream) -> NodeInput {
|
||||
match transform {
|
||||
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(transform) {
|
||||
Some(Tagged::DAffine2(transform)) => value(Tagged::DAffine2(centered(transform)), *exposed),
|
||||
_ => value(Tagged::DAffine2(DEFAULT_TRANSFORM), *exposed),
|
||||
},
|
||||
wire => {
|
||||
let multiply = upstream.add_node(NewNode {
|
||||
declaration: multiply,
|
||||
inputs: vec![wire.clone(), literal(Tagged::DAffine2(CORNER_TO_CENTER))],
|
||||
});
|
||||
NodeInput::Node { id: multiply, index: 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The transform placing a unit square centered on its origin over the one `transform` places anchored at its corner, which is `transform`
|
||||
/// followed by a translation of half a unit, computed in the order a `DAffine2` product computes it.
|
||||
fn centered([x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]: [f64; 6]) -> [f64; 6] {
|
||||
[
|
||||
x_axis_x,
|
||||
x_axis_y,
|
||||
y_axis_x,
|
||||
y_axis_y,
|
||||
x_axis_x * 0.5 + y_axis_x * 0.5 + translation_x,
|
||||
x_axis_y * 0.5 + y_axis_y * 0.5 + translation_y,
|
||||
]
|
||||
}
|
||||
|
||||
fn defaults(exposed: bool) -> (NodeInput, NodeInput) {
|
||||
(value(Tagged::DAffine2(DEFAULT_TRANSFORM), exposed), value(Tagged::DVec2(DEFAULT_RESOLUTION), exposed))
|
||||
}
|
||||
|
||||
fn value(value: Tagged, exposed: bool) -> NodeInput {
|
||||
NodeInput::Value { value: encode(&value), exposed }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const FOOTPRINT_VALUE: Declaration = decl!("math_nodes::FootprintValueNode"@1);
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| match slot {
|
||||
1 => literal(Tagged::Footprint(Footprint {
|
||||
transform: [random.below(10) as f64, 0., 0., random.below(10) as f64, random.below(10) as f64, random.below(10) as f64],
|
||||
resolution: [random.below(10) as u32, random.below(10) as u32],
|
||||
})),
|
||||
_ => literal(random.below(10) as f64),
|
||||
})
|
||||
}
|
||||
|
||||
/// Rasterize's inputs with `footprint` between its artwork and its executor.
|
||||
fn rasterize_inputs(footprint: NodeInput) -> Vec<NodeInput> {
|
||||
vec![literal(0.), footprint, NodeInput::Scope("wgpu-executor".into())]
|
||||
}
|
||||
|
||||
/// Rasterize's migrated inputs with `transform` and `resolution` between its artwork and its executor.
|
||||
fn migrated_inputs(transform: NodeInput, resolution: NodeInput) -> Vec<NodeInput> {
|
||||
vec![literal(0.), transform, resolution, NodeInput::Scope("wgpu-executor".into())]
|
||||
}
|
||||
|
||||
fn footprint_value_inputs(transform: NodeInput, resolution: NodeInput) -> Vec<NodeInput> {
|
||||
vec![literal(()), transform, resolution]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RasterizeV1, &contract());
|
||||
check_undo(&RasterizeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_footprint_becomes_the_transform_centered_on_its_area_and_its_resolution() {
|
||||
// The 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40)
|
||||
let footprint = Footprint {
|
||||
transform: [500., 0., 0., 250., -20., 40.],
|
||||
resolution: [64, 32],
|
||||
};
|
||||
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint))));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let expected = migrated_inputs(literal(Tagged::DAffine2([500., 0., 0., 250., 230., 165.])), literal(Tagged::DVec2([64., 32.])));
|
||||
assert_eq!(fixture.declaration_of(&migrated, rasterize), Some(decl!("graphene_std::platform_application_io::RasterizeNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, rasterize), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_footprint_becomes_the_default_area_and_resolution() {
|
||||
let footprint = Footprint {
|
||||
transform: [1000., 0., 0., 1000., 0., 0.],
|
||||
resolution: [1000, 1000],
|
||||
};
|
||||
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint))));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let (transform, resolution) = defaults(false);
|
||||
assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_footprint_value_node_hands_over_its_inputs_and_goes() {
|
||||
let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.]));
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let resolution_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||
let resolution = NodeInput::Node { id: resolution_source, index: 0 };
|
||||
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone()));
|
||||
let first = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||
let second = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution);
|
||||
assert_eq!(fixture.inputs(&migrated, first), expected);
|
||||
assert_eq!(fixture.inputs(&migrated, second), expected);
|
||||
assert_eq!(fixture.declaration_of(&migrated, footprint_value), None, "nothing else reads the Footprint Value node");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_footprint_value_node_hands_over_its_inputs_through_reroutes() {
|
||||
let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.]));
|
||||
let resolution = literal(Tagged::DVec2([30., 20.]));
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone()));
|
||||
let first_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@1), vec![NodeInput::Node { id: footprint_value, index: 0 }]);
|
||||
let second_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@2), vec![NodeInput::Node { id: first_reroute, index: 0 }]);
|
||||
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: second_reroute, index: 0 }));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution);
|
||||
assert_eq!(fixture.inputs(&migrated, rasterize), expected);
|
||||
assert_eq!(
|
||||
fixture.declaration_of(&migrated, footprint_value),
|
||||
Some(FOOTPRINT_VALUE),
|
||||
"the reroute still reads the Footprint Value node"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wired_footprint_value_transform_reaches_the_area_through_a_multiply_node() {
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let transform_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||
let wire = NodeInput::Node { id: transform_source, index: 0 };
|
||||
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(wire.clone(), literal(Tagged::DVec2([30., 20.]))));
|
||||
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let inputs = fixture.inputs(&migrated, rasterize);
|
||||
let NodeInput::Node { id: multiply, index: 0 } = inputs[1] else {
|
||||
panic!("the area should be wired from a Multiply node");
|
||||
};
|
||||
assert_eq!(inputs, migrated_inputs(NodeInput::Node { id: multiply, index: 0 }, literal(Tagged::DVec2([30., 20.]))));
|
||||
assert_eq!(fixture.declaration_of(&migrated, multiply), Some(decl!("math_nodes::MultiplyNode"@1)));
|
||||
assert_eq!(fixture.inputs(&migrated, multiply), [wire, literal(Tagged::DAffine2(CORNER_TO_CENTER))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_footprint_value_node_read_elsewhere_stays() {
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(literal(Tagged::DAffine2(CORNER_TO_CENTER)), literal(Tagged::DVec2([1., 1.]))));
|
||||
fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||
fixture.export(NodeInput::Node { id: footprint_value, index: 0 });
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(FOOTPRINT_VALUE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_other_wire_leaves_the_defaults_shown_in_the_graph() {
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: source, index: 0 }));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let (transform, resolution) = defaults(true);
|
||||
assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution));
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
// Version 2 moves these nodes' parameters ahead of their scope inputs, and only the compiler inserts them, so no stored node has version 1's order
|
||||
rename!("graphene_std::platform_application_io::ResourceNode"@1 => @2);
|
||||
rename!("graphene_std::render_background::RenderBackgroundNode"@1 => @2);
|
||||
rename!("graphene_std::render_cache::RenderOutputCacheNode"@1 => @2);
|
||||
rename!("graphene_std::render_node::RenderNode"@1 => @2);
|
||||
rename!("graphene_std::render_pixel_preview::RenderPixelPreviewNode"@1 => @2);
|
||||
|
||||
// Version 3 adds the scope and source ID inputs the render node spawns its readbacks with, which the compiler inserts along with the node
|
||||
rename!("graphene_std::render_node::RenderNode"@2 => @3);
|
||||
@@ -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;
|
||||
@@ -6,6 +6,5 @@ mod mandelbrot_v2;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod noise_pattern_v2;
|
||||
mod passthrough_from_extend_image_to_bounds;
|
||||
mod pattern_square;
|
||||
mod renames;
|
||||
@@ -1,36 +0,0 @@
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// 'Extend Image to Bounds' is gone, and the transparent pixels it padded an image with drew nothing, so it passes its image on and drops its bounds.
|
||||
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
||||
pub fn passthrough_from_extend_image_to_bounds(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(&PassthroughFromExtendImageToBounds, &contract());
|
||||
check_undo(&PassthroughFromExtendImageToBounds, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_image_and_drops_the_bounds() {
|
||||
let (image, bounds) = (literal(1.), literal(2.));
|
||||
|
||||
let mut fixture = Fixture::new(&PassthroughFromExtendImageToBounds);
|
||||
let extend = fixture.add(decl!("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1), vec![image.clone(), bounds]);
|
||||
let migrated = fixture.migrate(&PassthroughFromExtendImageToBounds).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, extend), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, extend), [image]);
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,3 @@ use migration_core::rename;
|
||||
|
||||
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
|
||||
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
|
||||
|
||||
// 'Image to Channels' became 'Into Channels', taking and giving graphics, whose stored input and channel outputs keep their places
|
||||
rename!("raster_nodes::adjustments::ImageToChannelsNode"@1 => "raster_nodes::channels::IntoChannelsNode"@2);
|
||||
|
||||
// 'Channels to Image' became 'From Channels', taking and giving graphics, whose stored inputs and output keep their places
|
||||
rename!("raster_nodes::std_nodes::ChannelsToImageNode"@1 => "raster_nodes::channels::FromChannelsNode"@2);
|
||||
|
||||
// 'Median Filter' became an effect taking any graphic, whose stored image and radius keep their places
|
||||
rename!("raster_nodes::filter::MedianFilterNode"@1 => @2);
|
||||
@@ -16,7 +16,7 @@ pub(crate) fn check_against(workspace: &Path, baseline: &str) -> Result<(), Stri
|
||||
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
|
||||
// Removal failing only leaves a temporary directory behind
|
||||
let _ = std::fs::remove_dir_all(&directory);
|
||||
let baseline_nodes = baseline_nodes?;
|
||||
let baseline_nodes: Vec<NodeSource> = baseline_nodes?.into_iter().filter(|node| !node.transient).collect();
|
||||
|
||||
let problems = api_problems(&baseline_nodes, ¤t, &migrations);
|
||||
if !problems.is_empty() {
|
||||
@@ -71,7 +71,7 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
|
||||
// Moving a module keeps the function and its API, which is what a rename looks like
|
||||
let moved = current
|
||||
.iter()
|
||||
.find(|new| !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
|
||||
.find(|new| !new.transient && !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
|
||||
problems.push(match moved {
|
||||
Some(new) => format!(
|
||||
"`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`",
|
||||
@@ -83,6 +83,9 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
|
||||
});
|
||||
continue;
|
||||
};
|
||||
if new.transient {
|
||||
continue;
|
||||
}
|
||||
|
||||
if new.version < version {
|
||||
problems.push(format!("`{identifier}` went back from version {version} to {}", new.version));
|
||||
@@ -123,6 +126,7 @@ mod tests {
|
||||
NodeSource {
|
||||
identifier: identifier.to_string(),
|
||||
version,
|
||||
transient: false,
|
||||
function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(),
|
||||
file: PathBuf::from("lib.rs"),
|
||||
signature: signature.to_string(),
|
||||
@@ -168,6 +172,15 @@ mod tests {
|
||||
assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_turned_transient_needs_no_migration() {
|
||||
let transient = NodeSource {
|
||||
transient: true,
|
||||
..node("a::b", 1, "(x: f64, y: f64)")
|
||||
};
|
||||
assert!(api_problems(&[node("a::b", 2, "(x: f64)")], &[transient], &[]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bump_needs_a_migration_from_the_baseline_version() {
|
||||
let bumped = [node("a::b", 3, "(x: f64)")];
|
||||
|
||||
@@ -117,6 +117,7 @@ fn check(workspace: &Path) -> Result<(), String> {
|
||||
|
||||
let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))?
|
||||
.into_iter()
|
||||
.filter(|node| !node.transient)
|
||||
.map(|node| (node.identifier, node.version))
|
||||
.collect();
|
||||
let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?;
|
||||
|
||||
@@ -10,6 +10,7 @@ pub(crate) struct NodeSource {
|
||||
/// function name with a `Node` suffix.
|
||||
pub identifier: String,
|
||||
pub version: u32,
|
||||
pub transient: bool,
|
||||
pub function: String,
|
||||
pub file: PathBuf,
|
||||
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
|
||||
@@ -119,7 +120,9 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
|
||||
|
||||
let mut path = module_path.join("::");
|
||||
let mut version = 1;
|
||||
let mut transient = false;
|
||||
for argument in arguments {
|
||||
transient |= argument.path().is_ident("transient");
|
||||
let syn::Meta::List(list) = argument else { continue };
|
||||
if list.path.is_ident("path") {
|
||||
path = list.tokens.to_string().replace(' ', "");
|
||||
@@ -147,6 +150,7 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
|
||||
Some(NodeSource {
|
||||
identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)),
|
||||
version,
|
||||
transient,
|
||||
function: function_name,
|
||||
file: file.to_path_buf(),
|
||||
signature,
|
||||
@@ -171,4 +175,24 @@ mod tests {
|
||||
assert!(!node.signature.contains("cache"), "{}", node.signature);
|
||||
assert!(node.signature.contains("image"), "{}", node.signature);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_transient_attribute_is_read() {
|
||||
let transient: syn::ItemFn = syn::parse_quote! {
|
||||
#[node_macro::node(transient, memoize)]
|
||||
fn draw(_: impl Ctx) -> List<Vector> {
|
||||
List::new()
|
||||
}
|
||||
};
|
||||
let saved: syn::ItemFn = syn::parse_quote! {
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw(_: impl Ctx) -> List<Vector> {
|
||||
List::new()
|
||||
}
|
||||
};
|
||||
let node = |function| node_source(function, Path::new("lib.rs"), &["drawing".to_string()]).expect("the function is a node");
|
||||
|
||||
assert!(node(&transient).transient);
|
||||
assert!(!node(&saved).transient);
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,7 @@ pub(crate) const MIGRATION_CRATES: [&str; 2] = [MIGRATIONS, "document/migrations
|
||||
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
|
||||
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename.
|
||||
pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> {
|
||||
let nodes = find_nodes(&workspace.join(NODE_CRATES))?;
|
||||
let nodes: Vec<NodeSource> = find_nodes(&workspace.join(NODE_CRATES))?.into_iter().filter(|node| !node.transient).collect();
|
||||
let migrations = workspace.join(MIGRATIONS);
|
||||
|
||||
match (command, arguments) {
|
||||
|
||||
+2
-1
@@ -14,7 +14,7 @@ publish.workspace = true
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
|
||||
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "graph-ui/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
@@ -35,6 +35,7 @@ preprocessor = { workspace = true }
|
||||
math-parser = { workspace = true }
|
||||
snapping = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
graph-ui = { workspace = true, features = ["serde"] }
|
||||
|
||||
# Workspace dependencies
|
||||
js-sys = { workspace = true }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// GRAPH
|
||||
pub const GRID_SIZE: u32 = 24;
|
||||
pub const GRID_SIZE: u32 = graph_ui::metrics::GRID_SIZE as u32;
|
||||
pub const HALF_GRID_SIZE: u32 = GRID_SIZE / 2;
|
||||
pub const EXPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72;
|
||||
pub const EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP: u32 = 120;
|
||||
@@ -11,8 +11,6 @@ pub const STACK_VERTICAL_GAP: i32 = 3;
|
||||
pub const LAYER_INDENT_OFFSET: i32 = 8;
|
||||
/// Horizontal grid width of a non-layer node in a chain.
|
||||
pub const NODE_CHAIN_WIDTH: i32 = 7;
|
||||
/// How quickly a dragged node glides into the grid cell it moves to, as the time it takes to cover all but 1/e (about 37%) of the remaining distance.
|
||||
pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.;
|
||||
|
||||
// VIEWPORT
|
||||
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
|
||||
|
||||
@@ -80,10 +80,8 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::UpdateLayerPanel,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendWires))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendGlide))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::UpdateVisibleNodes,
|
||||
NodeGraphMessageDiscriminant::UpdateLayersInView,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::SendSelectedNodes,
|
||||
|
||||
@@ -13,7 +13,7 @@ pub enum ClipboardMessage {
|
||||
CopyLayers,
|
||||
CutLayers,
|
||||
WriteItems { items: Vec<ApplicationDataItem> },
|
||||
Rendered { id: u64, svg: Result<Option<String>, String> },
|
||||
Rendered { id: u64, svg: Option<String> },
|
||||
Loaded { id: u64, content: DataTransfer },
|
||||
PasteItems { items: Vec<ApplicationDataItem> },
|
||||
PasteLayers { entries: Vec<ApplicationDataLayer> },
|
||||
|
||||
@@ -246,15 +246,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
let Some(PendingCopy::Rendering { items, loads, .. }) = self.pending_copy.take_if(|pending| pending.id() == id) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// The layers still copy, without an SVG
|
||||
let svg = svg.unwrap_or_else(|error| {
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Unable to copy as SVG".to_string(),
|
||||
description: error,
|
||||
});
|
||||
None
|
||||
});
|
||||
self.finish_copy(items, loads, svg, resource_storage, responses);
|
||||
}
|
||||
ClipboardMessage::Loaded { id, content } => {
|
||||
@@ -674,210 +665,16 @@ mod test {
|
||||
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
|
||||
}
|
||||
|
||||
/// The bounds of what the SVG draws, strokes included, and the size of its frame.
|
||||
fn drawn_bounds_and_frame(svg: &str) -> (usvg::Rect, usvg::Size) {
|
||||
let tree = usvg::Tree::from_str(svg, &usvg::Options::default()).unwrap_or_else(|error| panic!("the SVG should parse ({error}): {svg}"));
|
||||
(tree.root().abs_stroke_bounding_box(), tree.size())
|
||||
}
|
||||
|
||||
// A layer is copied as what it adds to the group holding it, so the group's move is left out of both its frame and what it draws
|
||||
#[cfg_attr(miri, ignore)]
|
||||
#[tokio::test]
|
||||
async fn copied_svg_frames_a_grouped_layer_without_its_groups_transform() {
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use glam::DAffine2;
|
||||
async fn copied_svg_leaves_out_the_layers_that_are_not_copied() {
|
||||
let mut editor = create_editor_with_three_layers().await;
|
||||
let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node();
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 50.).await;
|
||||
let rectangle = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle");
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
let group = rectangle.parent(editor.active_document().metadata()).expect("the rectangle should be grouped");
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::TransformChange {
|
||||
layer: group,
|
||||
transform: DAffine2::from_translation(DVec2::new(500., 300.)),
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![rectangle.to_node()] }).await;
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
let svg = copied_svg(&clipboard).expect("the grouped rectangle should render an SVG");
|
||||
|
||||
// The frame grows past the stroke by as far as its miter joins could reach
|
||||
let (drawn, frame) = drawn_bounds_and_frame(svg);
|
||||
let within_frame = drawn.left() >= 0. && drawn.top() >= 0. && drawn.right() <= frame.width() && drawn.bottom() <= frame.height();
|
||||
assert!(within_frame, "the rectangle should be drawn within the frame, at {drawn:?} in {frame:?}: {svg}");
|
||||
assert!(frame.width() < 120. && frame.height() < 70., "the frame should hold only the rectangle: {svg}");
|
||||
}
|
||||
|
||||
// Any node can be shown as a layer, which adds everything it outputs
|
||||
#[cfg_attr(miri, ignore)]
|
||||
#[tokio::test]
|
||||
async fn copied_svg_draws_a_layer_that_is_not_a_merge() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 50.).await;
|
||||
let rectangle = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle").to_node();
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
let content_node = network_interface
|
||||
.upstream_flow_back_from_nodes(vec![rectangle], &[], FlowType::HorizontalFlow)
|
||||
.nth(1)
|
||||
.expect("the layer should have a content chain");
|
||||
network_interface.set_to_node_or_layer(&content_node, &[], true);
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![content_node] }).await;
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
let svg = copied_svg(&clipboard).expect("the layer should render an SVG");
|
||||
assert!(svg.contains("<path"), "the SVG should draw the rectangle: {svg}");
|
||||
}
|
||||
|
||||
// An artboard holds its own content, so the other layers copied with it are left out of the SVG
|
||||
#[cfg_attr(miri, ignore)]
|
||||
#[tokio::test]
|
||||
async fn copied_svg_of_artboards_and_other_layers_draws_only_the_artboards() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Artboard, 0., 0., 200., 100., ModifierKeys::empty()).await;
|
||||
editor.draw_rect(500., 500., 600., 600.).await;
|
||||
|
||||
let layers = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
let svg = copied_svg(&clipboard).expect("the artboard should render an SVG");
|
||||
|
||||
let (_, frame) = drawn_bounds_and_frame(svg);
|
||||
assert!(
|
||||
(frame.width() - 200.).abs() < 1. && (frame.height() - 100.).abs() < 1.,
|
||||
"the SVG should be framed to the artboard alone: {svg}"
|
||||
);
|
||||
}
|
||||
|
||||
// The frame keeps the content's exact size, rather than whole pixels that would round a fifth of a unit away to nothing
|
||||
#[cfg_attr(miri, ignore)]
|
||||
#[tokio::test]
|
||||
async fn copied_svg_keeps_a_fractional_frame() {
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use glam::DAffine2;
|
||||
use graphene_std::vector::style::Stroke;
|
||||
|
||||
// A square shrunk to a fifth of a unit across, with only a fill
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle");
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::StrokeSet {
|
||||
layer,
|
||||
color: None,
|
||||
stroke: Stroke::default(),
|
||||
})
|
||||
.await;
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::TransformSet {
|
||||
layer,
|
||||
transform: DAffine2::from_scale(DVec2::splat(0.002)),
|
||||
transform_in: TransformIn::Local,
|
||||
skip_rerender: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
let svg = copied_svg(&clipboard).expect("the square should render an SVG");
|
||||
|
||||
let (drawn, frame) = drawn_bounds_and_frame(svg);
|
||||
assert!(
|
||||
(frame.width() - 0.2).abs() < 1e-4 && (frame.height() - 0.2).abs() < 1e-4,
|
||||
"the frame should be the square's size: {svg}"
|
||||
);
|
||||
assert!((drawn.width() - 0.2).abs() < 1e-4 && drawn.left().abs() < 1e-4, "the square should fill the frame: {svg}");
|
||||
}
|
||||
|
||||
/// Sets the viewport to `size` pixels and gives back the size of the part of the document it shows.
|
||||
async fn view_of_size(editor: &mut EditorTestUtils, size: DVec2) -> DVec2 {
|
||||
use graphene_std::math::quad::Quad;
|
||||
|
||||
editor.set_viewport_size(DVec2::ZERO, size).await;
|
||||
let viewport_to_document = editor.active_document().metadata().document_to_viewport.inverse();
|
||||
let [min, max] = (viewport_to_document * Quad::from_box([DVec2::ZERO, size])).bounding_box();
|
||||
max - min
|
||||
}
|
||||
|
||||
// Content drawn for its view, like a brush stroke's image or tiles covering the view, is framed to the view it was copied in
|
||||
#[cfg_attr(miri, ignore)]
|
||||
#[tokio::test]
|
||||
async fn copied_svg_frames_content_drawn_for_its_view_to_that_view() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let view = view_of_size(&mut editor, DVec2::new(400., 300.)).await;
|
||||
let framed_to_view = |svg: &str| {
|
||||
let (_, frame) = drawn_bounds_and_frame(svg);
|
||||
(frame.width() as f64 - view.x).abs() < 1e-3 && (frame.height() as f64 - view.y).abs() < 1e-3
|
||||
};
|
||||
|
||||
// A brush stroke
|
||||
editor.handle_message(PreferencesMessage::BrushTool { enabled: true }).await;
|
||||
editor.drag_tool(ToolType::Brush, 50., 50., 150., 100., ModifierKeys::empty()).await;
|
||||
let brush = editor.active_document().metadata().all_layers().next().expect("the brush layer");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![brush.to_node()] }).await;
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
let svg = copied_svg(&clipboard).expect("the brush layer should render an SVG");
|
||||
assert!(framed_to_view(svg), "the brush layer should be framed to the {view} view: {svg}");
|
||||
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "the stroke should be the GPU's image: {svg}");
|
||||
|
||||
// A rectangle tiled across the view
|
||||
editor.draw_rect(0., 0., 20., 20.).await;
|
||||
let tiled = editor.active_document().metadata().all_layers().next().expect("the rectangle");
|
||||
let tile = DefinitionIdentifier::ProtoNode(graphene_std::repeat::tile::IDENTIFIER);
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type: tile, layer: tiled }).await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![tiled.to_node()] }).await;
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
let svg = copied_svg(&clipboard).expect("the tiled layer should render an SVG");
|
||||
assert!(framed_to_view(svg), "the tiled layer should be framed to the {view} view: {svg}");
|
||||
assert!(svg.matches("<path").count() > 1, "the view should hold several tiles: {svg}");
|
||||
}
|
||||
|
||||
#[cfg_attr(miri, ignore)]
|
||||
#[tokio::test]
|
||||
async fn copied_svg_draws_generators_as_the_gpus_render() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// A Mandelbrot layer, made from an image layer by feeding the fractal into its content instead
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.create_raster_image(graphene_std::raster::Image::new(1, 1, Color::BLACK), None).await;
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("the image layer").to_node();
|
||||
let mandelbrot = NodeId::new();
|
||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(mandelbrot),
|
||||
node_type: DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER),
|
||||
xy: None,
|
||||
add_transaction: true,
|
||||
});
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(mandelbrot),
|
||||
input_connector: InputConnector::node_at_index(layer, 1),
|
||||
});
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }).await;
|
||||
|
||||
// The SVG frames the fractal's body, hundreds of units across rather than the image's one, and embeds the GPU's image of it where its placeholder stood
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
let svg = copied_svg(&clipboard).expect("the Mandelbrot layer should render an SVG");
|
||||
let (_, frame) = drawn_bounds_and_frame(svg);
|
||||
assert!(frame.width() > 100., "{svg}");
|
||||
assert!(svg.matches("data:image/png;base64,").count() == 1 && !svg.contains("deferred-image"), "{svg}");
|
||||
let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG");
|
||||
assert_eq!(svg.matches("<path").count(), 1, "only the copied layer should be drawn: {svg}");
|
||||
}
|
||||
|
||||
/// - paste
|
||||
|
||||
+11
-11
@@ -1,8 +1,8 @@
|
||||
use crate::consts::{VIEWPORT_ZOOM_WHEEL_RATE, VIEWPORT_ZOOM_WHEEL_RATE_CHANGE};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::prelude::*;
|
||||
use graph_ui::wire::WireStyle;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct PreferencesDialogMessageContext<'a> {
|
||||
@@ -254,16 +254,16 @@ impl PreferencesDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
let graph_wire_style = RadioInput::new(vec![
|
||||
RadioEntryData::new(GraphWireStyle::Direct.to_string())
|
||||
.label(GraphWireStyle::Direct.to_string())
|
||||
.tooltip_label(GraphWireStyle::Direct.to_string())
|
||||
.tooltip_description(GraphWireStyle::Direct.tooltip_description())
|
||||
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::Direct }.into()),
|
||||
RadioEntryData::new(GraphWireStyle::GridAligned.to_string())
|
||||
.label(GraphWireStyle::GridAligned.to_string())
|
||||
.tooltip_label(GraphWireStyle::GridAligned.to_string())
|
||||
.tooltip_description(GraphWireStyle::GridAligned.tooltip_description())
|
||||
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::GridAligned }.into()),
|
||||
RadioEntryData::new("Direct")
|
||||
.label("Direct")
|
||||
.tooltip_label("Direct")
|
||||
.tooltip_description("Wires bend to run at an angle directly between nodes.")
|
||||
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: WireStyle::Direct }.into()),
|
||||
RadioEntryData::new("Grid-Aligned")
|
||||
.label("Grid-Aligned")
|
||||
.tooltip_label("Grid-Aligned")
|
||||
.tooltip_description("Wires follow the grid, running in straight lines between nodes.")
|
||||
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: WireStyle::GridAligned }.into()),
|
||||
])
|
||||
.selected_index(Some(preferences.graph_wire_style as u32))
|
||||
.sizing(WidgetSizing::default().shrink(false))
|
||||
|
||||
@@ -5,11 +5,9 @@ use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewIm
|
||||
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,
|
||||
};
|
||||
use crate::messages::portfolio::document::node_graph::graph_ui::GraphNameField;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuInformation, FrontendNodeType, FrontendRemoteCursor};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
use crate::messages::portfolio::ingest::utility_types::{DataTransfer, IngestAction};
|
||||
use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -65,8 +63,6 @@ pub enum FrontendMessage {
|
||||
SendUIMetadata {
|
||||
#[serde(rename = "nodeDescriptions")]
|
||||
node_descriptions: Vec<(String, String)>,
|
||||
#[serde(rename = "nodeIcons")]
|
||||
node_icons: Vec<(String, IconName)>,
|
||||
#[serde(rename = "nodeTypes")]
|
||||
node_types: Vec<FrontendNodeType>,
|
||||
},
|
||||
@@ -121,11 +117,6 @@ pub enum FrontendMessage {
|
||||
preferences: PreferencesMessageHandler,
|
||||
},
|
||||
TriggerTextCommit,
|
||||
/// Asks the frontend to enter inline-rename mode for a layer in the graph view.
|
||||
TriggerEditLayerNameInGraph {
|
||||
#[serde(rename = "nodeId")]
|
||||
node_id: NodeId,
|
||||
},
|
||||
TriggerVisitLink {
|
||||
url: String,
|
||||
},
|
||||
@@ -158,34 +149,11 @@ pub enum FrontendMessage {
|
||||
ColorPickerStartHistoryTransaction,
|
||||
/// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker />` forwards this as its `commitHistoryTransaction` event.
|
||||
ColorPickerCommitHistoryTransaction,
|
||||
UpdateImportsExports {
|
||||
/// If the primary import is not visible, then it is None.
|
||||
imports: Vec<Option<FrontendGraphOutput>>,
|
||||
/// If the primary export is not visible, then it is None.
|
||||
exports: Vec<Option<FrontendGraphInput>>,
|
||||
/// The primary import location.
|
||||
#[serde(rename = "importPosition")]
|
||||
import_position: (i32, i32),
|
||||
/// The primary export location.
|
||||
#[serde(rename = "exportPosition")]
|
||||
export_position: (i32, i32),
|
||||
/// The document network does not have an add import or export button.
|
||||
#[serde(rename = "addImportExport")]
|
||||
add_import_export: bool,
|
||||
},
|
||||
UpdateInSelectedNetwork {
|
||||
#[serde(rename = "inSelectedNetwork")]
|
||||
in_selected_network: bool,
|
||||
},
|
||||
/// Whether the network shown in the graph lies inside a built-in node, whose contents are read-only until made editable.
|
||||
UpdateNetworkReadOnly {
|
||||
#[serde(rename = "readOnly")]
|
||||
read_only: bool,
|
||||
},
|
||||
UpdateBox {
|
||||
#[serde(rename = "box")]
|
||||
box_selection: Option<BoxSelection>,
|
||||
},
|
||||
UpdateRemoteCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
@@ -199,6 +167,14 @@ pub enum FrontendMessage {
|
||||
UpdateGraphViewOverlay {
|
||||
open: bool,
|
||||
},
|
||||
UpdateGraphTooltip {
|
||||
label: String,
|
||||
description: String,
|
||||
},
|
||||
UpdateGraphNameField {
|
||||
field: Option<GraphNameField>,
|
||||
opens: bool,
|
||||
},
|
||||
UpdateWorkspacePanelLayout {
|
||||
#[serde(rename = "panelLayout")]
|
||||
panel_layout: WorkspacePanelLayout,
|
||||
@@ -225,36 +201,6 @@ pub enum FrontendMessage {
|
||||
source: String,
|
||||
result: Option<String>,
|
||||
},
|
||||
UpdateImportReorderIndex {
|
||||
#[serde(rename = "importIndex")]
|
||||
index: Option<usize>,
|
||||
},
|
||||
UpdateExportReorderIndex {
|
||||
#[serde(rename = "exportIndex")]
|
||||
index: Option<usize>,
|
||||
},
|
||||
/// The wire a dragged node would be inserted onto if dropped now, keyed by the node and index of the input it feeds (the max node ID for an export).
|
||||
UpdateWireInsertionPreview {
|
||||
wire: Option<(NodeId, usize)>,
|
||||
},
|
||||
/// How far each node, and the imports and exports, gliding into the place it moved to is drawn from that place, in node graph space.
|
||||
UpdateGlideOffsets {
|
||||
nodes: Vec<(NodeId, (f64, f64))>,
|
||||
imports: (f64, f64),
|
||||
exports: (f64, f64),
|
||||
},
|
||||
/// The connector a press at the pointer would grab, by its center in node graph space.
|
||||
UpdateHoveredConnector {
|
||||
center: Option<(f64, f64)>,
|
||||
},
|
||||
UpdateLayerWidths {
|
||||
#[serde(rename = "layerWidths")]
|
||||
layer_widths: HashMap<NodeId, u32>,
|
||||
#[serde(rename = "chainWidths")]
|
||||
chain_widths: HashMap<NodeId, u32>,
|
||||
#[serde(rename = "hasLeftInputWire")]
|
||||
has_left_input_wire: HashMap<NodeId, bool>,
|
||||
},
|
||||
UpdateDocumentArtwork {
|
||||
svg: String,
|
||||
},
|
||||
@@ -300,25 +246,9 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "setColorChoice")]
|
||||
set_color_choice: Option<PrimarySecondary>,
|
||||
},
|
||||
UpdateGraphFadeArtwork {
|
||||
percentage: f64,
|
||||
},
|
||||
UpdateMouseCursor {
|
||||
cursor: MouseCursorIcon,
|
||||
},
|
||||
UpdateNodeGraphNodes {
|
||||
nodes: Vec<FrontendNode>,
|
||||
},
|
||||
UpdateNodeGraphErrorDiagnostics {
|
||||
errors: Vec<NodeGraphErrorDiagnostic>,
|
||||
},
|
||||
UpdateVisibleNodes {
|
||||
nodes: Vec<NodeId>,
|
||||
},
|
||||
UpdateNodeGraphWires {
|
||||
wires: Vec<WirePathUpdate>,
|
||||
},
|
||||
ClearAllNodeGraphWires,
|
||||
UpdateNodeGraphSelection {
|
||||
selected: Vec<NodeId>,
|
||||
},
|
||||
@@ -335,27 +265,15 @@ pub enum FrontendMessage {
|
||||
height: u32,
|
||||
pixels: serde_bytes::ByteBuf,
|
||||
},
|
||||
UpdateNodeThumbnailCanvases {
|
||||
UpdateNodeThumbnailCanvas {
|
||||
id: NodeId,
|
||||
#[serde(rename = "layersPanelCanvasId")]
|
||||
layers_panel_canvas_id: u64,
|
||||
#[serde(rename = "nodeGraphCanvasId")]
|
||||
node_graph_canvas_id: u64,
|
||||
#[serde(rename = "canvasId")]
|
||||
canvas_id: u64,
|
||||
},
|
||||
UpdateOpenDocumentsList {
|
||||
#[serde(rename = "openDocuments")]
|
||||
open_documents: Vec<DocumentInfo>,
|
||||
},
|
||||
UpdateWirePathInProgress {
|
||||
#[serde(rename = "wirePath")]
|
||||
wire_path: Option<WirePath>,
|
||||
/// Where the wire meets the connector it's dragged from, in node graph space.
|
||||
#[serde(rename = "draggedFrom")]
|
||||
dragged_from: Option<(f64, f64)>,
|
||||
/// Where the wire's loose end meets a connector it has snapped onto, in node graph space.
|
||||
#[serde(rename = "snappedTo")]
|
||||
snapped_to: Option<(f64, f64)>,
|
||||
},
|
||||
UpdatePlatform {
|
||||
platform: AppWindowPlatform,
|
||||
},
|
||||
|
||||
@@ -183,7 +183,7 @@ async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<Fr
|
||||
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)
|
||||
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO, None)
|
||||
.expect("the evaluation is submitted");
|
||||
|
||||
let mut messages = editor.dispatch(submitted);
|
||||
|
||||
@@ -31,8 +31,7 @@ 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::{
|
||||
@@ -409,6 +408,7 @@ macro_rules! inspectable_types {
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<BlendMode>,
|
||||
List<GradientForm>,
|
||||
List<GradientSpread>,
|
||||
List<GradientSpace>,
|
||||
List<GradientHueDirection>,
|
||||
@@ -469,7 +469,6 @@ macro_rules! inspectable_types {
|
||||
Item<DAffine2>,
|
||||
Item<BlendMode>,
|
||||
Item<GradientForm>,
|
||||
Item<GradientModel>,
|
||||
Item<GradientSpread>,
|
||||
Item<GradientSpace>,
|
||||
Item<GradientHueDirection>,
|
||||
@@ -1285,7 +1284,6 @@ impl_table_item_layout_for_choice_enum!(
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -1481,7 +1479,6 @@ macro_rules! known_item_types {
|
||||
TransferCurve,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
|
||||
@@ -211,11 +211,6 @@ pub enum DocumentMessage {
|
||||
SetGraphFadeArtwork {
|
||||
percentage: f64,
|
||||
},
|
||||
/// Renames a layer in the network the node graph is showing, which may be a subgraph.
|
||||
SetLayerNameInGraph {
|
||||
node_id: NodeId,
|
||||
name: String,
|
||||
},
|
||||
SetLayersPanelHoveredLayer {
|
||||
id: Option<NodeId>,
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::DocumentHistory;
|
||||
use super::node_graph::graph_ui::GraphUiPart;
|
||||
use super::node_graph::{document_node_definitions, node_inspector};
|
||||
use super::utility_types::error::EditorError;
|
||||
use super::utility_types::layers_in_view::LayersInView;
|
||||
@@ -199,7 +200,7 @@ pub struct DocumentMessageHandler {
|
||||
/// The layer under the pointer in the Layers panel, which gets a hover outline in the viewport.
|
||||
#[serde(skip)]
|
||||
layers_panel_hovered_layer: Option<LayerNodeIdentifier>,
|
||||
/// The layers the frontend shows in view, the only ones it's sent the details and thumbnails of.
|
||||
/// The layers in view in the Layers panel or the node graph, the only ones thumbnails are rendered for.
|
||||
#[serde(skip)]
|
||||
pub layers_in_view: LayersInView,
|
||||
/// Whether or not the editor has executed the network to render the document yet. If this is opened as an inactive tab, it won't be loaded initially because the active tab is prioritized.
|
||||
@@ -680,7 +681,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.breadcrumb_network_path.push(node_id);
|
||||
self.selection_network_path.clone_from(&self.breadcrumb_network_path);
|
||||
self.network_interface.unload_import_export_ports(&self.breadcrumb_network_path);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(DocumentMessage::ZoomCanvasToFitAll);
|
||||
responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
|
||||
@@ -699,20 +699,20 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.network_interface.cancel_drag(&self.selection_network_path);
|
||||
self.node_graph_handler.select_if_not_dragged = None;
|
||||
self.node_graph_handler.nodes_added_in_drag = false;
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
self.node_graph_handler.graph_ui.stop_animations(responses);
|
||||
responses.add(NodeGraphMessage::UpdateWireInsertionPreview);
|
||||
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
|
||||
}
|
||||
// Abort dragging a dot out of a connector, before the dot has appeared
|
||||
else if self.node_graph_handler.dot_drag_out.is_some() {
|
||||
self.node_graph_handler.dot_drag_out = None;
|
||||
}
|
||||
// Abort box selection
|
||||
else if self.node_graph_handler.box_selection_start.is_some() {
|
||||
self.node_graph_handler.box_selection_start = None;
|
||||
else if self.node_graph_handler.box_selection.is_some() {
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet {
|
||||
nodes: self.node_graph_handler.selection_before_pointer_down.clone(),
|
||||
});
|
||||
responses.add(FrontendMessage::UpdateBox { box_selection: None });
|
||||
self.node_graph_handler.set_box_selection(None, responses);
|
||||
}
|
||||
// Abort wire in progress of being connected
|
||||
else if self.node_graph_handler.wire_in_progress_from_connector.is_some() {
|
||||
@@ -744,7 +744,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.selection_network_path.clone_from(&self.breadcrumb_network_path);
|
||||
}
|
||||
self.network_interface.unload_import_export_ports(&self.breadcrumb_network_path);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
responses.add(DocumentMessage::PTZUpdate);
|
||||
responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
|
||||
@@ -800,24 +799,21 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::GraphViewOverlay { open } => {
|
||||
let opened = !self.graph_view_overlay_open && open;
|
||||
self.graph_view_overlay_open = open;
|
||||
self.node_graph_handler.graph_ui.graph_view_toggled(responses);
|
||||
|
||||
responses.add(FrontendMessage::UpdateGraphViewOverlay { open });
|
||||
responses.add(FrontendMessage::UpdateGraphFadeArtwork {
|
||||
percentage: self.graph_fade_artwork_percentage,
|
||||
});
|
||||
|
||||
// Update the tilt menu bar buttons to be disabled when the graph is open
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(PortfolioMessage::SubmitActiveGraphRender);
|
||||
if opened {
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
|
||||
}
|
||||
if open {
|
||||
responses.add(ToolMessage::DeactivateTools);
|
||||
responses.add(OverlaysMessage::Draw); // Clear the overlays
|
||||
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
|
||||
responses.add(NodeGraphMessage::UpdateGraphBarRight);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
@@ -827,6 +823,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
if self.end_node_graph_wire_in_progress(responses) {
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
}
|
||||
self.node_graph_handler.abort_node_drag(&mut self.network_interface, &self.selection_network_path, responses);
|
||||
|
||||
responses.add(ToolMessage::ActivateTool { tool_type: *current_tool });
|
||||
responses.add(OverlaysMessage::Draw); // Redraw overlays when graph is closed
|
||||
@@ -1545,6 +1542,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.chain_node_range_selection_reference = Some(node_id);
|
||||
}
|
||||
DocumentMessage::SetActivePanel { active_panel } => {
|
||||
let selection_network_path = self.selection_network_path.clone();
|
||||
match active_panel {
|
||||
PanelType::Document => {
|
||||
if self.graph_view_overlay_open {
|
||||
@@ -1558,7 +1556,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
responses.add(InspectorMessage::Refresh);
|
||||
responses.add(NodeGraphMessage::UpdateLayerPanel);
|
||||
responses.add(NodeGraphMessage::UpdateInSelectedNetwork);
|
||||
if self.graph_view_overlay_open && self.selection_network_path != selection_network_path {
|
||||
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
|
||||
}
|
||||
}
|
||||
DocumentMessage::SetBlendModeForSelectedLayers { blend_mode } => {
|
||||
for layer in self.network_interface.selected_nodes().selected_layers_except_artboards(&self.network_interface) {
|
||||
@@ -1567,15 +1567,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
DocumentMessage::SetGraphFadeArtwork { percentage } => {
|
||||
self.graph_fade_artwork_percentage = percentage;
|
||||
responses.add(FrontendMessage::UpdateGraphFadeArtwork { percentage });
|
||||
}
|
||||
DocumentMessage::SetLayerNameInGraph { node_id, name } => {
|
||||
responses.add(NodeGraphMessage::SetDisplayName {
|
||||
node_id,
|
||||
network_path: self.breadcrumb_network_path.clone(),
|
||||
alias: name,
|
||||
skip_adding_history_step: false,
|
||||
});
|
||||
responses.add(PortfolioMessage::SubmitActiveGraphRender);
|
||||
}
|
||||
DocumentMessage::SetLayersPanelHoveredLayer { id } => {
|
||||
let layer = id.filter(|id| self.network_interface.is_layer(id, &[])).map(LayerNodeIdentifier::new_unchecked);
|
||||
@@ -2087,6 +2079,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(NodeGraphMessage::UpdateBoxSelection);
|
||||
responses.add(NodeGraphMessage::UpdateHoveredConnector);
|
||||
responses.add(NodeGraphMessage::UpdateImportsExports);
|
||||
responses.add(PortfolioMessage::SubmitActiveGraphRender);
|
||||
|
||||
responses.add(FrontendMessage::UpdateNodeGraphTransform {
|
||||
translation: transform.translation.into(),
|
||||
@@ -2711,8 +2704,6 @@ impl DocumentMessageHandler {
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
}
|
||||
|
||||
/// Keeps the graph showing the open network across a reconcile, which can rebuild its view state or remove it.
|
||||
@@ -2768,8 +2759,6 @@ impl DocumentMessageHandler {
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
}
|
||||
|
||||
pub fn serialize_document(&self) -> String {
|
||||
@@ -3067,9 +3056,6 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
// Settled before storage moves, so the glide's offsets don't outlive the step
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
// Alone, the step enters history first so it stays on the History panel once undone
|
||||
if !self.is_in_session() {
|
||||
@@ -3082,8 +3068,6 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if self.history.redo() {
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
@@ -3093,8 +3077,6 @@ impl DocumentMessageHandler {
|
||||
|
||||
/// Takes back the open transaction along with the `undo_count - 1` steps before it, leaving nothing to redo.
|
||||
fn abort_steps(&mut self, document_id: DocumentId, undo_count: usize, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
|
||||
let open_transaction_has_edits = self.network_interface.transaction_status() == TransactionStatus::Modified;
|
||||
if open_transaction_has_edits {
|
||||
// Staged so they are taken back with the steps before them
|
||||
@@ -3123,7 +3105,6 @@ impl DocumentMessageHandler {
|
||||
return;
|
||||
}
|
||||
self.end_history_preview(viewport, responses);
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
self.apply_history_line_change(document_id, rev, change, byte_store, responses);
|
||||
}
|
||||
@@ -3138,7 +3119,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
let Some(past) = self.history.interface_at(rev) else { return };
|
||||
|
||||
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
|
||||
self.node_graph_handler.graph_ui.stop_animations(responses);
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
let replaced = self.install_history_snapshot(past, viewport);
|
||||
let current = self.history_preview.take().map_or(replaced, |preview| preview.current);
|
||||
@@ -3191,8 +3172,6 @@ impl DocumentMessageHandler {
|
||||
fn show_installed_interface(&self, responses: &mut VecDeque<Message>) {
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
responses.add(DocumentMessage::DocumentStructureChanged);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
@@ -3228,6 +3207,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
/// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`.
|
||||
fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph_handler.graph_ui.stop_animations(responses);
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
let changes = gdd.take_remote_changes();
|
||||
self.pending_remote.extend(changes);
|
||||
@@ -5128,7 +5108,7 @@ mod document_message_handler_tests {
|
||||
let document = portfolio.documents.get_mut(&document_id).unwrap();
|
||||
portfolio
|
||||
.executor
|
||||
.submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO)
|
||||
.submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO, None)
|
||||
.unwrap();
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
|
||||
@@ -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>,
|
||||
|
||||
+2
-2
@@ -1034,7 +1034,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());
|
||||
@@ -1062,7 +1062,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,7 +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_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;
|
||||
@@ -450,8 +450,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;
|
||||
@@ -491,22 +490,11 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// Only a chosen form sets the curvatures, leaving any the graph feeds or that already make it
|
||||
let curvatures = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
|
||||
if let Some(gradient_form) = gradient_form
|
||||
&& curvatures.is_some_and(|curvatures| GradientForm::from_curvatures(curvatures) != Some(gradient_form))
|
||||
{
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let [start_curvature, end_curvature] = gradient_form.curvatures();
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, StartCurvatureInput),
|
||||
NodeInput::value(TaggedValue::Number(start_curvature), false),
|
||||
true,
|
||||
);
|
||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end_curvature), false), true);
|
||||
}
|
||||
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();
|
||||
@@ -773,28 +761,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) {
|
||||
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 identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return };
|
||||
let Some(curvatures) = gradient_curvature_values(node) else { return };
|
||||
if GradientForm::from_curvatures(curvatures) == Some(gradient_form) {
|
||||
return;
|
||||
}
|
||||
|
||||
let [start, end] = gradient_form.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.
|
||||
|
||||
@@ -3,7 +3,6 @@ mod document_node_derive;
|
||||
use super::node_inspector::choice::enum_choice;
|
||||
use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
|
||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
||||
@@ -686,7 +685,6 @@ 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));
|
||||
@@ -1642,13 +1640,6 @@ pub fn network_node_identifiers() -> impl Iterator<Item = &'static str> {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn collect_node_icons() -> Vec<(String, IconName)> {
|
||||
DOCUMENT_NODE_TYPES
|
||||
.iter()
|
||||
.filter_map(|(identifier, definition)| Some((identifier.serialized(), definition.icon?.to_string())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl DocumentNodeDefinition {
|
||||
/// Converts the [DocumentNodeDefinition] type to a [NodeTemplate], using the provided `input_override` and falling back to the default inputs.
|
||||
/// `input_override` does not have to be the correct length.
|
||||
@@ -1684,18 +1675,19 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||
use glam::DAffine2;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::platform_application_io::rasterize;
|
||||
|
||||
let definition = super::resolve_proto_node_definition(&rasterize::IDENTIFIER).expect("Rasterize should have a definition");
|
||||
let transform = definition.node_template.input(rasterize::TransformInput).and_then(|input| input.as_value());
|
||||
let resolution = definition.node_template.input(rasterize::ResolutionInput).and_then(|input| input.as_value());
|
||||
let footprint = definition.node_template.input(rasterize::FootprintInput).and_then(|input| input.as_value());
|
||||
|
||||
// The square from (0, 0) to (1000, 1000)
|
||||
let expected_transform = DAffine2::from_scale_angle_translation(DVec2::splat(1000.), 0., DVec2::splat(500.));
|
||||
assert_eq!(transform, Some(&TaggedValue::DAffine2(expected_transform)));
|
||||
assert_eq!(resolution, Some(&TaggedValue::DVec2(DVec2::splat(1000.))));
|
||||
let expected = Footprint {
|
||||
transform: DAffine2::from_scale(DVec2::splat(1000.)),
|
||||
resolution: UVec2::splat(1000),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(footprint, Some(&TaggedValue::Footprint(expected)));
|
||||
}
|
||||
|
||||
// The executor input the compiler fills in has no type yet, which mustn't rule out every implementation
|
||||
|
||||
@@ -0,0 +1,514 @@
|
||||
mod animation;
|
||||
mod name_field;
|
||||
mod pointer;
|
||||
|
||||
pub use name_field::{GraphName, GraphNameField, edited_name};
|
||||
pub use pointer::{PointerHits, connector_under_pointer, tooltip_target};
|
||||
|
||||
use super::node_graph_message_handler::NodeGraphMessageHandler;
|
||||
use super::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::portfolio::document::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NetworkConnectorKey, NodeNetworkInterface, OutputConnector, Previewing};
|
||||
use crate::messages::prelude::{Message, PortfolioMessage, Responses};
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_ui::GraphUiConfig;
|
||||
use graph_ui::animation::{Glided, Glides};
|
||||
use graph_ui::card::{Card, Connector, DataType, Selection};
|
||||
use graph_ui::dot::Dot;
|
||||
use graph_ui::error_badge::ErrorBadge;
|
||||
use graph_ui::geometry::NodeGeometry;
|
||||
use graph_ui::highlights::{self, Highlights, NodePart};
|
||||
use graph_ui::layer::Layer;
|
||||
use graph_ui::network_connector::{NetworkConnector, NetworkConnectorKind, network_connector_row_offset};
|
||||
use graph_ui::placed::Placed;
|
||||
use graph_ui::replicated_map::{Keyed, ReplicatedMap, ReplicatedMapEdit};
|
||||
use graph_ui::scene::GraphUiSceneEdit;
|
||||
use graph_ui::wire::{InputKey, OutputKey, Wire, WireInProgress, WireKey, WireStyle};
|
||||
use pointer::TooltipTarget;
|
||||
use std::collections::{BTreeSet, HashMap, VecDeque};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ConnectorKey {
|
||||
Input(InputConnector),
|
||||
Output(OutputConnector),
|
||||
}
|
||||
|
||||
impl From<NetworkConnectorKey> for ConnectorKey {
|
||||
fn from(connector: NetworkConnectorKey) -> Self {
|
||||
match connector {
|
||||
NetworkConnectorKey::Import(index) => ConnectorKey::Output(OutputConnector::Import(index)),
|
||||
NetworkConnectorKey::Export(index) => ConnectorKey::Input(InputConnector::Export(index)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ConnectorKey> for highlights::ConnectorKey {
|
||||
fn from(connector: ConnectorKey) -> Self {
|
||||
match connector {
|
||||
ConnectorKey::Input(input) => highlights::ConnectorKey::Input(input_key(input)),
|
||||
ConnectorKey::Output(output) => highlights::ConnectorKey::Output(output_key(output)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum GraphUiPart {
|
||||
All,
|
||||
NetworkConnectors,
|
||||
Errors,
|
||||
InsertionTarget,
|
||||
Moved { nodes: Vec<NodeId> },
|
||||
}
|
||||
|
||||
pub struct GraphUiSceneBuilder<'a> {
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
network_path: &'a [NodeId],
|
||||
node_graph_handler: &'a NodeGraphMessageHandler,
|
||||
selected_nodes: Vec<NodeId>,
|
||||
selected: Selection,
|
||||
}
|
||||
|
||||
impl<'a> GraphUiSceneBuilder<'a> {
|
||||
pub fn of(document: &'a DocumentMessageHandler) -> Self {
|
||||
let network_interface = &document.network_interface;
|
||||
let network_path = document.breadcrumb_network_path();
|
||||
Self {
|
||||
network_interface,
|
||||
network_path,
|
||||
node_graph_handler: &document.node_graph_handler,
|
||||
selected_nodes: network_interface.selected_nodes_in_nested_network(network_path).unwrap_or_default().0,
|
||||
selected: if network_path == document.selection_network_path() {
|
||||
Selection::Active
|
||||
} else {
|
||||
Selection::Inactive
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&self, part: GraphUiPart, scene: &mut GraphUiSceneEdit) {
|
||||
match part {
|
||||
GraphUiPart::All => {
|
||||
let dragging = self.network_interface.dragging(self.network_path);
|
||||
let glides = &self.node_graph_handler.graph_ui.glides;
|
||||
replace_rows(self.cards(), dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards);
|
||||
replace_rows(self.layers(), dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers);
|
||||
replace_rows(self.dots(), dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots);
|
||||
place_wires(self.wires(), scene);
|
||||
scene.network_connectors.replace_all(self.network_connectors());
|
||||
scene.errors.replace_all(self.errors());
|
||||
}
|
||||
GraphUiPart::NetworkConnectors => scene.network_connectors.replace_all(self.network_connectors()),
|
||||
GraphUiPart::Errors => scene.errors.replace_all(self.errors()),
|
||||
GraphUiPart::InsertionTarget => self.update_insertion_target(scene),
|
||||
GraphUiPart::Moved { nodes } => self.update_moved(scene, nodes),
|
||||
}
|
||||
}
|
||||
|
||||
fn nodes(&self) -> impl Iterator<Item = NodeId> + '_ {
|
||||
self.network_interface.nested_network(self.network_path).into_iter().flat_map(|network| network.nodes.keys().copied())
|
||||
}
|
||||
|
||||
fn selection(&self, key: NodeId) -> Selection {
|
||||
if self.selected_nodes.contains(&key) { self.selected } else { Selection::None }
|
||||
}
|
||||
|
||||
fn cards(&self) -> Vec<Placed<Card>> {
|
||||
self.nodes().filter_map(|key| self.card(key)).collect()
|
||||
}
|
||||
|
||||
fn card(&self, key: NodeId) -> Option<Placed<Card>> {
|
||||
let (network_interface, network_path) = (self.network_interface, self.network_path);
|
||||
if network_interface.is_layer(&key, network_path) || network_interface.is_redirect_dot(&key, network_path) {
|
||||
return None;
|
||||
}
|
||||
let NodeGeometry { cell, shape, .. } = self.geometry(key)?;
|
||||
let name = network_interface.display_name(&key, network_path);
|
||||
let look = Card {
|
||||
key,
|
||||
shape,
|
||||
name,
|
||||
icon: network_interface.node_icon(&key, network_path),
|
||||
primary_input: self.input(key, 0),
|
||||
primary_output: self.output(key, 0),
|
||||
secondary_inputs: (1..network_interface.number_of_inputs(&key, network_path)).filter_map(|index| self.input(key, index)).collect(),
|
||||
secondary_outputs: (1..network_interface.number_of_outputs(&key, network_path)).filter_map(|index| self.output(key, index)).collect(),
|
||||
selection: self.selection(key),
|
||||
visible: network_interface.is_visible(&key, network_path),
|
||||
previewed: network_interface.previewing(network_path).previews(key),
|
||||
};
|
||||
Some(Placed { cell, look })
|
||||
}
|
||||
|
||||
fn geometry(&self, key: NodeId) -> Option<NodeGeometry> {
|
||||
self.network_interface.with_layout(self.network_path, |layout| layout.geometry(&key)).flatten()
|
||||
}
|
||||
|
||||
fn layers(&self) -> Vec<Placed<Layer>> {
|
||||
self.nodes().filter_map(|key| self.layer(key)).collect()
|
||||
}
|
||||
|
||||
fn layer(&self, key: NodeId) -> Option<Placed<Layer>> {
|
||||
let (network_interface, network_path) = (self.network_interface, self.network_path);
|
||||
if !network_interface.is_layer(&key, network_path) {
|
||||
return None;
|
||||
}
|
||||
let NodeGeometry { cell, chain_length, shape, .. } = self.geometry(key)?;
|
||||
let look = Layer {
|
||||
key,
|
||||
shape,
|
||||
chain_length,
|
||||
name: network_interface.display_name(&key, network_path),
|
||||
renaming: self.node_graph_handler.graph_ui.editing_name == Some(GraphName::Layer(key)),
|
||||
has_left_input_wire: network_interface.has_left_input_wire(&key, network_path),
|
||||
primary_input: self.input(key, 0),
|
||||
primary_output: self.output(key, 0),
|
||||
secondary_input: (1..network_interface.number_of_inputs(&key, network_path)).find_map(|index| self.input(key, index)),
|
||||
primary_input_connected_to_layer: network_interface.primary_input_connected_to_layer(&key, network_path),
|
||||
primary_output_connected_to_layer: network_interface.primary_output_connected_to_layer(&key, network_path),
|
||||
visible: network_interface.is_visible(&key, network_path),
|
||||
read_only: network_interface.is_read_only(network_path),
|
||||
selection: self.selection(key),
|
||||
previewed: network_interface.previewing(network_path).previews(key),
|
||||
};
|
||||
Some(Placed { cell, look })
|
||||
}
|
||||
|
||||
fn dots(&self) -> Vec<Placed<Dot>> {
|
||||
self.nodes().filter_map(|key| self.dot(key)).collect()
|
||||
}
|
||||
|
||||
fn dot(&self, key: NodeId) -> Option<Placed<Dot>> {
|
||||
let (network_interface, network_path) = (self.network_interface, self.network_path);
|
||||
if !network_interface.is_redirect_dot(&key, network_path) {
|
||||
return None;
|
||||
}
|
||||
let input = self.input(key, 0);
|
||||
let output = self.output(key, 0);
|
||||
let NodeGeometry { cell, shape, .. } = self.geometry(key)?;
|
||||
let look = Dot {
|
||||
key,
|
||||
shape,
|
||||
data_type: output.as_ref().map_or(DataType::General, |output| output.data_type),
|
||||
wired: input.is_some_and(|input| input.connected) || output.is_some_and(|output| output.connected),
|
||||
selected: self.selected_nodes.contains(&key),
|
||||
previewed: network_interface.previewing(network_path).previews(key),
|
||||
};
|
||||
Some(Placed { cell, look })
|
||||
}
|
||||
|
||||
fn wires(&self) -> Vec<Wire> {
|
||||
let inputs = self.network_interface.node_graph_input_connectors(self.network_path).into_iter();
|
||||
inputs.filter_map(|input| self.wire(input)).chain(self.preview_wire()).collect()
|
||||
}
|
||||
|
||||
fn wire(&self, input: InputConnector) -> Option<Wire> {
|
||||
let output = self.network_interface.upstream_output_connector(&input, self.network_path)?;
|
||||
let to = input_key(input);
|
||||
Some(self.wire_row(WireKey::Input(to), output, to))
|
||||
}
|
||||
|
||||
fn preview_wire(&self) -> Option<Wire> {
|
||||
let (network_interface, network_path) = (self.network_interface, self.network_path);
|
||||
let input = InputConnector::Export(0);
|
||||
|
||||
let Previewing::Yes { previewed } = network_interface.previewing(network_path) else { return None };
|
||||
|
||||
if network_interface.upstream_output_connector(&input, network_path) == Some(previewed.to_connector()) {
|
||||
return None;
|
||||
}
|
||||
Some(self.wire_row(WireKey::Preview, previewed.to_connector(), input_key(input)))
|
||||
}
|
||||
|
||||
fn wire_row(&self, key: WireKey, output: OutputConnector, to: InputKey) -> Wire {
|
||||
let output_type = self.network_interface.output_type(&output, self.network_path);
|
||||
Wire {
|
||||
key,
|
||||
from: output_key(output),
|
||||
to,
|
||||
data_type: data_type(output_type.displayed_type()),
|
||||
list: output_type.is_list(),
|
||||
insertion_target: Some(key) == self.insertion_target(),
|
||||
}
|
||||
}
|
||||
|
||||
fn insertion_target(&self) -> Option<WireKey> {
|
||||
self.node_graph_handler.wire_insertion_preview.map(|input| WireKey::Input(input_key(input)))
|
||||
}
|
||||
|
||||
fn network_connectors(&self) -> Vec<NetworkConnector> {
|
||||
[NetworkConnectorKind::Import, NetworkConnectorKind::Export]
|
||||
.into_iter()
|
||||
.flat_map(|kind| self.network_connectors_of(kind))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn network_connectors_of(&self, kind: NetworkConnectorKind) -> Vec<NetworkConnector> {
|
||||
let (network_interface, network_path) = (self.network_interface, self.network_path);
|
||||
let count = match kind {
|
||||
NetworkConnectorKind::Import => network_interface.number_of_imports(network_path),
|
||||
NetworkConnectorKind::Export => network_interface.number_of_exports(network_path),
|
||||
};
|
||||
let row = |key: NetworkConnectorKey, position: DVec2, connector: Option<Connector>| NetworkConnector {
|
||||
key,
|
||||
position: position.as_ivec2(),
|
||||
connector,
|
||||
editable: !network_path.is_empty(),
|
||||
renaming: self.node_graph_handler.graph_ui.editing_name == Some(GraphName::NetworkConnector(key)),
|
||||
};
|
||||
let named = (0..count).filter_map(|index| {
|
||||
let key = NetworkConnectorKey::new(kind, index);
|
||||
Some(row(key, self.position(key.into())?, Some(self.connector(key.into())?)))
|
||||
});
|
||||
let empty = network_interface.empty_import_export_connectors(kind == NetworkConnectorKind::Import, network_path);
|
||||
named
|
||||
.chain(empty.into_iter().map(|(index, position)| row(NetworkConnectorKey::new(kind, index), position, None)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn errors(&self) -> Vec<ErrorBadge> {
|
||||
let errors = self.node_graph_handler.node_graph_errors(self.network_interface, self.network_path);
|
||||
errors.into_iter().map(|(key, text)| ErrorBadge { key, text }).collect()
|
||||
}
|
||||
|
||||
fn update_moved(&self, scene: &mut GraphUiSceneEdit, nodes: Vec<NodeId>) {
|
||||
let (network_interface, network_path) = (self.network_interface, self.network_path);
|
||||
let downstream_layers = nodes.iter().filter_map(|node| network_interface.downstream_layer_for_chain_node(node, network_path));
|
||||
let rows: BTreeSet<NodeId> = nodes.iter().copied().chain(downstream_layers).collect();
|
||||
self.place_node_rows(rows, scene);
|
||||
scene.network_connectors.replace_all(self.network_connectors());
|
||||
place_wires(all_wires(scene), scene);
|
||||
}
|
||||
|
||||
fn place_node_rows(&self, nodes: impl IntoIterator<Item = NodeId>, scene: &mut GraphUiSceneEdit) {
|
||||
let (network_interface, network_path) = (self.network_interface, self.network_path);
|
||||
let dragging = network_interface.dragging(network_path);
|
||||
let glides = &self.node_graph_handler.graph_ui.glides;
|
||||
for node in nodes {
|
||||
let Some(NodeGeometry { cell, chain_length, .. }) = self.geometry(node) else { continue };
|
||||
|
||||
let placed = replace_row(node, dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards, |card| {
|
||||
(card.cell != cell).then(|| Placed { cell, look: card.look.clone() })
|
||||
}) || replace_row(node, dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers, |layer| {
|
||||
let has_left_input_wire = network_interface.has_left_input_wire(&node, network_path);
|
||||
let changed = (layer.cell, layer.look.chain_length, layer.look.has_left_input_wire) != (cell, chain_length, has_left_input_wire);
|
||||
let look = || Layer {
|
||||
chain_length,
|
||||
has_left_input_wire,
|
||||
..layer.look.clone()
|
||||
};
|
||||
changed.then(|| Placed { cell, look: look() })
|
||||
}) || replace_row(node, dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots, |dot| {
|
||||
(dot.cell != cell).then(|| Placed { cell, look: dot.look.clone() })
|
||||
});
|
||||
if !placed {
|
||||
self.put_node_rows(node, dragging, scene);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn put_node_rows(&self, node: NodeId, dragging: bool, scene: &mut GraphUiSceneEdit) {
|
||||
let glides = &self.node_graph_handler.graph_ui.glides;
|
||||
if let Some(card) = self.card(node) {
|
||||
place_row(card, dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards);
|
||||
}
|
||||
if let Some(layer) = self.layer(node) {
|
||||
place_row(layer, dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers);
|
||||
}
|
||||
if let Some(dot) = self.dot(node) {
|
||||
place_row(dot, dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots);
|
||||
}
|
||||
}
|
||||
|
||||
fn input(&self, node: NodeId, index: usize) -> Option<Connector> {
|
||||
self.connector(ConnectorKey::Input(InputConnector::node_at_index(node, index)))
|
||||
}
|
||||
|
||||
fn output(&self, node: NodeId, index: usize) -> Option<Connector> {
|
||||
self.connector(ConnectorKey::Output(OutputConnector::node(node, index)))
|
||||
}
|
||||
|
||||
fn connector(&self, key: ConnectorKey) -> Option<Connector> {
|
||||
let (network_interface, network_path) = (self.network_interface, self.network_path);
|
||||
let (name, connector_type, connected) = match key {
|
||||
ConnectorKey::Input(input) => network_interface.graph_ui_input(&input, network_path),
|
||||
ConnectorKey::Output(output) => network_interface.graph_ui_output(&output, network_path),
|
||||
}?;
|
||||
Some(Connector {
|
||||
index: match key {
|
||||
ConnectorKey::Input(input) => input.input_index(),
|
||||
ConnectorKey::Output(output) => output.index(),
|
||||
} as u32,
|
||||
name,
|
||||
data_type: data_type(connector_type.displayed_type()),
|
||||
connected,
|
||||
})
|
||||
}
|
||||
|
||||
fn position(&self, key: ConnectorKey) -> Option<DVec2> {
|
||||
match key {
|
||||
ConnectorKey::Input(input) => self.network_interface.input_position(&input, self.network_path),
|
||||
ConnectorKey::Output(output) => self.network_interface.output_position(&output, self.network_path),
|
||||
}
|
||||
}
|
||||
|
||||
fn update_insertion_target(&self, scene: &mut GraphUiSceneEdit) {
|
||||
let target = self.insertion_target();
|
||||
let wires = all_wires(scene).into_iter().map(|wire| Wire {
|
||||
insertion_target: Some(wire.key) == target,
|
||||
..wire
|
||||
});
|
||||
place_wires(wires.collect(), scene);
|
||||
}
|
||||
}
|
||||
|
||||
fn stays<T: Keyed<Key = NodeId> + PartialEq>(row: &T, dragging: bool, glides: &Glides, settled: &ReplicatedMap<T>) -> bool {
|
||||
!glides.rows.contains_key(&Glided::Node(row.key())) && (!dragging || settled.get(&row.key()) == Some(row))
|
||||
}
|
||||
|
||||
fn replace_rows<T: Keyed<Key = NodeId> + PartialEq>(rows: Vec<T>, dragging: bool, glides: &Glides, settled: &mut ReplicatedMapEdit<T>, moving: &mut ReplicatedMapEdit<T>) {
|
||||
let (still, moved): (Vec<T>, Vec<T>) = rows.into_iter().partition(|row| stays(row, dragging, glides, settled));
|
||||
settled.replace_all(still);
|
||||
moving.replace_all(moved);
|
||||
}
|
||||
|
||||
fn place_row<T: Keyed<Key = NodeId> + PartialEq>(row: T, dragging: bool, glides: &Glides, settled: &mut ReplicatedMapEdit<T>, moving: &mut ReplicatedMapEdit<T>) {
|
||||
let key = row.key();
|
||||
if stays(&row, dragging, glides, settled) {
|
||||
moving.remove(&key);
|
||||
settled.put(row);
|
||||
} else {
|
||||
settled.remove(&key);
|
||||
moving.put(row);
|
||||
}
|
||||
}
|
||||
|
||||
fn replace_row<T: Keyed<Key = NodeId> + PartialEq>(
|
||||
node: NodeId,
|
||||
dragging: bool,
|
||||
glides: &Glides,
|
||||
settled: &mut ReplicatedMapEdit<T>,
|
||||
moving: &mut ReplicatedMapEdit<T>,
|
||||
replaced: impl FnOnce(&T) -> Option<T>,
|
||||
) -> bool {
|
||||
let Some(row) = moving.get(&node).or_else(|| settled.get(&node)) else { return false };
|
||||
if let Some(row) = replaced(row) {
|
||||
place_row(row, dragging, glides, settled, moving);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn all_wires(scene: &GraphUiSceneEdit) -> Vec<Wire> {
|
||||
scene.settled.wires.iter().chain(scene.moving.wires.iter()).cloned().collect()
|
||||
}
|
||||
|
||||
fn place_wires(wires: Vec<Wire>, scene: &mut GraphUiSceneEdit) {
|
||||
let settled = |node: NodeId| scene.settled.cards.get(&node).is_some() || scene.settled.layers.get(&node).is_some() || scene.settled.dots.get(&node).is_some();
|
||||
let between_settled_nodes = |wire: &Wire| match (wire.from, wire.to) {
|
||||
(OutputKey::Node { node: from, .. }, InputKey::Node { node: to, .. }) => settled(from) && settled(to),
|
||||
_ => false,
|
||||
};
|
||||
let (tiled, loose): (Vec<Wire>, Vec<Wire>) = wires.into_iter().partition(|wire| !wire.insertion_target && between_settled_nodes(wire));
|
||||
scene.settled.wires.replace_all(tiled);
|
||||
scene.moving.wires.replace_all(loose);
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct GraphUiState {
|
||||
highlights: Highlights,
|
||||
glides: Glides,
|
||||
animating: bool,
|
||||
pub(super) time: f64,
|
||||
tooltip: Option<(Option<TooltipTarget>, String, String)>,
|
||||
editing_name: Option<GraphName>,
|
||||
name_field: Option<(GraphName, GraphNameField)>,
|
||||
error_text_sizes: HashMap<String, DVec2>,
|
||||
}
|
||||
|
||||
impl GraphUiState {
|
||||
pub fn change_highlights(&mut self, change: impl FnOnce(&mut Highlights), responses: &mut VecDeque<Message>) {
|
||||
let mut highlights = self.highlights.clone();
|
||||
change(&mut highlights);
|
||||
if self.highlights != highlights {
|
||||
self.start_grows(&mut highlights);
|
||||
self.highlights = highlights;
|
||||
self.follow_animations(responses);
|
||||
responses.add(PortfolioMessage::SubmitActiveGraphRender);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config(document: &DocumentMessageHandler, wire_style: WireStyle) -> Option<GraphUiConfig> {
|
||||
let node_graph_handler = &document.node_graph_handler;
|
||||
let graph_metadata = document.network_interface.network_metadata(document.breadcrumb_network_path());
|
||||
graph_metadata.filter(|_| document.graph_view_overlay_open).map(|metadata| {
|
||||
let view = metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
|
||||
GraphUiConfig {
|
||||
view,
|
||||
fade_artwork: document.graph_fade_artwork_percentage / 100.,
|
||||
wire_in_progress: wire_in_progress(node_graph_handler),
|
||||
reorder_bar: reorder_bar(document),
|
||||
box_selection: node_graph_handler
|
||||
.box_selection
|
||||
.filter(|(_, dragged)| *dragged)
|
||||
.map(|(corners, _)| corners.map(|corner| view.transform_point2(corner).max(DVec2::ZERO).floor())),
|
||||
highlights: node_graph_handler.graph_ui.highlights.clone(),
|
||||
wire_style,
|
||||
glides: node_graph_handler.graph_ui.glides.clone(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn reorder_bar(document: &DocumentMessageHandler) -> Option<(NetworkConnectorKind, DVec2)> {
|
||||
let node_graph_handler = &document.node_graph_handler;
|
||||
let index = node_graph_handler.end_index?;
|
||||
let kind = if node_graph_handler.reordering_import.is_some() {
|
||||
NetworkConnectorKind::Import
|
||||
} else if node_graph_handler.reordering_export.is_some() {
|
||||
NetworkConnectorKind::Export
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let (imports, exports) = document.network_interface.import_export_position(document.breadcrumb_network_path())?;
|
||||
let first_row_center = match kind {
|
||||
NetworkConnectorKind::Import => imports,
|
||||
NetworkConnectorKind::Export => exports,
|
||||
};
|
||||
Some((kind, first_row_center.as_dvec2() + DVec2::new(0., network_connector_row_offset(index))))
|
||||
}
|
||||
|
||||
fn wire_in_progress(node_graph_handler: &NodeGraphMessageHandler) -> Option<WireInProgress> {
|
||||
Some(WireInProgress {
|
||||
ends: node_graph_handler.wire_in_progress_ends?,
|
||||
data_type: data_type(node_graph_handler.wire_in_progress_type),
|
||||
})
|
||||
}
|
||||
|
||||
fn output_key(output: OutputConnector) -> OutputKey {
|
||||
match output {
|
||||
OutputConnector::Node { node_id, output_index } => OutputKey::Node { node: node_id, index: output_index },
|
||||
OutputConnector::Import(index) => OutputKey::Import(index),
|
||||
}
|
||||
}
|
||||
|
||||
fn input_key(input: InputConnector) -> InputKey {
|
||||
match input {
|
||||
InputConnector::Node { node_id, input_index } => InputKey::Node { node: node_id, index: input_index },
|
||||
InputConnector::Export(index) => InputKey::Export(index),
|
||||
}
|
||||
}
|
||||
|
||||
fn data_type(data_type: FrontendGraphDataType) -> DataType {
|
||||
match data_type {
|
||||
FrontendGraphDataType::General => DataType::General,
|
||||
FrontendGraphDataType::Number => DataType::Number,
|
||||
FrontendGraphDataType::Artboard => DataType::Artboard,
|
||||
FrontendGraphDataType::Graphic => DataType::Graphic,
|
||||
FrontendGraphDataType::Raster => DataType::Raster,
|
||||
FrontendGraphDataType::Vector => DataType::Vector,
|
||||
FrontendGraphDataType::Color => DataType::Color,
|
||||
FrontendGraphDataType::Gradient => DataType::Gradient,
|
||||
FrontendGraphDataType::Typography => DataType::Typography,
|
||||
FrontendGraphDataType::Invalid => DataType::Invalid,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use super::*;
|
||||
use crate::messages::prelude::{BroadcastMessage, EventMessage, NodeGraphMessage};
|
||||
use graph_ui::animation::{Animation, GROW_DURATION, Glided};
|
||||
use graph_ui::highlights::ConnectorKey;
|
||||
|
||||
impl GraphUiState {
|
||||
pub fn glide(&mut self, moves: impl IntoIterator<Item = (Glided, DVec2)>, responses: &mut VecDeque<Message>) {
|
||||
for (row, moved) in moves {
|
||||
let from = moved + self.glides.offset(row, self.time);
|
||||
match Animation::glide(from, self.time) {
|
||||
Some(glide) => self.glides.rows.insert(row, glide),
|
||||
None => self.glides.rows.remove(&row),
|
||||
};
|
||||
}
|
||||
self.follow_animations(responses);
|
||||
}
|
||||
|
||||
pub fn stop_animations(&mut self, responses: &mut VecDeque<Message>) {
|
||||
if !self.glides.rows.is_empty() {
|
||||
self.glides.rows.clear();
|
||||
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
|
||||
}
|
||||
if !self.highlights.grows.is_empty() {
|
||||
self.highlights.grows.clear();
|
||||
responses.add(PortfolioMessage::SubmitActiveGraphRender);
|
||||
}
|
||||
self.follow_animations(responses);
|
||||
}
|
||||
|
||||
pub fn animation_tick(&mut self, graph_open: bool, responses: &mut VecDeque<Message>) {
|
||||
if !self.animating {
|
||||
responses.add(animation_frames(false));
|
||||
return;
|
||||
}
|
||||
if !graph_open {
|
||||
self.stop_animations(responses);
|
||||
return;
|
||||
}
|
||||
|
||||
let time = self.time;
|
||||
self.highlights.grows.retain(|_, grow| !ended(grow, time));
|
||||
if !self.glides.rows.is_empty() && self.glides.rows.values().all(|glide| ended(glide, time)) {
|
||||
self.glides.rows.clear();
|
||||
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
|
||||
}
|
||||
self.follow_animations(responses);
|
||||
responses.add(PortfolioMessage::SubmitActiveGraphRender);
|
||||
}
|
||||
|
||||
pub(super) fn start_grows(&self, highlights: &mut Highlights) {
|
||||
let keys: BTreeSet<ConnectorKey> = self.highlights.connectors().chain(highlights.connectors()).collect();
|
||||
for key in keys {
|
||||
let grows = highlights.connector(key).is_grown();
|
||||
if self.highlights.connector(key).is_grown() == grows {
|
||||
continue;
|
||||
}
|
||||
let (from, to) = (self.highlights.grown(key, self.time), if grows { 1. } else { 0. });
|
||||
let grow = Animation {
|
||||
from,
|
||||
to,
|
||||
start: self.time,
|
||||
end: self.time + GROW_DURATION * (to - from).abs(),
|
||||
};
|
||||
highlights.grows.insert(key, grow);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn follow_animations(&mut self, responses: &mut VecDeque<Message>) {
|
||||
let animating = !self.glides.rows.is_empty() || !self.highlights.grows.is_empty();
|
||||
if self.animating == animating {
|
||||
return;
|
||||
}
|
||||
self.animating = animating;
|
||||
responses.add(animation_frames(animating));
|
||||
}
|
||||
}
|
||||
|
||||
fn animation_frames(subscribed: bool) -> BroadcastMessage {
|
||||
let (on, send) = (EventMessage::AnimationFrame, Box::new(NodeGraphMessage::AnimationTick.into()));
|
||||
match subscribed {
|
||||
true => BroadcastMessage::SubscribeEvent { on, send },
|
||||
false => BroadcastMessage::UnsubscribeEvent { on, send },
|
||||
}
|
||||
}
|
||||
|
||||
fn ended<T>(animation: &Animation<T>, time: f64) -> bool {
|
||||
time >= animation.end || time < animation.start
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
use super::*;
|
||||
use crate::messages::prelude::FrontendMessage;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum GraphName {
|
||||
Layer(NodeId),
|
||||
NetworkConnector(NetworkConnectorKey),
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GraphNameField {
|
||||
pub name: String,
|
||||
pub x: f64,
|
||||
pub top: f64,
|
||||
#[serde(rename = "alignRight")]
|
||||
pub align_right: bool,
|
||||
pub dimmed: bool,
|
||||
}
|
||||
|
||||
impl GraphUiSceneBuilder<'_> {
|
||||
fn name_field(&self, name: GraphName) -> Option<GraphNameField> {
|
||||
match name {
|
||||
GraphName::Layer(key) => {
|
||||
let layer = self.layer(key)?;
|
||||
let [top_left, _] = layer.name_box();
|
||||
Some(GraphNameField {
|
||||
name: layer.look.name,
|
||||
x: top_left.x,
|
||||
top: top_left.y,
|
||||
align_right: false,
|
||||
dimmed: !layer.look.visible,
|
||||
})
|
||||
}
|
||||
GraphName::NetworkConnector(key) => self.network_connector_name_field(key),
|
||||
}
|
||||
}
|
||||
|
||||
fn network_connector_name_field(&self, key: NetworkConnectorKey) -> Option<GraphNameField> {
|
||||
let row = self.network_connectors().into_iter().find(|row| row.key == key && row.editable)?;
|
||||
let connector = row.connector.as_ref()?;
|
||||
let [top_left, _] = row.name_box(0.);
|
||||
Some(GraphNameField {
|
||||
name: connector.name.clone(),
|
||||
x: top_left.x,
|
||||
top: top_left.y,
|
||||
align_right: key.kind() == NetworkConnectorKind::Import,
|
||||
dimmed: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl GraphUiState {
|
||||
pub fn begin_name_edit(&mut self, name: GraphName, responses: &mut VecDeque<Message>) {
|
||||
if self.editing_name != Some(name) {
|
||||
self.editing_name = Some(name);
|
||||
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn end_name_edit(&mut self) -> Option<GraphName> {
|
||||
self.editing_name.take()
|
||||
}
|
||||
|
||||
pub fn update_name_field(&mut self, field: Option<GraphNameField>, responses: &mut VecDeque<Message>) {
|
||||
let shown = self.name_field.as_ref();
|
||||
let same_row = |(name, field): &(GraphName, GraphNameField)| match (name, shown) {
|
||||
(GraphName::NetworkConnector(_), Some((shown, shown_field))) if shown == name => shown_field.name == field.name,
|
||||
_ => true,
|
||||
};
|
||||
let edited = self.editing_name.zip(field).filter(same_row);
|
||||
if edited.is_none() {
|
||||
self.editing_name = None;
|
||||
}
|
||||
if edited == self.name_field {
|
||||
return;
|
||||
}
|
||||
let sent = self.name_field.as_ref().map(|(name, _)| *name);
|
||||
let opens = edited.as_ref().is_some_and(|(name, _)| sent != Some(*name));
|
||||
self.name_field.clone_from(&edited);
|
||||
responses.add(FrontendMessage::UpdateGraphNameField {
|
||||
field: edited.map(|(_, field)| field),
|
||||
opens,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn leave_network(&mut self, responses: &mut VecDeque<Message>) {
|
||||
if self.editing_name.is_some() || self.name_field.is_some() {
|
||||
self.drop_name_edit(responses);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn graph_view_toggled(&mut self, responses: &mut VecDeque<Message>) {
|
||||
self.tooltip = None;
|
||||
self.drop_name_edit(responses);
|
||||
}
|
||||
|
||||
fn drop_name_edit(&mut self, responses: &mut VecDeque<Message>) {
|
||||
self.editing_name = None;
|
||||
self.name_field = None;
|
||||
responses.add(FrontendMessage::UpdateGraphNameField { field: None, opens: false });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn edited_name(document: &DocumentMessageHandler) -> Option<GraphNameField> {
|
||||
let name = document.node_graph_handler.graph_ui.editing_name?;
|
||||
GraphUiSceneBuilder::of(document).name_field(name)
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::LayerClickTargetTypes;
|
||||
use crate::messages::prelude::FrontendMessage;
|
||||
use graph_ui::metrics::{CARD_ROW_PADDING, GRID_SIZE};
|
||||
use graph_ui::{error_badge, error_text_size};
|
||||
use std::cell::OnceCell;
|
||||
|
||||
impl GraphUiState {
|
||||
pub fn part_under_pointer(&mut self, hits: &PointerHits, errors: &[(NodeId, String)], pointer_free: bool) -> Option<NodePart> {
|
||||
if let Some(badge) = self.error_badge_under(hits, errors) {
|
||||
return Some(NodePart::ErrorBadge(badge));
|
||||
}
|
||||
|
||||
let (network_interface, network_path) = (hits.network_interface, hits.network_path);
|
||||
let dot = hits.node().filter(|node_id| network_interface.is_redirect_dot(node_id, network_path));
|
||||
if let Some(dot) = dot {
|
||||
if !pointer_free {
|
||||
return None;
|
||||
}
|
||||
if hits.output() == Some(OutputConnector::node(dot, 0)) {
|
||||
return Some(NodePart::DotOutput(dot));
|
||||
}
|
||||
let pulls_a_wire_in = hits.input() == Some(InputConnector::node_at_index(dot, 0));
|
||||
return (!pulls_a_wire_in).then_some(NodePart::Dot(dot));
|
||||
}
|
||||
|
||||
let visibility = hits.visibility().map(NodePart::Visibility);
|
||||
let lock = || hits.lock().map(NodePart::Lock);
|
||||
let grip = || hits.grip().map(NodePart::Grip);
|
||||
visibility.or_else(lock).or_else(grip)
|
||||
}
|
||||
|
||||
fn error_badge_under(&mut self, hits: &PointerHits, errors: &[(NodeId, String)]) -> Option<NodeId> {
|
||||
let mut badges: Vec<&(NodeId, String)> = errors.iter().collect();
|
||||
badges.sort_by_key(|(key, _)| (self.highlights.badge_hovered(*key), *key));
|
||||
let text_sizes = &mut self.error_text_sizes;
|
||||
text_sizes.retain(|text, _| badges.iter().any(|(_, badge_text)| badge_text == text));
|
||||
let mut text_size = |text: &String| match text_sizes.get(text) {
|
||||
Some(size) => *size,
|
||||
None => *text_sizes.entry(text.clone()).or_insert_with(|| error_text_size(text)),
|
||||
};
|
||||
let geometry = |key: &NodeId| hits.network_interface.with_layout(hits.network_path, |layout| layout.geometry(key)).flatten();
|
||||
let mut covers = |(key, text): &(NodeId, String)| geometry(key).is_some_and(|geometry| error_badge::covers(geometry.error_badge_anchor(), text_size(text), hits.point));
|
||||
badges.into_iter().rev().find(|badge| covers(badge)).map(|(key, _)| *key)
|
||||
}
|
||||
|
||||
pub fn set_tooltip(&mut self, target: Option<TooltipTarget>, network_interface: &NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque<Message>) {
|
||||
let (label, description) = target.map(|target| tooltip_text(target, network_interface, network_path)).unwrap_or_default();
|
||||
let tooltip = (target, label, description);
|
||||
if self.tooltip.as_ref() == Some(&tooltip) {
|
||||
return;
|
||||
}
|
||||
let (_, label, description) = self.tooltip.insert(tooltip).clone();
|
||||
responses.add(FrontendMessage::UpdateGraphTooltip { label, description });
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum TooltipTarget {
|
||||
Name(NetworkConnectorKey),
|
||||
AddConnector(NetworkConnectorKey),
|
||||
Connector(ConnectorKey),
|
||||
Visibility(NodeId),
|
||||
Lock(NodeId),
|
||||
Grip(NodeId),
|
||||
Dot(NodeId),
|
||||
Row { node: NodeId, row: usize },
|
||||
Node(NodeId),
|
||||
}
|
||||
|
||||
pub struct PointerHits<'a> {
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
network_path: &'a [NodeId],
|
||||
viewport_location: DVec2,
|
||||
point: DVec2,
|
||||
found: FoundHits,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FoundHits {
|
||||
name: OnceCell<Option<NetworkConnectorKey>>,
|
||||
empty_connector: OnceCell<Option<NetworkConnectorKey>>,
|
||||
node: OnceCell<Option<NodeId>>,
|
||||
visibility: OnceCell<Option<NodeId>>,
|
||||
lock: OnceCell<Option<NodeId>>,
|
||||
grip: OnceCell<Option<NodeId>>,
|
||||
input: OnceCell<Option<InputConnector>>,
|
||||
output: OnceCell<Option<OutputConnector>>,
|
||||
}
|
||||
|
||||
impl<'a> PointerHits<'a> {
|
||||
pub fn new(network_interface: &'a NodeNetworkInterface, network_path: &'a [NodeId], viewport_location: DVec2, point: DVec2) -> Self {
|
||||
Self {
|
||||
network_interface,
|
||||
network_path,
|
||||
viewport_location,
|
||||
point,
|
||||
found: FoundHits::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn name(&self) -> Option<NetworkConnectorKey> {
|
||||
*self.found.name.get_or_init(|| self.network_interface.import_export_name_from_point(self.point, self.network_path))
|
||||
}
|
||||
|
||||
fn empty_connector(&self) -> Option<NetworkConnectorKey> {
|
||||
*self.found.empty_connector.get_or_init(|| {
|
||||
let empty = |is_import| self.network_interface.empty_import_export_connector_at(self.point, is_import, self.network_path);
|
||||
let import = empty(true).map(|(index, _)| NetworkConnectorKey::Import(index));
|
||||
import.or_else(|| empty(false).map(|(index, _)| NetworkConnectorKey::Export(index)))
|
||||
})
|
||||
}
|
||||
|
||||
fn node(&self) -> Option<NodeId> {
|
||||
*self.found.node.get_or_init(|| self.network_interface.node_from_click(self.viewport_location, self.network_path))
|
||||
}
|
||||
|
||||
fn visibility(&self) -> Option<NodeId> {
|
||||
self.layer_button(&self.found.visibility, LayerClickTargetTypes::Visibility)
|
||||
}
|
||||
|
||||
fn lock(&self) -> Option<NodeId> {
|
||||
self.layer_button(&self.found.lock, LayerClickTargetTypes::Lock)
|
||||
}
|
||||
|
||||
fn grip(&self) -> Option<NodeId> {
|
||||
self.layer_button(&self.found.grip, LayerClickTargetTypes::Grip)
|
||||
}
|
||||
|
||||
fn layer_button(&self, found: &OnceCell<Option<NodeId>>, button: LayerClickTargetTypes) -> Option<NodeId> {
|
||||
*found.get_or_init(|| self.network_interface.layer_click_target_from_click(self.viewport_location, button, self.network_path))
|
||||
}
|
||||
|
||||
fn input(&self) -> Option<InputConnector> {
|
||||
*self.found.input.get_or_init(|| self.network_interface.input_port_from_click(self.viewport_location, self.network_path))
|
||||
}
|
||||
|
||||
fn output(&self) -> Option<OutputConnector> {
|
||||
*self
|
||||
.found
|
||||
.output
|
||||
.get_or_init(|| self.network_interface.output_port_from_click(self.viewport_location, self.network_path))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connector_under_pointer(hits: &PointerHits) -> Option<ConnectorKey> {
|
||||
if hits.name().is_some() || hits.visibility().is_some() || hits.lock().is_some() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let input = || hits.input().map(ConnectorKey::Input);
|
||||
let output = || hits.output().map(ConnectorKey::Output);
|
||||
hits.empty_connector().map(ConnectorKey::from).or_else(input).or_else(output)
|
||||
}
|
||||
|
||||
pub fn tooltip_target(hits: &PointerHits) -> Option<TooltipTarget> {
|
||||
let (network_interface, network_path) = (hits.network_interface, hits.network_path);
|
||||
if let Some(name) = hits.name() {
|
||||
return Some(TooltipTarget::Name(name));
|
||||
}
|
||||
if let Some(add) = hits.empty_connector() {
|
||||
return Some(TooltipTarget::AddConnector(add));
|
||||
}
|
||||
|
||||
let node = hits.node();
|
||||
if let Some(dot) = node.filter(|node| network_interface.is_redirect_dot(node, network_path)) {
|
||||
return Some(TooltipTarget::Dot(dot));
|
||||
}
|
||||
let input = || hits.input().map(|input| TooltipTarget::Connector(ConnectorKey::Input(input)));
|
||||
let output = || hits.output().map(|output| TooltipTarget::Connector(ConnectorKey::Output(output)));
|
||||
let part = hits
|
||||
.visibility()
|
||||
.map(TooltipTarget::Visibility)
|
||||
.or_else(|| hits.lock().map(TooltipTarget::Lock))
|
||||
.or_else(input)
|
||||
.or_else(output)
|
||||
.or_else(|| hits.grip().map(TooltipTarget::Grip));
|
||||
if part.is_some() {
|
||||
return part;
|
||||
}
|
||||
|
||||
let node = node?;
|
||||
if network_interface.is_layer(&node, network_path) {
|
||||
return Some(TooltipTarget::Node(node));
|
||||
}
|
||||
let point = hits.point;
|
||||
let [min, max] = network_interface.node_bounding_box(&node, network_path)?;
|
||||
let row = ((point.y - min.y) / GRID_SIZE).floor();
|
||||
let on_row_name = point.x >= min.x + CARD_ROW_PADDING && point.x <= max.x - CARD_ROW_PADDING;
|
||||
Some(if row >= 1. && on_row_name {
|
||||
TooltipTarget::Row { node, row: row as usize }
|
||||
} else {
|
||||
TooltipTarget::Node(node)
|
||||
})
|
||||
}
|
||||
|
||||
fn tooltip_text(target: TooltipTarget, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> (String, String) {
|
||||
let input = |input: InputConnector| network_interface.input_tooltip(&input, network_path);
|
||||
let output = |output: OutputConnector| network_interface.output_tooltip(&output, network_path);
|
||||
let input_tooltip = |key: InputConnector| {
|
||||
let lists_no_types = matches!(key, InputConnector::Node { .. });
|
||||
input(key).map(|input| connector_tooltip(input.name, &input.description, input.resolved_type, &input.valid_types, input.connected, lists_no_types))
|
||||
};
|
||||
let output_tooltip = |key: OutputConnector| output(key).map(|output| connector_tooltip(output.name, &output.description, output.resolved_type, &output.possible_types, output.connected, false));
|
||||
let label_only = |text: &str| (text.to_string(), String::new());
|
||||
|
||||
match target {
|
||||
TooltipTarget::Name(NetworkConnectorKey::Import(index)) => (network_interface.displayed_import_name(index, network_path), network_interface.import_description(index, network_path)),
|
||||
TooltipTarget::Name(NetworkConnectorKey::Export(index)) => (network_interface.displayed_export_name(index, network_path), network_interface.export_description(index, network_path)),
|
||||
TooltipTarget::AddConnector(add) => {
|
||||
let (label, description) = match add {
|
||||
NetworkConnectorKey::Import(index) => (
|
||||
if index == 0 { "Add Primary Import" } else { "Add Import" },
|
||||
"Drag a wire from here and connect it to an input, or drop one here from an input.",
|
||||
),
|
||||
NetworkConnectorKey::Export(index) => (
|
||||
if index == 0 { "Add Primary Export" } else { "Add Export" },
|
||||
"Drag a wire from here and connect it to an output, or drop one here from an output.",
|
||||
),
|
||||
};
|
||||
(label.to_string(), description.to_string())
|
||||
}
|
||||
TooltipTarget::Connector(ConnectorKey::Input(key)) => input_tooltip(key).unwrap_or_default(),
|
||||
TooltipTarget::Connector(ConnectorKey::Output(key)) => output_tooltip(key).unwrap_or_default(),
|
||||
TooltipTarget::Visibility(layer) => label_only(if network_interface.is_visible(&layer, network_path) { "Hide" } else { "Show" }),
|
||||
TooltipTarget::Lock(_) => label_only("Unlock"),
|
||||
TooltipTarget::Grip(_) => (String::new(), "Drag only this layer without pushing others outside the stack".to_string()),
|
||||
TooltipTarget::Dot(dot) => output_tooltip(OutputConnector::node(dot, 0)).unwrap_or_else(|| label_only(&network_interface.display_name(&dot, network_path))),
|
||||
TooltipTarget::Row { node, row } => {
|
||||
let exposed = |index: &usize| network_interface.graph_ui_input(&InputConnector::node_at_index(node, *index), network_path).is_some();
|
||||
let input_index = (1..network_interface.number_of_inputs(&node, network_path)).filter(exposed).nth(row - 1);
|
||||
let named_input = input_index.map(|index| network_interface.displayed_input_name_and_description(&node, index, network_path));
|
||||
let named_output = || {
|
||||
network_interface
|
||||
.graph_ui_output(&OutputConnector::node(node, row), network_path)
|
||||
.map(|(name, ..)| (name, network_interface.output_description(&node, row, network_path)))
|
||||
};
|
||||
named_input.or_else(named_output).unwrap_or_default()
|
||||
}
|
||||
TooltipTarget::Node(node) => {
|
||||
let (name, implementation_name) = (network_interface.display_name(&node, network_path), network_interface.implementation_name(&node, network_path));
|
||||
let label = if name == implementation_name { name } else { format!("{implementation_name} ({name})") };
|
||||
let definition = network_interface.reference(&node, network_path).and_then(|reference| resolve_document_node_type(&reference));
|
||||
(label, definition.map(|definition| definition.description.trim().to_string()).unwrap_or_default())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn connector_tooltip(name: String, description: &str, resolved_type: String, types: &[String], connected: bool, lists_no_types: bool) -> (String, String) {
|
||||
let wired_type = connected.then(|| format!("Wired Type:\n`{resolved_type}`"));
|
||||
let possible_types = if types.is_empty() {
|
||||
lists_no_types.then(|| "Possible Types:\nNone".to_string())
|
||||
} else {
|
||||
Some(format!("Possible Types:\n{}", types.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>().join("\n")))
|
||||
};
|
||||
let types = [wired_type, possible_types].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
|
||||
let description = [description.trim().to_string(), types].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join("\n---\n");
|
||||
(if name.is_empty() { resolved_type } else { name }, description)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod document_node_definitions;
|
||||
pub mod graph_ui;
|
||||
mod node_graph_message;
|
||||
mod node_graph_message_handler;
|
||||
pub mod node_inspector;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use super::graph_ui::GraphName;
|
||||
use super::utility_types::{Direction, NodeEvaluationError};
|
||||
use crate::messages::input_mapper::utility_types::keyboard::Key;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, ImportOrExport, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, InputConnector, NetworkConnectorKey, NodeTemplate, OutputConnector};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -78,7 +79,7 @@ pub enum NodeGraphMessage {
|
||||
},
|
||||
/// Disconnects every wire an import feeds, or the wire feeding an export.
|
||||
DisconnectImportExport {
|
||||
index: ImportOrExport,
|
||||
index: NetworkConnectorKey,
|
||||
},
|
||||
EnterNestedNetwork,
|
||||
DuplicateSelectedNodes,
|
||||
@@ -174,10 +175,7 @@ pub enum NodeGraphMessage {
|
||||
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.
|
||||
SendGlide,
|
||||
/// Sent every frame while nodes glide into their grid cells, to bring them closer.
|
||||
GlideTick,
|
||||
AnimationTick,
|
||||
ShakeNode,
|
||||
UpdateNodeGraphWidth,
|
||||
RemoveImport {
|
||||
@@ -188,7 +186,7 @@ pub enum NodeGraphMessage {
|
||||
},
|
||||
/// Removes an import or export, or hides it if it's the primary, since the primary slot always remains.
|
||||
RemoveImportExport {
|
||||
index: ImportOrExport,
|
||||
index: NetworkConnectorKey,
|
||||
},
|
||||
ReorderImport {
|
||||
start_index: usize,
|
||||
@@ -209,11 +207,8 @@ pub enum NodeGraphMessage {
|
||||
SelectedNodesSet {
|
||||
nodes: Vec<NodeId>,
|
||||
},
|
||||
UnloadWires,
|
||||
SendWires,
|
||||
UpdateVisibleNodes,
|
||||
UpdateLayersInView,
|
||||
SendGraph,
|
||||
SendNodePositions,
|
||||
SetInputValue {
|
||||
node_id: NodeId,
|
||||
input_index: usize,
|
||||
@@ -223,10 +218,11 @@ pub enum NodeGraphMessage {
|
||||
input_connector: InputConnector,
|
||||
input: NodeInput,
|
||||
},
|
||||
/// Asks the frontend to enter inline-rename mode for the given layer's display name in the graph view.
|
||||
/// Triggered by double-clicking the layer's name area.
|
||||
BeginEditLayerName {
|
||||
node_id: NodeId,
|
||||
BeginEditName {
|
||||
name: GraphName,
|
||||
},
|
||||
EndEditName {
|
||||
name: Option<String>,
|
||||
},
|
||||
SetDisplayName {
|
||||
node_id: NodeId,
|
||||
@@ -258,15 +254,11 @@ pub enum NodeGraphMessage {
|
||||
NudgeSelectedNodes {
|
||||
direction: Direction,
|
||||
},
|
||||
/// With `glide`, whatever the shift moves glides to where it lands, rather than jumping there.
|
||||
ShiftSelectedNodes {
|
||||
direction: Direction,
|
||||
glide: bool,
|
||||
},
|
||||
/// With `glide`, whatever the shift moves glides to where it lands, rather than jumping there.
|
||||
ShiftSelectedNodesByAmount {
|
||||
graph_delta: IVec2,
|
||||
glide: bool,
|
||||
},
|
||||
/// Draws the dragged nodes `offset` grid cells from where the drag started, stored once the drag finishes.
|
||||
DragSelectedNodes {
|
||||
@@ -280,19 +272,19 @@ pub enum NodeGraphMessage {
|
||||
},
|
||||
SetImportExportName {
|
||||
name: String,
|
||||
index: ImportOrExport,
|
||||
index: NetworkConnectorKey,
|
||||
},
|
||||
SetImportExportNameImpl {
|
||||
name: String,
|
||||
index: ImportOrExport,
|
||||
index: NetworkConnectorKey,
|
||||
},
|
||||
SetImportExportDescription {
|
||||
description: String,
|
||||
index: ImportOrExport,
|
||||
index: NetworkConnectorKey,
|
||||
},
|
||||
SetImportExportDescriptionImpl {
|
||||
description: String,
|
||||
index: ImportOrExport,
|
||||
index: NetworkConnectorKey,
|
||||
},
|
||||
ToggleSelectedAsLayersOrNodes,
|
||||
ToggleSelectedLocked,
|
||||
@@ -329,7 +321,6 @@ pub enum NodeGraphMessage {
|
||||
network_path: Vec<NodeId>,
|
||||
},
|
||||
UpdateBoxSelection,
|
||||
/// Shows hovered the connector a press at the pointer would grab, or none.
|
||||
UpdateHoveredConnector,
|
||||
/// Highlights the wire a dragged node would be inserted onto if dropped where it is, or stops highlighting one.
|
||||
UpdateWireInsertionPreview,
|
||||
@@ -354,7 +345,6 @@ pub enum NodeGraphMessage {
|
||||
},
|
||||
UpdateActionButtons,
|
||||
UpdateGraphBarRight,
|
||||
UpdateInSelectedNetwork,
|
||||
UpdateHints,
|
||||
SendSelectedNodes,
|
||||
}
|
||||
@@ -382,6 +372,7 @@ impl NodeGraphMessage {
|
||||
| Self::MergeSelectedNodes
|
||||
| Self::ReorderImport { .. }
|
||||
| Self::ReorderExport { .. }
|
||||
| Self::BeginEditName { .. }
|
||||
| Self::SetImportExportName { .. }
|
||||
| Self::SetImportExportNameImpl { .. }
|
||||
| Self::SetImportExportDescription { .. }
|
||||
@@ -418,7 +409,6 @@ impl NodeGraphMessage {
|
||||
| Self::RemoveImportExport { .. }
|
||||
| Self::SetInputValue { .. }
|
||||
| Self::SetInput { .. }
|
||||
| Self::BeginEditLayerName { .. }
|
||||
| Self::MakeUnique { .. }
|
||||
| Self::SetToNodeOrLayer { .. }
|
||||
| Self::ShiftNodePosition { .. }
|
||||
@@ -441,19 +431,16 @@ impl NodeGraphMessage {
|
||||
| Self::PointerOutsideViewport { .. }
|
||||
| Self::MiddleClick
|
||||
| Self::WireHoverTick
|
||||
| Self::SendGlide
|
||||
| Self::GlideTick
|
||||
| Self::AnimationTick
|
||||
| Self::UpdateNodeGraphWidth
|
||||
| Self::RunDocumentGraph
|
||||
| Self::ForceRunDocumentGraph
|
||||
| Self::SelectedNodesAdd { .. }
|
||||
| Self::SelectedNodesRemove { .. }
|
||||
| Self::SelectedNodesSet { .. }
|
||||
| Self::UnloadWires
|
||||
| Self::SendWires
|
||||
| Self::UpdateVisibleNodes
|
||||
| Self::UpdateLayersInView
|
||||
| Self::SendGraph
|
||||
| Self::SendNodePositions
|
||||
| Self::EndEditName { .. }
|
||||
| Self::TogglePreview { .. }
|
||||
| Self::TogglePreviewImpl { .. }
|
||||
| Self::UpdateBoxSelection
|
||||
@@ -467,7 +454,6 @@ impl NodeGraphMessage {
|
||||
| Self::UpdateEvaluationErrors { .. }
|
||||
| Self::UpdateActionButtons
|
||||
| Self::UpdateGraphBarRight
|
||||
| Self::UpdateInSelectedNetwork
|
||||
| Self::UpdateHints
|
||||
| Self::SendSelectedNodes => None,
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -31,14 +31,14 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
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};
|
||||
@@ -254,23 +254,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 {
|
||||
@@ -421,6 +404,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
// ============
|
||||
Some(x) if id_is::<Font>(x) => font_widget(default_info),
|
||||
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
|
||||
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
|
||||
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
|
||||
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
|
||||
@@ -433,7 +417,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(),
|
||||
@@ -676,6 +659,142 @@ pub fn image_data_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<Wi
|
||||
widgets
|
||||
}
|
||||
|
||||
pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||
|
||||
let mut location_widgets = start_widgets(¶meter_widgets_info);
|
||||
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
let mut scale_widgets = vec![TextLabel::new("").widget_instance()];
|
||||
add_blank_assist(&mut scale_widgets);
|
||||
scale_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
let mut resolution_widgets = vec![TextLabel::new("").widget_instance()];
|
||||
add_blank_assist(&mut resolution_widgets);
|
||||
resolution_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
let Some(document_node) = document_node else { return LayoutGroup::default() };
|
||||
let Some(input) = document_node.inputs.get(index) else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return Vec::new().into();
|
||||
};
|
||||
|
||||
if let Some(&TaggedValue::Footprint(footprint)) = input.as_non_exposed_value() {
|
||||
let top_left = footprint.transform.transform_point2(DVec2::ZERO);
|
||||
let bounds = footprint.scale();
|
||||
let oversample = footprint.resolution.as_dvec2() / bounds;
|
||||
|
||||
location_widgets.extend_from_slice(&[
|
||||
NumberInput::new(Some(top_left.x))
|
||||
.label("X")
|
||||
.unit(" px")
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
|
||||
let (offset, scale) = {
|
||||
let diff = DVec2::new(top_left.x - x.value.unwrap_or_default(), 0.);
|
||||
(top_left - diff, bounds)
|
||||
};
|
||||
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
||||
resolution: (oversample * scale).as_uvec2(),
|
||||
..footprint
|
||||
};
|
||||
|
||||
TaggedValue::Footprint(footprint)
|
||||
}))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(top_left.y))
|
||||
.label("Y")
|
||||
.unit(" px")
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
|
||||
let (offset, scale) = {
|
||||
let diff = DVec2::new(0., top_left.y - x.value.unwrap_or_default());
|
||||
(top_left - diff, bounds)
|
||||
};
|
||||
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
||||
resolution: (oversample * scale).as_uvec2(),
|
||||
..footprint
|
||||
};
|
||||
|
||||
TaggedValue::Footprint(footprint)
|
||||
}))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
scale_widgets.extend_from_slice(&[
|
||||
NumberInput::new(Some(bounds.x))
|
||||
.label("W")
|
||||
.unit(" px")
|
||||
.on_update(update_value_at_index(
|
||||
move |x: &NumberInput| {
|
||||
let (offset, scale) = (top_left, DVec2::new(x.value.unwrap_or_default(), bounds.y));
|
||||
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
||||
resolution: (oversample * scale).as_uvec2(),
|
||||
..footprint
|
||||
};
|
||||
|
||||
TaggedValue::Footprint(footprint)
|
||||
},
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(bounds.y))
|
||||
.label("H")
|
||||
.unit(" px")
|
||||
.on_update(update_value_at_index(
|
||||
move |x: &NumberInput| {
|
||||
let (offset, scale) = (top_left, DVec2::new(bounds.x, x.value.unwrap_or_default()));
|
||||
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
||||
resolution: (oversample * scale).as_uvec2(),
|
||||
..footprint
|
||||
};
|
||||
|
||||
TaggedValue::Footprint(footprint)
|
||||
},
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
resolution_widgets.push(
|
||||
NumberInput::new(Some((footprint.resolution.as_dvec2() / bounds).x * 100.))
|
||||
.label("Resolution")
|
||||
.mode_range()
|
||||
.min(0.)
|
||||
.range_min(Some(1.))
|
||||
.range_max(Some(100.))
|
||||
.unit("%")
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
|
||||
let resolution = (bounds * x.value.unwrap_or(100.) / 100.).as_uvec2().max((1, 1).into()).min((4000, 4000).into());
|
||||
|
||||
let footprint = Footprint { resolution, ..footprint };
|
||||
TaggedValue::Footprint(footprint)
|
||||
}))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
let widgets = [LayoutGroup::row(location_widgets), LayoutGroup::row(scale_widgets), LayoutGroup::row(resolution_widgets)];
|
||||
let (last, rest) = widgets.split_last().expect("Footprint widget should return multiple rows");
|
||||
*extra_widgets = rest.to_vec();
|
||||
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 {
|
||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||
@@ -3167,80 +3286,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::*;
|
||||
|
||||
@@ -3398,7 +3443,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();
|
||||
}
|
||||
|
||||
@@ -3787,25 +3843,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();
|
||||
|
||||
@@ -37,78 +37,33 @@ impl FrontendGraphDataType {
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
// A generator draws pixels like an image, at whatever resolution is needed
|
||||
"Generator" => Self::Raster,
|
||||
"Pixels" => Self::Raster,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendGraphInput {
|
||||
#[serde(rename = "dataType")]
|
||||
pub data_type: FrontendGraphDataType,
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct InputTooltip {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
#[serde(rename = "resolvedType")]
|
||||
pub resolved_type: String,
|
||||
#[serde(rename = "validTypes")]
|
||||
pub valid_types: Vec<String>,
|
||||
/// Whether a wire feeds this input.
|
||||
pub connected: bool,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendGraphOutput {
|
||||
#[serde(rename = "dataType")]
|
||||
pub data_type: FrontendGraphDataType,
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct OutputTooltip {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
#[serde(rename = "resolvedType")]
|
||||
pub resolved_type: String,
|
||||
/// Every type this output could produce given its node's current inputs, or empty where that isn't known.
|
||||
#[serde(rename = "possibleTypes")]
|
||||
pub possible_types: Vec<String>,
|
||||
/// Whether this output feeds at least one wire.
|
||||
pub connected: bool,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendNode {
|
||||
pub id: graph_craft::document::NodeId,
|
||||
#[serde(rename = "isLayer")]
|
||||
pub is_layer: bool,
|
||||
#[serde(rename = "canBeLayer")]
|
||||
pub can_be_layer: bool,
|
||||
/// Whether the node is a redirect dot, which is a Passthrough node drawn as a small dot bending the wire running through it.
|
||||
#[serde(rename = "isRedirectDot")]
|
||||
pub is_redirect_dot: bool,
|
||||
pub reference: Option<String>,
|
||||
#[serde(rename = "displayName")]
|
||||
pub display_name: String,
|
||||
#[serde(rename = "implementationName")]
|
||||
pub implementation_name: String,
|
||||
#[serde(rename = "primaryInput")]
|
||||
pub primary_input: Option<FrontendGraphInput>,
|
||||
#[serde(rename = "exposedInputs")]
|
||||
pub exposed_inputs: Vec<FrontendGraphInput>,
|
||||
#[serde(rename = "primaryOutput")]
|
||||
pub primary_output: Option<FrontendGraphOutput>,
|
||||
#[serde(rename = "exposedOutputs")]
|
||||
pub exposed_outputs: Vec<FrontendGraphOutput>,
|
||||
#[serde(rename = "primaryInputConnectedToLayer")]
|
||||
pub primary_input_connected_to_layer: bool,
|
||||
#[serde(rename = "primaryOutputConnectedToLayer")]
|
||||
pub primary_output_connected_to_layer: bool,
|
||||
pub position: (i32, i32),
|
||||
pub previewed: bool,
|
||||
pub visible: bool,
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum InputTypeConstraint {
|
||||
@@ -136,19 +91,6 @@ pub struct DragStart {
|
||||
pub stored: IVec2,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct BoxSelection {
|
||||
#[serde(rename = "startX")]
|
||||
pub start_x: u32,
|
||||
#[serde(rename = "startY")]
|
||||
pub start_y: u32,
|
||||
#[serde(rename = "endX")]
|
||||
pub end_x: u32,
|
||||
#[serde(rename = "endY")]
|
||||
pub end_y: u32,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(tag = "type", content = "data")]
|
||||
@@ -181,6 +123,10 @@ pub enum ContextMenuData {
|
||||
exposed: bool,
|
||||
/// Whether any wire is attached to it within the subgraph.
|
||||
connected: bool,
|
||||
description: String,
|
||||
/// Where the description popover points, in node graph coordinates.
|
||||
#[serde(rename = "descriptionAnchor")]
|
||||
description_anchor: (f64, f64),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -197,16 +143,6 @@ pub struct ContextMenuInformation {
|
||||
pub context_menu_data: ContextMenuData,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NodeGraphErrorDiagnostic {
|
||||
/// The node the error is shown beside, which it follows as the node glides into place.
|
||||
#[serde(rename = "nodeId")]
|
||||
pub node_id: NodeId,
|
||||
pub position: (i32, i32),
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NodeEvaluationError {
|
||||
pub node_path: Vec<NodeId>,
|
||||
|
||||
@@ -24,9 +24,12 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
OverlaysMessage::Draw => {
|
||||
use super::utility_types::OverlayContext;
|
||||
|
||||
if context.graph_open {
|
||||
return;
|
||||
}
|
||||
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,9 +1,11 @@
|
||||
//! 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::wires::GraphWireStyle;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::Part;
|
||||
use glam::DVec2;
|
||||
use graph_ui::geometry::WireEnd;
|
||||
use graph_ui::router::route;
|
||||
use graph_ui::wire::WireStyle;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use std::time::Instant;
|
||||
|
||||
@@ -19,38 +21,6 @@ const DEMOS: [&str; 8] = [
|
||||
];
|
||||
const REPETITIONS: u32 = 200;
|
||||
|
||||
#[test]
|
||||
fn wire_anchors_lie_on_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,
|
||||
}
|
||||
};
|
||||
|
||||
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:?}");
|
||||
}
|
||||
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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn time_the_layout_click_targets_and_hit_tests() {
|
||||
@@ -81,7 +51,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
|
||||
let start = Instant::now();
|
||||
for _ in 0..REPETITIONS {
|
||||
for input in &inputs {
|
||||
std::hint::black_box(interface.wire_update_from_input(input, GraphWireStyle::default(), &GlideOffsets::default(), &[]));
|
||||
std::hint::black_box(interface.vector_wire_from_input(input, WireStyle::default(), &[]));
|
||||
}
|
||||
}
|
||||
let all_wires = start.elapsed() / REPETITIONS;
|
||||
@@ -104,25 +74,16 @@ fn time_the_layout_click_targets_and_hit_tests() {
|
||||
let types = start.elapsed() / REPETITIONS;
|
||||
let endpoints: Vec<_> = connected
|
||||
.iter()
|
||||
.filter_map(|(input, output)| Some((interface.output_position(output, &[])?, interface.input_position(input, &[])?)))
|
||||
.filter_map(|(input, output)| Some([interface.output_position(output, &[])?, interface.input_position(input, &[])?].map(|position| WireEnd { position, vertical: false })))
|
||||
.collect();
|
||||
let start = Instant::now();
|
||||
for _ in 0..REPETITIONS {
|
||||
for (output, input) in &endpoints {
|
||||
std::hint::black_box(crate::messages::portfolio::document::utility_types::wires::build_vector_wire(
|
||||
*output,
|
||||
*input,
|
||||
false,
|
||||
false,
|
||||
GraphWireStyle::default(),
|
||||
));
|
||||
for ends in &endpoints {
|
||||
std::hint::black_box(route(*ends, WireStyle::default()));
|
||||
}
|
||||
}
|
||||
let paths = start.elapsed() / REPETITIONS;
|
||||
let built: Vec<_> = endpoints
|
||||
.iter()
|
||||
.map(|(output, input)| crate::messages::portfolio::document::utility_types::wires::build_vector_wire(*output, *input, false, false, GraphWireStyle::default()))
|
||||
.collect();
|
||||
let built: Vec<_> = endpoints.iter().map(|ends| route(*ends, WireStyle::default())).collect();
|
||||
let start = Instant::now();
|
||||
for _ in 0..REPETITIONS {
|
||||
for path in &built {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -2,13 +2,13 @@ use crate::messages::prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// The layers the frontend shows in view, as rows of the Layers panel and as nodes in the node graph, which are the only ones it's sent the thumbnails of.
|
||||
/// The latest thumbnail of every layer waits here for whenever the layer comes into view.
|
||||
/// The layers in view in the Layers panel and the node graph, which the graph runtime renders thumbnails for.
|
||||
/// The latest thumbnail of each waits here, and goes to the frontend while its layer has a row in view in the Layers panel.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LayersInView {
|
||||
/// The layers with a row in view in the Layers panel, which is also sent their details.
|
||||
layers_panel: HashSet<NodeId>,
|
||||
/// The nodes in view in the node graph while it's open.
|
||||
/// The layers in view in the node graph while it's open.
|
||||
node_graph: HashSet<NodeId>,
|
||||
/// The message with the latest thumbnail of each layer, as rendered by the graph runtime.
|
||||
thumbnails: HashMap<NodeId, FrontendMessage>,
|
||||
@@ -29,27 +29,26 @@ impl LayersInView {
|
||||
/// Sets the layers with a row in view in the Layers panel, sending the thumbnails it lacks for them.
|
||||
pub fn set_layers_panel(&mut self, layers: HashSet<NodeId>, responses: &mut VecDeque<Message>) {
|
||||
self.layers_panel = layers;
|
||||
self.send_thumbnails_in_view(responses);
|
||||
self.send_thumbnails_in_layers_panel(responses);
|
||||
responses.add(PortfolioMessage::SubmitThumbnailsInView);
|
||||
}
|
||||
|
||||
/// Sets the nodes in view in the node graph, sending the thumbnails it lacks for those that are layers.
|
||||
/// Sets the nodes in view in the node graph, which draws the thumbnails of those that are layers itself.
|
||||
pub fn set_node_graph(&mut self, nodes: HashSet<NodeId>, responses: &mut VecDeque<Message>) {
|
||||
self.node_graph = nodes;
|
||||
self.send_thumbnails_in_view(responses);
|
||||
responses.add(PortfolioMessage::SubmitThumbnailsInView);
|
||||
}
|
||||
|
||||
pub fn thumbnail_layer(message: &FrontendMessage) -> Option<NodeId> {
|
||||
match message {
|
||||
FrontendMessage::UpdateNodeThumbnailCanvases { id, .. } | FrontendMessage::UpdateNodeThumbnailPixels { id, .. } => Some(*id),
|
||||
FrontendMessage::UpdateNodeThumbnailCanvas { id, .. } | FrontendMessage::UpdateNodeThumbnailPixels { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the message with a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view.
|
||||
/// Keeps the message with a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view in the Layers panel.
|
||||
pub fn receive_thumbnail(&mut self, layer: NodeId, thumbnail: FrontendMessage, responses: &mut VecDeque<Message>) {
|
||||
if self.in_view(&layer) {
|
||||
if self.layers_panel.contains(&layer) {
|
||||
responses.add(thumbnail.clone());
|
||||
self.thumbnails_sent.insert(layer);
|
||||
} else {
|
||||
@@ -79,13 +78,8 @@ impl LayersInView {
|
||||
}
|
||||
}
|
||||
|
||||
fn in_view(&self, layer: &NodeId) -> bool {
|
||||
self.layers_panel.contains(layer) || self.node_graph.contains(layer)
|
||||
}
|
||||
|
||||
// O(layers in view)
|
||||
fn send_thumbnails_in_view(&mut self, responses: &mut VecDeque<Message>) {
|
||||
for &layer in self.layers_panel.iter().chain(&self.node_graph) {
|
||||
fn send_thumbnails_in_layers_panel(&mut self, responses: &mut VecDeque<Message>) {
|
||||
for &layer in &self.layers_panel {
|
||||
if self.thumbnails_sent.contains(&layer) {
|
||||
continue;
|
||||
}
|
||||
@@ -136,7 +130,7 @@ mod tests {
|
||||
assert_eq!(thumbnails_sent(responses), vec![(layer, "latest".to_string())], "coming into view, only the latest thumbnail is sent");
|
||||
|
||||
let mut responses = VecDeque::new();
|
||||
layers_in_view.set_node_graph(HashSet::from([layer]), &mut responses);
|
||||
layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses);
|
||||
assert!(thumbnails_sent(responses).is_empty(), "a thumbnail the frontend already has isn't sent again");
|
||||
}
|
||||
|
||||
|
||||
@@ -6,4 +6,3 @@ pub mod network_interface;
|
||||
pub mod nodes;
|
||||
pub mod text_metrics;
|
||||
pub mod transformation;
|
||||
pub mod wires;
|
||||
@@ -9,12 +9,12 @@ pub(crate) use catalog::shipped_node_id;
|
||||
pub(crate) use derived_ids::derived_node_id;
|
||||
#[cfg(test)]
|
||||
mod characterization_tests;
|
||||
mod connectors;
|
||||
mod derived_ids;
|
||||
mod deserialization;
|
||||
pub mod editor_delta;
|
||||
#[cfg(test)]
|
||||
mod editor_delta_tests;
|
||||
mod frontend;
|
||||
mod geometry;
|
||||
mod hit_tests;
|
||||
mod invalidation;
|
||||
@@ -22,7 +22,6 @@ mod layout;
|
||||
mod layout_pass;
|
||||
mod memo_network;
|
||||
mod mutations;
|
||||
mod node_parts;
|
||||
mod queries;
|
||||
mod reconcile;
|
||||
mod resolved_types;
|
||||
@@ -36,8 +35,8 @@ mod validation;
|
||||
mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use graph_ui::geometry::{Part, PartTarget};
|
||||
pub use layout_pass::NetworkLayout;
|
||||
pub use node_parts::{Part, PartTarget};
|
||||
pub use reconcile::{ReconcileError, Reconciled};
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
@@ -50,14 +49,11 @@ use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier, NodeRelati
|
||||
use super::misc::PTZ;
|
||||
use super::nodes::SelectedNodes;
|
||||
use crate::consts::{
|
||||
EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, HALF_GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH,
|
||||
STACK_VERTICAL_GAP,
|
||||
EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, 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::{InputTooltip, OutputTooltip};
|
||||
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};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
|
||||
use deserialization::deserialize_node_persistent_metadata;
|
||||
@@ -66,6 +62,9 @@ use graph_craft::Type;
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, LiftedNetwork, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
|
||||
use graph_ui::geometry::is_thick_wire;
|
||||
use graph_ui::router::route;
|
||||
use graph_ui::wire::WireStyle;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::registry::MULTI_OUTPUT_NODES;
|
||||
@@ -479,8 +478,8 @@ mod network_interface_tests {
|
||||
let mut interface = NodeNetworkInterface::from_trees(network, network_metadata);
|
||||
assert_eq!(interface.validate_invariants(), Vec::<String>::new());
|
||||
|
||||
interface.set_import_export_name("Shared".into(), ImportOrExport::Import(0), &[NodeId(10)]);
|
||||
interface.set_import_export_name("Result".into(), ImportOrExport::Export(0), &[NodeId(10)]);
|
||||
interface.set_import_export_name("Shared".into(), NetworkConnectorKey::Import(0), &[NodeId(10)]);
|
||||
interface.set_import_export_name("Result".into(), NetworkConnectorKey::Export(0), &[NodeId(10)]);
|
||||
|
||||
let view = interface.view(&[]).unwrap();
|
||||
assert_eq!(view.persistent_input_metadata(&NodeId(11), 0).unwrap().input_name, "Shared");
|
||||
|
||||
@@ -74,20 +74,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn glide_offsets(&self, network_path: &[NodeId]) -> GlideOffsets {
|
||||
self.network_metadata(network_path)
|
||||
.map(|network_metadata| network_metadata.transient_metadata.glide_offsets.borrow().clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn set_glide_offsets(&self, glide_offsets: GlideOffsets, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in set_glide_offsets");
|
||||
return;
|
||||
};
|
||||
*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)?;
|
||||
@@ -279,10 +265,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");
|
||||
@@ -312,29 +294,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_input_center(&self, input: &InputConnector, network_path: &[NodeId]) -> Option<DVec2> {
|
||||
self.input_position(input, network_path)
|
||||
}
|
||||
|
||||
pub fn get_output_center(&self, output: &OutputConnector, network_path: &[NodeId]) -> Option<DVec2> {
|
||||
self.output_position(output, network_path)
|
||||
}
|
||||
|
||||
/// The wire into the input as the frontend draws it, with its ends following anything drawn gliding into place.
|
||||
pub fn wire_update_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
|
||||
let wire = self.wire_path_from_input(input, graph_wire_style, false, glide_offsets, network_path)?;
|
||||
let (id, input_index) = match input {
|
||||
InputConnector::Node { node_id, input_index } => (*node_id, *input_index),
|
||||
InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index),
|
||||
};
|
||||
|
||||
Some(WirePathUpdate {
|
||||
id,
|
||||
input_index,
|
||||
wire_path_update: Some(wire),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn all_input_connectors(&self, network_path: &[NodeId]) -> Vec<InputConnector> {
|
||||
let mut input_connectors = Vec::new();
|
||||
let Some(network) = self.nested_network(network_path) else {
|
||||
@@ -359,119 +318,24 @@ impl NodeNetworkInterface {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Maps to the frontend representation of a wire start. Includes disconnected value wire inputs.
|
||||
pub fn node_graph_wire_inputs(&self, network_path: &[NodeId]) -> Vec<(NodeId, usize)> {
|
||||
self.node_graph_input_connectors(network_path)
|
||||
.iter()
|
||||
.map(|input| match input {
|
||||
InputConnector::Node { node_id, input_index } => (*node_id, *input_index),
|
||||
InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index),
|
||||
})
|
||||
.chain(std::iter::once((NodeId(u64::MAX), u32::MAX as usize)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The dashed wire from the previewed node to the export, drawn alongside the export's own wire.
|
||||
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
|
||||
let input = InputConnector::Export(0);
|
||||
|
||||
let Previewing::Yes { previewed } = self.previewing(network_path) else { return None };
|
||||
|
||||
if self.upstream_output_connector(&input, network_path) == Some(previewed.to_connector()) {
|
||||
return None;
|
||||
}
|
||||
let Some(input_position) = self.get_input_center(&input, network_path) else {
|
||||
log::error!("Could not get input position for wire end in preview: {input:?}");
|
||||
return None;
|
||||
};
|
||||
let input_position = input_position + glide_offsets.input(&input);
|
||||
let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index);
|
||||
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
|
||||
log::error!("Could not get output position for wire start in preview: {upstream_output:?}");
|
||||
return None;
|
||||
};
|
||||
let output_position = output_position + glide_offsets.output(&upstream_output);
|
||||
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
|
||||
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 path_string = vector_wire.to_svg();
|
||||
let center_path_string = center_line.to_svg();
|
||||
let output_type = self.output_type(&upstream_output, network_path);
|
||||
let data_type = output_type.displayed_type();
|
||||
let is_list = output_type.is_list();
|
||||
let wire_path_update = Some(WirePath {
|
||||
path_string,
|
||||
data_type,
|
||||
thick,
|
||||
dashed: true,
|
||||
is_list,
|
||||
center_path_string,
|
||||
});
|
||||
|
||||
Some(WirePathUpdate {
|
||||
id: NodeId(u64::MAX),
|
||||
input_index: u32::MAX as usize,
|
||||
wire_path_update,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the wire subpath, its thick center-line subpath, and whether the wire should be thick.
|
||||
pub fn vector_wire_from_input(&self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
|
||||
self.gliding_vector_wire_from_input(input, wire_style, &GlideOffsets::default(), network_path)
|
||||
}
|
||||
|
||||
/// Like [`Self::vector_wire_from_input`], but with its ends following anything drawn gliding into place.
|
||||
pub(crate) fn gliding_vector_wire_from_input(&self, input: &InputConnector, wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
|
||||
let Some(input_position) = self.get_input_center(input, network_path) else {
|
||||
/// Returns the wire subpath and whether the wire should be thick, or None if nothing feeds the input.
|
||||
pub fn vector_wire_from_input(&self, input: &InputConnector, wire_style: WireStyle, network_path: &[NodeId]) -> Option<(BezPath, bool)> {
|
||||
let Some(to) = self.input_end(input, network_path) else {
|
||||
log::error!("Could not get dom rect for wire end: {input:?}");
|
||||
return None;
|
||||
};
|
||||
let input_position = input_position + glide_offsets.input(input);
|
||||
// An upstream output could not be found, so the wire does not exist, but it should still be loaded as as empty vector
|
||||
let Some(upstream_output) = self.upstream_output_connector(input, network_path) else {
|
||||
return Some((BezPath::new(), BezPath::new(), false));
|
||||
};
|
||||
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
|
||||
let upstream_output = self.upstream_output_connector(input, network_path)?;
|
||||
let Some(from) = self.output_end(&upstream_output, network_path) else {
|
||||
log::error!("Could not get output port for wire start: {upstream_output:?}");
|
||||
return None;
|
||||
};
|
||||
let output_position = output_position + glide_offsets.output(&upstream_output);
|
||||
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
|
||||
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);
|
||||
Some((vector_wire, center_line, thick))
|
||||
}
|
||||
|
||||
pub fn wire_path_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, dashed: bool, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePath> {
|
||||
let (vector_wire, center_line, thick) = self.gliding_vector_wire_from_input(input, graph_wire_style, glide_offsets, network_path)?;
|
||||
let path_string = vector_wire.to_svg();
|
||||
let center_path_string = center_line.to_svg();
|
||||
let (data_type, is_list) = self
|
||||
.upstream_output_connector(input, network_path)
|
||||
.map(|output| {
|
||||
let output_type = self.output_type(&output, network_path);
|
||||
(output_type.displayed_type(), output_type.is_list())
|
||||
})
|
||||
.unwrap_or((FrontendGraphDataType::General, false));
|
||||
Some(WirePath {
|
||||
path_string,
|
||||
data_type,
|
||||
thick,
|
||||
dashed,
|
||||
is_list,
|
||||
center_path_string,
|
||||
})
|
||||
Some((route([from, to], wire_style), is_thick_wire([from, to])))
|
||||
}
|
||||
|
||||
/// 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_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()?;
|
||||
let body = self.with_layout(network_path, |layout| layout.geometry(node_id)).flatten()?.body();
|
||||
Some([body.min, body.max])
|
||||
}
|
||||
}
|
||||
|
||||
+16
-110
@@ -1,5 +1,5 @@
|
||||
use super::{
|
||||
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
|
||||
ChainInsertionPoint, FlowType, InputConnector, LayerClickTargetTypes, NetworkConnectorKey, 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};
|
||||
@@ -7,10 +7,10 @@ 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};
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeInput};
|
||||
use graph_ui::wire::WireStyle;
|
||||
use graphene_std::uuid::NodeId;
|
||||
|
||||
fn assert_invariants(editor: &EditorTestUtils, context: &str) {
|
||||
@@ -1190,12 +1190,7 @@ async fn a_stack_closes_up_over_a_deleted_layer_and_a_nudge_moves_the_rest_one_r
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third] }).await;
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let before = network_interface.position(&third, &[]).expect("Surviving layer should have a position");
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::ShiftSelectedNodes {
|
||||
direction: Direction::Down,
|
||||
glide: false,
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Down }).await;
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let after = network_interface.position(&third, &[]).expect("Surviving layer should have a position");
|
||||
assert_eq!(after.y - before.y, 1, "A single nudge should move the layer exactly one unit");
|
||||
@@ -1452,13 +1447,13 @@ async fn editing_import_and_export_descriptions_stores_them_on_the_subgraph_node
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetImportExportDescription {
|
||||
description: "The artwork to add.".to_string(),
|
||||
index: ImportOrExport::Import(1),
|
||||
index: NetworkConnectorKey::Import(1),
|
||||
})
|
||||
.await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetImportExportDescription {
|
||||
description: "The combined result.".to_string(),
|
||||
index: ImportOrExport::Export(0),
|
||||
index: NetworkConnectorKey::Export(0),
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -2442,14 +2437,14 @@ fn a_node_dragged_over_exactly_one_wire_previews_being_inserted_onto_it() {
|
||||
// Level with the wire between the other two
|
||||
network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]);
|
||||
assert_eq!(
|
||||
NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]),
|
||||
NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]),
|
||||
Some((dragged, 0, InputConnector::node_at_index(consumer, 0))),
|
||||
"the wire it overlaps is the one a drop would insert it onto"
|
||||
);
|
||||
|
||||
network_interface.set_absolute_position(&dragged, IVec2::new(8, 10), &[]);
|
||||
assert_eq!(
|
||||
NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]),
|
||||
NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]),
|
||||
None,
|
||||
"clear of every wire it previews nothing"
|
||||
);
|
||||
@@ -2457,7 +2452,7 @@ fn a_node_dragged_over_exactly_one_wire_previews_being_inserted_onto_it() {
|
||||
// With a node already taking its output, a drop would not insert it
|
||||
network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]);
|
||||
network_interface.set_input(&InputConnector::node_at_index(source, 0), NodeInput::node(dragged, 0), &[]);
|
||||
assert_eq!(NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), None);
|
||||
assert_eq!(NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]), None);
|
||||
}
|
||||
|
||||
fn passthrough_definition() -> DefinitionIdentifier {
|
||||
@@ -2864,7 +2859,7 @@ async fn double_click_in_graph(editor: &mut EditorTestUtils, point: DVec2, secon
|
||||
fn wire_middle(network_interface: &NodeNetworkInterface, input: InputConnector) -> DVec2 {
|
||||
use kurbo::ParamCurveArclen;
|
||||
|
||||
let (wire, _, _) = network_interface.vector_wire_from_input(&input, GraphWireStyle::Direct, &[]).expect("the wire should have a path");
|
||||
let (wire, _) = network_interface.vector_wire_from_input(&input, WireStyle::Direct, &[]).expect("the wire should have a path");
|
||||
let longest_segment = wire
|
||||
.segments()
|
||||
.max_by(|a, b| a.arclen(kurbo::DEFAULT_ACCURACY).total_cmp(&b.arclen(kurbo::DEFAULT_ACCURACY)))
|
||||
@@ -3711,96 +3706,18 @@ fn a_wire_is_found_near_its_path_but_not_away_from_it() {
|
||||
let input = InputConnector::node_at_index(consumer, 0);
|
||||
let on_wire = wire_middle(&network_interface, input);
|
||||
|
||||
assert_eq!(network_interface.wire_input_from_point(on_wire, 6., GraphWireStyle::Direct, &[]), Some(input));
|
||||
assert_eq!(network_interface.wire_input_from_point(on_wire + DVec2::new(0., 200.), 6., GraphWireStyle::Direct, &[]), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_dragged_layer_keeps_its_wires_where_it_is_drawn_in_the_frame_it_moves() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, ..) = layer_with_chain(&mut editor).await;
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
|
||||
let left_input = InputConnector::layer_secondary_input(layer);
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let wire_before = network_interface.wire_path_from_input(&left_input, GraphWireStyle::default(), false, &GlideOffsets::default(), &[]);
|
||||
let bounds = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
|
||||
let press = DVec2::new(bounds[1].x - 30., (bounds[0].y + bounds[1].y) / 2.);
|
||||
let node_graph_to_viewport = network_interface
|
||||
.network_metadata(&[])
|
||||
.expect("the network should have metadata")
|
||||
.persistent_metadata
|
||||
.navigation_metadata
|
||||
.node_graph_to_viewport;
|
||||
|
||||
let pressed = node_graph_to_viewport.transform_point2(press);
|
||||
editor.move_mouse(pressed.x, pressed.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::PointerDown {
|
||||
shift_click: false,
|
||||
control_click: false,
|
||||
alt_click: false,
|
||||
right_click: false,
|
||||
})
|
||||
.await;
|
||||
|
||||
// One grid cell right, through the input preprocessor so the frontend messages of the move itself are returned
|
||||
let moved = node_graph_to_viewport.transform_point2(press + DVec2::new(GRID_SIZE as f64, 0.));
|
||||
let editor_mouse_state = EditorPointerState {
|
||||
editor_position: moved,
|
||||
mouse_keys: MouseKeys::LEFT,
|
||||
..Default::default()
|
||||
};
|
||||
let messages = editor
|
||||
.handle_message(InputPreprocessorMessage::PointerMove {
|
||||
editor_mouse_state,
|
||||
modifier_keys: ModifierKeys::empty(),
|
||||
})
|
||||
.await;
|
||||
|
||||
// Still drawn a whole cell back as it starts gliding, so the last wire sent to its left input is the one from before the move
|
||||
let last_wire_sent = messages
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
FrontendMessage::UpdateNodeGraphWires { wires } => Some(wires),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.rfind(|wire| wire.id == layer && wire.input_index == 1)
|
||||
.and_then(|wire| wire.wire_path_update);
|
||||
assert_eq!(last_wire_sent.map(|wire| wire.path_string), wire_before.map(|wire| wire.path_string));
|
||||
}
|
||||
|
||||
/// Nudges the only node of a new document while its graph is open, so the node starts gliding into the cell it moved to.
|
||||
async fn gliding_nudged_node(editor: &mut EditorTestUtils) -> NodeId {
|
||||
editor.new_document().await;
|
||||
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await;
|
||||
editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await;
|
||||
assert!(
|
||||
!editor.active_document().network_interface.glide_offsets(&[]).is_empty(),
|
||||
"the nudged node should be gliding: fixture is wrong"
|
||||
);
|
||||
node
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redoing_a_nudge_undone_while_it_glides_leaves_nothing_gliding() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
gliding_nudged_node(&mut editor).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
editor.handle_message(DocumentMessage::Redo).await;
|
||||
|
||||
assert!(editor.active_document().network_interface.glide_offsets(&[]).is_empty());
|
||||
assert_eq!(network_interface.wire_input_from_point(on_wire, 6., WireStyle::Direct, &[]), Some(input));
|
||||
assert_eq!(network_interface.wire_input_from_point(on_wire + DVec2::new(0., 200.), 6., WireStyle::Direct, &[]), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn undoing_a_nudge_keeps_the_node_it_moved() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
let node = gliding_nudged_node(&mut editor).await;
|
||||
editor.new_document().await;
|
||||
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await;
|
||||
editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().network_interface.position(&node, &[]), Some(IVec2::ZERO));
|
||||
@@ -3822,17 +3739,6 @@ async fn undoing_right_after_creating_a_node_removes_only_that_node() {
|
||||
assert_eq!(nodes.keys().copied().collect::<Vec<_>>(), vec![kept]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn entering_a_node_while_its_network_glides_settles_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
gliding_nudged_node(&mut editor).await;
|
||||
let merge = editor.create_node_by_name_at(merge_definition(), 20, 0).await;
|
||||
|
||||
editor.enter_editable_network(merge).await;
|
||||
|
||||
assert!(editor.active_document().network_interface.glide_offsets(&[]).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resting_a_wire_on_an_exposed_input_reveals_nothing_that_would_move_it_from_under_the_pointer() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
+47
-70
@@ -1,56 +1,20 @@
|
||||
//! The shapes the node graph frontend is sent: one entry per visible port, carrying its type, its
|
||||
//! name and whether it's connected. Read-only projections of the graph, rather than a source of truth.
|
||||
//! The connectors the graph UI's rows and tooltips are built from: one entry per visible port, carrying its type,
|
||||
//! its name and whether it's connected. Read-only projections of the graph, rather than a source of truth.
|
||||
|
||||
use super::resolved_types::TypeSource;
|
||||
use super::*;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
pub fn frontend_imports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> {
|
||||
match network_path.split_last() {
|
||||
Some((node_id, encapsulating_network_path)) => {
|
||||
let Some(node) = self.document_node(node_id, encapsulating_network_path) else {
|
||||
log::error!("Could not get node {node_id} in network {encapsulating_network_path:?}");
|
||||
return Vec::new();
|
||||
};
|
||||
let mut frontend_imports = (0..node.inputs.len())
|
||||
.map(|import_index| self.frontend_output_from_connector(&OutputConnector::Import(import_index), network_path))
|
||||
.collect::<Vec<_>>();
|
||||
if frontend_imports.is_empty() {
|
||||
frontend_imports.push(None);
|
||||
}
|
||||
frontend_imports
|
||||
}
|
||||
// In the document network display no imports
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn frontend_exports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphInput>> {
|
||||
let Some(network) = self.nested_network(network_path) else { return Vec::new() };
|
||||
let mut frontend_exports = ((0..network.exports.len()).map(|export_index| self.frontend_input_from_connector(&InputConnector::Export(export_index), network_path))).collect::<Vec<_>>();
|
||||
if frontend_exports.is_empty() {
|
||||
frontend_exports.push(None);
|
||||
}
|
||||
frontend_exports
|
||||
}
|
||||
|
||||
/// Returns None if there is an error, it is a hidden primary export, or a hidden input
|
||||
pub fn frontend_input_from_connector(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<FrontendGraphInput> {
|
||||
// Return None if it is a hidden input
|
||||
if self.input_from_connector(input_connector, network_path).is_some_and(|input| !input.is_exposed()) {
|
||||
return None;
|
||||
}
|
||||
let input_type = self.input_type(input_connector, network_path);
|
||||
let data_type = input_type.displayed_type();
|
||||
let resolved_type = input_type.resolved_type_node_string();
|
||||
|
||||
let connected = self.upstream_output_connector(input_connector, network_path).is_some();
|
||||
|
||||
let (name, description) = match input_connector {
|
||||
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path),
|
||||
InputConnector::Export(export_index) => (self.displayed_export_name(*export_index, network_path), self.export_description(*export_index, network_path)),
|
||||
/// Returns None if there is an error, it is a hidden primary export, or a hidden or missing input
|
||||
pub fn input_tooltip(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<InputTooltip> {
|
||||
let (name, input_type, connected) = self.graph_ui_input(input_connector, network_path)?;
|
||||
let description = match input_connector {
|
||||
InputConnector::Node { node_id, input_index } => self
|
||||
.persistent_input_metadata(node_id, *input_index, network_path)
|
||||
.map(|metadata| metadata.input_description.clone())
|
||||
.unwrap_or_default(),
|
||||
InputConnector::Export(export_index) => self.export_description(*export_index, network_path),
|
||||
};
|
||||
|
||||
let valid_types = match input_connector {
|
||||
InputConnector::Node { .. } => self.potential_valid_input_types(input_connector, network_path),
|
||||
// An export takes any type itself, so it's limited only by what its subgraph node's output feeds, or at the document's root, what can be rendered
|
||||
@@ -60,22 +24,47 @@ impl NodeNetworkInterface {
|
||||
.filter(|valid_type| !valid_type.nested_type().is_generic())
|
||||
.collect(),
|
||||
};
|
||||
let valid_types = distinct_type_names(&valid_types);
|
||||
|
||||
Some(FrontendGraphInput {
|
||||
data_type,
|
||||
resolved_type,
|
||||
Some(InputTooltip {
|
||||
resolved_type: input_type.resolved_type_node_string(),
|
||||
name,
|
||||
description,
|
||||
valid_types,
|
||||
valid_types: distinct_type_names(&valid_types),
|
||||
connected,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns None if there is an error, it is the document network, a hidden primary output or import
|
||||
pub fn frontend_output_from_connector(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<FrontendGraphOutput> {
|
||||
pub fn output_tooltip(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<OutputTooltip> {
|
||||
let (name, output_type, connected) = self.graph_ui_output(output_connector, network_path)?;
|
||||
let description = match output_connector {
|
||||
OutputConnector::Node { node_id, output_index } => self.output_description(node_id, *output_index, network_path),
|
||||
OutputConnector::Import(import_index) => self.import_description(*import_index, network_path),
|
||||
};
|
||||
Some(OutputTooltip {
|
||||
resolved_type: output_type.resolved_type_node_string(),
|
||||
name,
|
||||
description,
|
||||
possible_types: distinct_type_names(&self.possible_output_types(output_connector, network_path)),
|
||||
connected,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn graph_ui_input(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<(String, TypeSource, bool)> {
|
||||
// Return None if it is a hidden or missing input
|
||||
if !self.input_from_connector(input_connector, network_path).is_some_and(|input| input.is_exposed()) {
|
||||
return None;
|
||||
}
|
||||
let name = match input_connector {
|
||||
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path).0,
|
||||
InputConnector::Export(export_index) => self.displayed_export_name(*export_index, network_path),
|
||||
};
|
||||
let connected = self.upstream_output_connector(input_connector, network_path).is_some();
|
||||
Some((name, self.input_type(input_connector, network_path), connected))
|
||||
}
|
||||
|
||||
pub fn graph_ui_output(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<(String, TypeSource, bool)> {
|
||||
let output_type = self.output_type(output_connector, network_path);
|
||||
let (name, description) = match output_connector {
|
||||
let name = match output_connector {
|
||||
OutputConnector::Node { node_id, output_index } => {
|
||||
// Do not display the primary output port for a node if it is a network node with a hidden primary export
|
||||
if *output_index == 0 && self.hidden_primary_output(node_id, network_path) {
|
||||
@@ -85,8 +74,7 @@ impl NodeNetworkInterface {
|
||||
let output_names = self.view(network_path).ok()?.output_names(node_id).ok()?;
|
||||
let output_name = output_names.get(*output_index).cloned().unwrap_or_default();
|
||||
|
||||
let output_name = if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() };
|
||||
(output_name, self.output_description(node_id, *output_index, network_path))
|
||||
if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() }
|
||||
}
|
||||
OutputConnector::Import(import_index) => {
|
||||
// Return None if it is an import in the document network
|
||||
@@ -98,24 +86,13 @@ impl NodeNetworkInterface {
|
||||
return None;
|
||||
};
|
||||
|
||||
(self.displayed_import_name(*import_index, network_path), self.import_description(*import_index, network_path))
|
||||
self.displayed_import_name(*import_index, network_path)
|
||||
}
|
||||
};
|
||||
let data_type = output_type.displayed_type();
|
||||
let resolved_type = output_type.resolved_type_node_string();
|
||||
let possible_types = distinct_type_names(&self.possible_output_types(output_connector, network_path));
|
||||
let connected = self
|
||||
.with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).is_some_and(|inputs| !inputs.is_empty()))
|
||||
.unwrap_or_default();
|
||||
|
||||
Some(FrontendGraphOutput {
|
||||
data_type,
|
||||
resolved_type,
|
||||
name,
|
||||
description,
|
||||
possible_types,
|
||||
connected,
|
||||
})
|
||||
Some((name, output_type, connected))
|
||||
}
|
||||
|
||||
/// Returns the input name to display in the Inspector. If the input has no name then its type is used.
|
||||
+14
-71
@@ -4,56 +4,13 @@
|
||||
//! the caller decides whether to cache the result.
|
||||
|
||||
use super::*;
|
||||
use graph_ui::label_width;
|
||||
use graph_ui::metrics::{LAYER_GRIP_WIDTH, LAYER_NAME_LEFT};
|
||||
use graph_ui::network_connector::{NetworkConnectorKind, network_connector_name_box, network_connector_row_offset};
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
pub(super) fn node_input_anchor(&self, node_id: &NodeId, input_index: usize, network_path: &[NodeId]) -> Option<DVec2> {
|
||||
let top_left = self.position(node_id, network_path)?.as_dvec2() * GRID_SIZE as f64;
|
||||
let grid = GRID_SIZE as f64;
|
||||
let inputs = &self.document_node(node_id, network_path)?.inputs;
|
||||
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
return (input_index == 0).then_some(top_left + DVec2::new(0., grid));
|
||||
}
|
||||
|
||||
if self.is_layer(node_id, network_path) {
|
||||
return match input_index {
|
||||
0 => Some(top_left + DVec2::new(2. * grid, 2. * grid + 8.)),
|
||||
1 if inputs.iter().filter(|input| input.is_exposed()).count() > 1 => Some(top_left + DVec2::new(0., grid)),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
|
||||
if !inputs.get(input_index)?.is_exposed() {
|
||||
return None;
|
||||
}
|
||||
let row = inputs.iter().take(input_index).enumerate().filter(|(index, input)| *index == 0 || input.is_exposed()).count();
|
||||
Some(top_left + DVec2::new(0., grid * (row as f64 + 1.)))
|
||||
}
|
||||
|
||||
pub(super) fn node_output_anchor(&self, node_id: &NodeId, output_index: usize, network_path: &[NodeId]) -> Option<DVec2> {
|
||||
let top_left = self.position(node_id, network_path)?.as_dvec2() * GRID_SIZE as f64;
|
||||
let grid = GRID_SIZE as f64;
|
||||
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
return (output_index == 0).then_some(top_left + DVec2::new(0., grid));
|
||||
}
|
||||
|
||||
if self.is_layer(node_id, network_path) {
|
||||
return (output_index == 0).then_some(top_left + DVec2::new(2. * grid, -8.));
|
||||
}
|
||||
|
||||
let hidden = output_index == 0 && self.hidden_primary_output(node_id, network_path);
|
||||
(!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.)))
|
||||
}
|
||||
|
||||
/// 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])> {
|
||||
// How far past the port's center the name begins
|
||||
const IMPORT_NAME_INSET: f64 = 8.;
|
||||
const EXPORT_NAME_INSET: f64 = 9.;
|
||||
const FONT_SIZE: f64 = 14.;
|
||||
|
||||
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(NetworkConnectorKey, [DVec2; 2])> {
|
||||
if network_path.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -72,16 +29,13 @@ impl NodeNetworkInterface {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let half_row = DVec2::new(0., HALF_GRID_SIZE as f64);
|
||||
let imports = import_centers.into_iter().map(|(import_index, center)| {
|
||||
let name_width = text_width(&self.displayed_import_name(import_index, network_path), FONT_SIZE);
|
||||
let name_right = center - DVec2::new(IMPORT_NAME_INSET, 0.);
|
||||
(ImportOrExport::Import(import_index), [name_right - DVec2::new(name_width, 0.) - half_row, name_right + half_row])
|
||||
let name_width = label_width(&self.displayed_import_name(import_index, network_path));
|
||||
(NetworkConnectorKey::Import(import_index), network_connector_name_box(NetworkConnectorKind::Import, center, name_width))
|
||||
});
|
||||
let exports = export_centers.into_iter().map(|(export_index, center)| {
|
||||
let name_width = text_width(&self.displayed_export_name(export_index, network_path), FONT_SIZE);
|
||||
let name_left = center + DVec2::new(EXPORT_NAME_INSET, 0.);
|
||||
(ImportOrExport::Export(export_index), [name_left - half_row, name_left + DVec2::new(name_width, 0.) + half_row])
|
||||
let name_width = label_width(&self.displayed_export_name(export_index, network_path));
|
||||
(NetworkConnectorKey::Export(export_index), network_connector_name_box(NetworkConnectorKind::Export, center, name_width))
|
||||
});
|
||||
imports.chain(exports).collect()
|
||||
}
|
||||
@@ -98,13 +52,13 @@ impl NodeNetworkInterface {
|
||||
if !network_path.is_empty() {
|
||||
let import_start_index = if self.hidden_primary_import(network_path) { 1 } else { 0 };
|
||||
for import_index in import_start_index..self.number_of_imports(network_path) {
|
||||
import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., import_export_row_offset(import_index)));
|
||||
import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., network_connector_row_offset(import_index)));
|
||||
}
|
||||
}
|
||||
|
||||
let export_start_index = if self.hidden_primary_export(network_path) { 1 } else { 0 };
|
||||
for export_index in export_start_index..network.exports.len() {
|
||||
import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., import_export_row_offset(export_index)));
|
||||
import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., network_connector_row_offset(export_index)));
|
||||
}
|
||||
|
||||
Some(import_export_ports)
|
||||
@@ -133,7 +87,7 @@ impl NodeNetworkInterface {
|
||||
connectors.push((0, first_row_center));
|
||||
}
|
||||
let next_index = count.max(1);
|
||||
connectors.push((next_index, first_row_center + DVec2::new(0., import_export_row_offset(next_index) + GRID_SIZE as f64)));
|
||||
connectors.push((next_index, first_row_center + DVec2::new(0., network_connector_row_offset(next_index) + GRID_SIZE as f64)));
|
||||
connectors
|
||||
}
|
||||
|
||||
@@ -149,26 +103,21 @@ impl NodeNetworkInterface {
|
||||
if y < first_row_center + GRID_SIZE as f64 {
|
||||
return Some(0);
|
||||
}
|
||||
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
|
||||
Some((1..row_count).find(|&row| first_row_center + network_connector_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
|
||||
/// because measuring the name's text is slow.
|
||||
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
|
||||
const GAP_WIDTH: f64 = 8.;
|
||||
const FONT_SIZE: f64 = 14.;
|
||||
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
|
||||
let thumbnail_width = 3. * GRID_SIZE as f64;
|
||||
let layer_text = self.display_name(node_id, network_path);
|
||||
|
||||
let text_width = text_width(&layer_text, FONT_SIZE);
|
||||
let text_width = label_width(&layer_text);
|
||||
|
||||
let grip_padding = 4.;
|
||||
let grip_width = 8.;
|
||||
let lock_icon_width = if self.is_locked(node_id, network_path) { GRID_SIZE as f64 } else { 0. };
|
||||
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;
|
||||
let layer_width_pixels = LAYER_NAME_LEFT + text_width + grip_padding + LAYER_GRIP_WIDTH + lock_icon_width + icon_overhang_width;
|
||||
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
|
||||
}
|
||||
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
|
||||
@@ -258,9 +207,3 @@ impl NodeNetworkInterface {
|
||||
Some((rounded_import_top_left.as_ivec2(), rounded_export_top_right.as_ivec2()))
|
||||
}
|
||||
}
|
||||
|
||||
/// How far below the first import or export the one at `index` sits, with a grid cell of space separating the primary from the secondary ones.
|
||||
fn import_export_row_offset(index: usize) -> f64 {
|
||||
let rows = if index == 0 { 0 } else { index + 1 };
|
||||
(rows * GRID_SIZE as usize) as f64
|
||||
}
|
||||
+39
-91
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use graph_ui::geometry::WireEnd;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use kurbo::{DEFAULT_ACCURACY, ParamCurveNearest};
|
||||
|
||||
@@ -51,13 +52,10 @@ impl NodeNetworkInterface {
|
||||
/// 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| {
|
||||
layout.find_part(node_id, |geometry, 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::Input(place) => Part::Input(geometry.input_at(place)? as u32),
|
||||
part => part,
|
||||
};
|
||||
find(part, target)
|
||||
@@ -74,13 +72,11 @@ 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))))
|
||||
.filter(|node_id| layout.geometry(node_id).is_some_and(|geometry| geometry.body().contains(point)))
|
||||
.collect::<Vec<_>>()
|
||||
})?;
|
||||
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
|
||||
@@ -103,7 +99,6 @@ 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,
|
||||
@@ -113,7 +108,6 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
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()
|
||||
})
|
||||
@@ -121,28 +115,18 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// 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.
|
||||
pub fn empty_import_export_connector_at(&self, point: DVec2, is_import: bool, network_path: &[NodeId]) -> Option<(usize, DVec2)> {
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
let point = point - if is_import { glide_offsets.imports } else { glide_offsets.exports };
|
||||
|
||||
// The same reach as an import (output) or export (input) port's click target
|
||||
self.empty_import_export_connectors(is_import, network_path)
|
||||
.into_iter()
|
||||
.find(|(_, center)| port_click_target(side_port_bounds(*center, !is_import)).intersect_point_no_stroke(point))
|
||||
self.empty_import_export_connectors(is_import, network_path).into_iter().find(|(index, center)| match is_import {
|
||||
true => PartTarget::output_port(*center, *index as u32).contains(point),
|
||||
false => PartTarget::input_port(*center, *index as u32).contains(point),
|
||||
})
|
||||
}
|
||||
|
||||
/// The import or export with its name under `point`, given in node graph space.
|
||||
pub fn import_export_name_from_point(&self, point: DVec2, network_path: &[NodeId]) -> Option<ImportOrExport> {
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
pub fn import_export_name_from_point(&self, point: DVec2, network_path: &[NodeId]) -> Option<NetworkConnectorKey> {
|
||||
self.import_export_name_bounds(network_path)
|
||||
.into_iter()
|
||||
.find(|(import_or_export, [name_min, name_max])| {
|
||||
let point = point
|
||||
- match import_or_export {
|
||||
ImportOrExport::Import(_) => glide_offsets.imports,
|
||||
ImportOrExport::Export(_) => glide_offsets.exports,
|
||||
};
|
||||
name_min.cmple(point).all() && point.cmple(*name_max).all()
|
||||
})
|
||||
.find(|(_, [name_min, name_max])| name_min.cmple(point).all() && point.cmple(*name_max).all())
|
||||
.map(|(import_or_export, _)| import_or_export)
|
||||
}
|
||||
|
||||
@@ -170,14 +154,13 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// The input fed by a wire passing within `tolerance` of the point (in node graph space), for placing a dot on it. Only wires a dot can bend are found.
|
||||
pub fn wire_input_from_point(&self, point: DVec2, tolerance: f64, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<InputConnector> {
|
||||
pub fn wire_input_from_point(&self, point: DVec2, tolerance: f64, wire_style: WireStyle, network_path: &[NodeId]) -> Option<InputConnector> {
|
||||
let target = dvec2_to_point(point);
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
self.node_graph_input_connectors(network_path)
|
||||
.into_iter()
|
||||
.filter(|input| self.can_bend_wire_into(input, network_path))
|
||||
.filter_map(|input| {
|
||||
let (wire, _, _) = self.gliding_vector_wire_from_input(&input, wire_style, &glide_offsets, network_path)?;
|
||||
let (wire, _) = self.vector_wire_from_input(&input, wire_style, network_path)?;
|
||||
let distance = wire
|
||||
.segments()
|
||||
.map(|segment| segment.nearest(target, DEFAULT_ACCURACY).distance_sq.sqrt())
|
||||
@@ -196,13 +179,11 @@ 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 covering_dot = self.redirect_dot_from_click(click, network_path);
|
||||
self.nodes_reaching(point, network_path)
|
||||
.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,
|
||||
@@ -210,11 +191,9 @@ impl NodeNetworkInterface {
|
||||
})
|
||||
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
||||
.or_else(|| {
|
||||
self.with_import_export_ports(network_path, |import_export_ports| {
|
||||
import_export_ports.clicked_input_port_from_point(point - glide_offsets.exports).map(InputConnector::Export)
|
||||
})
|
||||
.flatten()
|
||||
.filter(|_| covering_dot.is_none())
|
||||
self.with_import_export_ports(network_path, |import_export_ports| import_export_ports.clicked_input_port_from_point(point).map(InputConnector::Export))
|
||||
.flatten()
|
||||
.filter(|_| covering_dot.is_none())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -226,14 +205,12 @@ 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);
|
||||
// A redirect dot is drawn above everything else, so where it covers other ports, only its own can be pressed
|
||||
let covering_dot = self.redirect_dot_from_click(click, network_path);
|
||||
self.nodes_reaching(point, network_path)
|
||||
.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,
|
||||
@@ -242,7 +219,7 @@ impl NodeNetworkInterface {
|
||||
.next()
|
||||
.or_else(|| {
|
||||
self.with_import_export_ports(network_path, |import_export_ports| {
|
||||
import_export_ports.clicked_output_port_from_point(point - glide_offsets.imports).map(OutputConnector::Import)
|
||||
import_export_ports.clicked_output_port_from_point(point).map(OutputConnector::Import)
|
||||
})
|
||||
.flatten()
|
||||
.filter(|_| covering_dot.is_none())
|
||||
@@ -250,20 +227,30 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
pub fn input_position(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<DVec2> {
|
||||
match input_connector {
|
||||
InputConnector::Node { node_id, input_index } => self.node_input_anchor(node_id, *input_index, network_path),
|
||||
InputConnector::Export(export_index) => self
|
||||
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.input_port_position(*export_index))
|
||||
.flatten(),
|
||||
}
|
||||
Some(self.input_end(input_connector, network_path)?.position)
|
||||
}
|
||||
|
||||
pub fn output_position(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<DVec2> {
|
||||
Some(self.output_end(output_connector, network_path)?.position)
|
||||
}
|
||||
|
||||
pub fn input_end(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<WireEnd> {
|
||||
match input_connector {
|
||||
InputConnector::Node { node_id, input_index } => self.with_layout(network_path, |layout| layout.geometry(node_id)?.input_end(*input_index)).flatten(),
|
||||
InputConnector::Export(export_index) => self
|
||||
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.input_port_position(*export_index))
|
||||
.flatten()
|
||||
.map(|position| WireEnd { position, vertical: false }),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn output_end(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<WireEnd> {
|
||||
match output_connector {
|
||||
OutputConnector::Node { node_id, output_index } => self.node_output_anchor(node_id, *output_index, network_path),
|
||||
OutputConnector::Node { node_id, output_index } => self.with_layout(network_path, |layout| layout.geometry(node_id)?.output_end(*output_index)).flatten(),
|
||||
OutputConnector::Import(import_index) => self
|
||||
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.output_port_position(*import_index))
|
||||
.flatten(),
|
||||
.flatten()
|
||||
.map(|position| WireEnd { position, vertical: false }),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,49 +310,10 @@ impl NodeNetworkInterface {
|
||||
Some((node_graph_to_viewport * Quad::from_box(bounds)).bounding_box())
|
||||
}
|
||||
|
||||
pub fn collect_layer_widths(&self, network_path: &[NodeId]) -> (HashMap<NodeId, u32>, HashMap<NodeId, u32>, HashMap<NodeId, bool>) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in collect_layer_widths");
|
||||
return (HashMap::new(), HashMap::new(), HashMap::new());
|
||||
};
|
||||
let nodes = network_metadata
|
||||
.persistent_metadata
|
||||
.node_metadata
|
||||
.keys()
|
||||
.filter_map(|node_id| if self.is_layer(node_id, network_path) { Some(*node_id) } else { None })
|
||||
.collect::<Vec<_>>();
|
||||
let layer_widths = nodes
|
||||
.iter()
|
||||
.filter_map(|node_id| self.layer_width(node_id, network_path).map(|layer_width| (*node_id, layer_width)))
|
||||
.collect::<HashMap<NodeId, u32>>();
|
||||
let chain_widths = nodes.iter().map(|node_id| (*node_id, self.chain_width(node_id, network_path))).collect::<HashMap<NodeId, u32>>();
|
||||
let has_left_input_wire = nodes
|
||||
.iter()
|
||||
.map(|node_id| {
|
||||
(
|
||||
*node_id,
|
||||
!self
|
||||
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.all(|node_id| self.is_chain(&node_id, network_path)),
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<NodeId, bool>>();
|
||||
|
||||
(layer_widths, chain_widths, has_left_input_wire)
|
||||
pub fn has_left_input_wire(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
!self
|
||||
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow)
|
||||
.skip(1)
|
||||
.all(|node_id| self.is_chain(&node_id, network_path))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
+27
-31
@@ -1,7 +1,8 @@
|
||||
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
|
||||
use super::*;
|
||||
use glam::UVec2;
|
||||
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
|
||||
use graph_ui::geometry::{NodeGeometry, NodeShape};
|
||||
use graph_ui::metrics::CARD_GRID_WIDTH;
|
||||
use std::cell::RefCell;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
@@ -90,11 +91,6 @@ impl NetworkLayout {
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// How many nodes the layer's chain holds.
|
||||
pub fn chain_length(&self, layer: &NodeId) -> u32 {
|
||||
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
|
||||
@@ -105,18 +101,17 @@ impl NetworkLayout {
|
||||
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())
|
||||
pub fn geometry(&self, node_id: &NodeId) -> Option<NodeGeometry> {
|
||||
Some(self.geometry_at(*self.indices.get(node_id)?))
|
||||
}
|
||||
|
||||
/// 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)?);
|
||||
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&NodeGeometry, &PartTarget) -> Option<R>) -> Option<R> {
|
||||
let geometry = self.geometry(node_id)?;
|
||||
let mut found = None;
|
||||
placed.parts(|target| {
|
||||
geometry.parts(|target| {
|
||||
if found.is_none() {
|
||||
found = find(&target);
|
||||
found = find(&geometry, &target);
|
||||
}
|
||||
});
|
||||
found
|
||||
@@ -131,13 +126,13 @@ 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,
|
||||
fn geometry_at(&self, index: NodeIndex) -> NodeGeometry {
|
||||
let node = self.layout.node(index);
|
||||
NodeGeometry {
|
||||
cell: node.position,
|
||||
kind: self.graph[index].kind,
|
||||
chain_length: node.chain_length,
|
||||
shape: self.shapes[index.index()].clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,7 +143,7 @@ impl NetworkLayout {
|
||||
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();
|
||||
let body = self.geometry_at(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 {
|
||||
@@ -220,11 +215,8 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
pub(crate) fn nodes_reaching(&self, point: DVec2, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
self.with_layout(network_path, |layout| {
|
||||
layout.node_ids.iter().filter(|node_id| layout.reaches(node_id, point - glide_offsets.node(node_id))).copied().collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
self.with_layout(network_path, |layout| layout.node_ids.iter().filter(|node_id| layout.reaches(node_id, point)).copied().collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn drag_preview(&self, network_path: &[NodeId]) -> (IVec2, bool) {
|
||||
@@ -260,6 +252,10 @@ impl NodeNetworkInterface {
|
||||
transient.layout.unload();
|
||||
}
|
||||
|
||||
pub(crate) fn dragging(&self, network_path: &[NodeId]) -> bool {
|
||||
self.network_metadata(network_path).is_some_and(|network_metadata| network_metadata.transient_metadata.drag.is_some())
|
||||
}
|
||||
|
||||
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
|
||||
pub fn shift_selected_nodes(&mut self, offset: IVec2, keep_upstream: bool, network_path: &[NodeId]) {
|
||||
self.cancel_drag(network_path);
|
||||
@@ -420,11 +416,12 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
let (kind, size) = match (is_layer, is_redirect_dot) {
|
||||
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, 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))),
|
||||
(false, true) => (NodeKind::Waypoint, UVec2::new(CARD_GRID_WIDTH, self.node_height(node_id, network_path))),
|
||||
(false, false) => (NodeKind::Node, UVec2::new(CARD_GRID_WIDTH, self.node_height(node_id, network_path))),
|
||||
};
|
||||
|
||||
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
|
||||
let inputs = &self.document_node(node_id, network_path)?.inputs;
|
||||
let node = Node {
|
||||
placement,
|
||||
kind,
|
||||
@@ -433,9 +430,9 @@ impl NodeNetworkInterface {
|
||||
held: false,
|
||||
};
|
||||
let shape = NodeShape {
|
||||
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
|
||||
size,
|
||||
exposed_inputs: inputs.iter().enumerate().filter(|(_, input)| input.is_exposed()).map(|(index, _)| index).collect(),
|
||||
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),
|
||||
@@ -444,7 +441,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
|
||||
@@ -827,10 +827,10 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Wires the output into the inputs through one new redirect dot placed midway between them, which fans out to the inputs.
|
||||
fn create_wires_through_dot(&mut self, output_connector: &OutputConnector, input_connectors: &[InputConnector], network_path: &[NodeId]) {
|
||||
let output_center = self.get_output_center(output_connector, network_path);
|
||||
let output_center = self.output_position(output_connector, network_path);
|
||||
let input_centers = input_connectors
|
||||
.iter()
|
||||
.map(|input_connector| self.get_input_center(input_connector, network_path))
|
||||
.map(|input_connector| self.input_position(input_connector, network_path))
|
||||
.collect::<Option<Vec<_>>>();
|
||||
let center = match output_center.zip(input_centers) {
|
||||
Some((output_center, input_centers)) => {
|
||||
@@ -1164,7 +1164,7 @@ impl NodeNetworkInterface {
|
||||
self.invalidate_node_appearance(node_id, network_path);
|
||||
}
|
||||
|
||||
pub fn set_import_export_name(&mut self, name: String, index: ImportOrExport, network_path: &[NodeId]) {
|
||||
pub fn set_import_export_name(&mut self, name: String, index: NetworkConnectorKey, network_path: &[NodeId]) {
|
||||
let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else {
|
||||
log::error!("Could not get encapsulating network in set_import_export_name");
|
||||
return;
|
||||
@@ -1176,8 +1176,8 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
let name_changed = match index {
|
||||
ImportOrExport::Import(import_index) => node.set_input_name(import_index, name),
|
||||
ImportOrExport::Export(export_index) => node.set_output_name(export_index, name),
|
||||
NetworkConnectorKey::Import(import_index) => node.set_input_name(import_index, name),
|
||||
NetworkConnectorKey::Export(export_index) => node.set_output_name(export_index, name),
|
||||
};
|
||||
|
||||
if name_changed {
|
||||
@@ -1185,7 +1185,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_import_export_description(&mut self, description: String, index: ImportOrExport, network_path: &[NodeId]) {
|
||||
pub fn set_import_export_description(&mut self, description: String, index: NetworkConnectorKey, network_path: &[NodeId]) {
|
||||
let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else {
|
||||
log::error!("Could not get encapsulating network in set_import_export_description");
|
||||
return;
|
||||
@@ -1197,8 +1197,8 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
let description_changed = match index {
|
||||
ImportOrExport::Import(import_index) => node.set_input_description(import_index, description),
|
||||
ImportOrExport::Export(export_index) => node.set_output_description(export_index, description),
|
||||
NetworkConnectorKey::Import(import_index) => node.set_input_description(import_index, description),
|
||||
NetworkConnectorKey::Export(export_index) => node.set_output_description(export_index, description),
|
||||
};
|
||||
|
||||
if description_changed {
|
||||
|
||||
@@ -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. }
|
||||
}
|
||||
}
|
||||
@@ -264,16 +264,6 @@ impl NodeNetworkInterface {
|
||||
layers
|
||||
}
|
||||
|
||||
/// The width in grid cells of a layer's chain area: one cell plus a chain width per chained node, or zero for a layer without a displayed chain input.
|
||||
pub fn chain_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
|
||||
if self.number_of_displayed_inputs(node_id, network_path) <= 1 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let chain_length = self.with_layout(network_path, |layout| layout.chain_length(node_id)).unwrap_or_default();
|
||||
chain_length * NODE_CHAIN_WIDTH as u32 + 1
|
||||
}
|
||||
|
||||
/// Check if the specified node id is connected to the output
|
||||
pub fn connected_to_output(&self, target_node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
self.query(network_path, "connected_to_output", |view| Ok(view.connected_to_output(target_node_id))).unwrap_or_default()
|
||||
|
||||
@@ -116,12 +116,7 @@ impl Iterator for FlowIter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ImportOrExport {
|
||||
Import(usize),
|
||||
Export(usize),
|
||||
}
|
||||
pub use graph_ui::network_connector::NetworkConnectorKey;
|
||||
|
||||
/// The primary input (index 0) of any node: a chain node's horizontal wire continuing from the left, or a layer's vertical stack wire from the sibling rendered below it.
|
||||
pub const PRIMARY_INPUT_INDEX: usize = 0;
|
||||
@@ -265,29 +260,10 @@ pub(crate) enum DotSide {
|
||||
Outgoing,
|
||||
}
|
||||
|
||||
/// The corners of the click target for a connector on a node or layer's left or right side, or an import or export.
|
||||
/// It fills its row's height and reaches further away from the node than into it, leaving the node body grabbable.
|
||||
pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
|
||||
const INWARD_REACH: f64 = 8.;
|
||||
const OUTWARD_REACH: f64 = 12.;
|
||||
const HALF_HEIGHT: f64 = 12.;
|
||||
|
||||
// Inputs face left and outputs face right
|
||||
let (left_reach, right_reach) = if is_input { (OUTWARD_REACH, INWARD_REACH) } else { (INWARD_REACH, OUTWARD_REACH) };
|
||||
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
|
||||
}
|
||||
|
||||
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
|
||||
const CORNER_RADIUS: f64 = 4.;
|
||||
|
||||
let path = rounded_rectangle_path(corner1, corner2, [CORNER_RADIUS; 4]);
|
||||
ClickTarget::new_with_path(path, 0.)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Ports {
|
||||
pub(crate) input_ports: Vec<(usize, ClickTarget)>,
|
||||
pub(crate) output_ports: Vec<(usize, ClickTarget)>,
|
||||
pub(crate) input_ports: Vec<(usize, PartTarget)>,
|
||||
pub(crate) output_ports: Vec<(usize, PartTarget)>,
|
||||
/// Where a wire attaches to an input port with a click target not centered on that point.
|
||||
pub(crate) input_anchors: Vec<(usize, DVec2)>,
|
||||
/// Where a wire attaches to an output port with a click target not centered on that point.
|
||||
@@ -310,30 +286,30 @@ impl Ports {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
|
||||
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, PartTarget)> {
|
||||
self.input_ports.iter()
|
||||
}
|
||||
|
||||
pub fn output_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
|
||||
pub fn output_ports(&self) -> impl Iterator<Item = &(usize, PartTarget)> {
|
||||
self.output_ports.iter()
|
||||
}
|
||||
|
||||
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.input_ports.push((input_index, PartTarget::input_port(center, input_index as u32)));
|
||||
self.input_anchors.push((input_index, center));
|
||||
}
|
||||
|
||||
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.output_ports.push((output_index, PartTarget::output_port(center, output_index as u32)));
|
||||
self.output_anchors.push((output_index, 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))
|
||||
self.input_ports.iter().find_map(|(port, target)| target.contains(point).then_some(*port))
|
||||
}
|
||||
|
||||
pub fn clicked_output_port_from_point(&self, point: DVec2) -> Option<usize> {
|
||||
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||
self.output_ports.iter().find_map(|(port, target)| target.contains(point).then_some(*port))
|
||||
}
|
||||
|
||||
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
|
||||
@@ -663,57 +639,6 @@ pub struct NodeNetworkTransientMetadata {
|
||||
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)>,
|
||||
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
/// How far the nodes, imports, and exports gliding into the grid cells they just moved to are drawn from those cells, in node graph space.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct GlideOffsets {
|
||||
pub nodes: HashMap<NodeId, DVec2>,
|
||||
pub imports: DVec2,
|
||||
pub exports: DVec2,
|
||||
}
|
||||
|
||||
impl GlideOffsets {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty() && self.imports == DVec2::ZERO && self.exports == DVec2::ZERO
|
||||
}
|
||||
|
||||
pub fn node(&self, node_id: &NodeId) -> DVec2 {
|
||||
self.nodes.get(node_id).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn input(&self, input: &InputConnector) -> DVec2 {
|
||||
match input {
|
||||
InputConnector::Node { node_id, .. } => self.node(node_id),
|
||||
InputConnector::Export(_) => self.exports,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn output(&self, output: &OutputConnector) -> DVec2 {
|
||||
match output {
|
||||
OutputConnector::Node { node_id, .. } => self.node(node_id),
|
||||
OutputConnector::Import(_) => self.imports,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shrinks every offset to the given fraction of itself, settling those left too small to see.
|
||||
pub fn shrink(&mut self, remaining_fraction: f64) {
|
||||
const SMALLEST_VISIBLE_OFFSET: f64 = 0.5;
|
||||
|
||||
let shrink = |offset: &mut DVec2| {
|
||||
*offset *= remaining_fraction;
|
||||
if offset.length() < SMALLEST_VISIBLE_OFFSET {
|
||||
*offset = DVec2::ZERO;
|
||||
}
|
||||
};
|
||||
self.nodes.values_mut().for_each(shrink);
|
||||
self.nodes.retain(|_, offset| *offset != DVec2::ZERO);
|
||||
shrink(&mut self.imports);
|
||||
shrink(&mut self.exports);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the imports and exports keep their distance from horizontally, in node graph space. They keep a few grid cells from the sides of a node,
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
|
||||
@@ -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;
|
||||
@@ -121,10 +121,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_std::raster::SampleImageNode",
|
||||
"graphene_std::raster::SampleNode",
|
||||
"raster_nodes::std_nodes::SampleImageNode",
|
||||
// The deleted Extend Image to Bounds passes its image through, since the transparent pixels it padded with drew nothing
|
||||
"graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
||||
"graphene_std::raster::ExtendImageToBoundsNode",
|
||||
"raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -185,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 +297,14 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::floor::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::FloorNode", "graphene_core::ops::FloorNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
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"],
|
||||
@@ -545,13 +553,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::channels::into_channels::IDENTIFIER,
|
||||
aliases: &["raster_nodes::adjustments::ImageToChannelsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::channels::from_channels::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
aliases: &[
|
||||
"raster_nodes::std_nodes::ChannelsToImageNode",
|
||||
"raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_std::raster::CombineChannelsNode",
|
||||
@@ -569,6 +572,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ExposureNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode", "graphene_std::raster::ExtendImageToBoundsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||
@@ -1565,13 +1572,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `into_channels` proto nodes.
|
||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `image_to_channels` proto nodes.
|
||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||
let split_wrapper_replacements = [
|
||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::channels::into_channels::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||
];
|
||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
@@ -1617,7 +1624,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Into Channels" nodes.
|
||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Image to Channels" nodes.
|
||||
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
||||
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
||||
const EXTRACT_CHANNEL: [&str; 4] = [
|
||||
@@ -1636,7 +1643,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if EXTRACT_XY.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::raster_nodes::channels::into_channels::IDENTIFIER, "Extract Channel"))
|
||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -1682,52 +1689,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";
|
||||
@@ -1823,7 +1784,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
for (node_id, node, network_path) in &nodes {
|
||||
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
|
||||
}
|
||||
remove_footprint_value_nodes(document);
|
||||
create_layer_stacks(document);
|
||||
follow_segments_turned_on_load(document);
|
||||
|
||||
@@ -2182,100 +2142,6 @@ fn read_noise_through_gamma_correction(document: &mut DocumentMessageHandler, no
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Whether a node is a removed 'Footprint Value' node, under any identifier it had.
|
||||
fn is_footprint_value(node: &DocumentNode) -> bool {
|
||||
matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::FootprintValueNode"))
|
||||
}
|
||||
|
||||
/// Sets an upgraded Rasterize node's area transform and resolution from the footprint it took, stored or from a 'Footprint Value' node (even
|
||||
/// through reroutes) whose inputs it takes over. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph.
|
||||
fn set_rasterize_area_from_footprint(document: &mut DocumentMessageHandler, node_id: &NodeId, network_path: &[NodeId], footprint: &NodeInput) -> Option<()> {
|
||||
use graphene_std::math_nodes::multiply;
|
||||
|
||||
// A footprint's transform placed a unit square anchored at its corner, where the area's is centered on its origin
|
||||
let corner_to_center = DAffine2::from_translation(DVec2::splat(0.5));
|
||||
let (transform_connector, resolution_connector) = (InputConnector::node_at_index(*node_id, 1), InputConnector::node_at_index(*node_id, 2));
|
||||
|
||||
// Reroutes pass the footprint along unchanged, and a cycle of them leads nowhere else
|
||||
let mut footprint = footprint.clone();
|
||||
let mut visited = HashSet::new();
|
||||
while let NodeInput::Node { node_id: source, output_index: 0 } = footprint
|
||||
&& visited.insert(source)
|
||||
&& let Some(reroute) = document.network_interface.document_node(&source, network_path)
|
||||
&& matches!(&reroute.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER)
|
||||
&& let Some(content) = reroute.inputs.first()
|
||||
{
|
||||
footprint = content.clone();
|
||||
}
|
||||
|
||||
match &footprint {
|
||||
// A stored footprint loads as its transform's six numbers then its resolution's two
|
||||
NodeInput::Value { tagged_value, exposed } => {
|
||||
let TaggedValue::Numbers(numbers) = &**tagged_value else { return None };
|
||||
let &[x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y, width, height] = numbers.as_slice() else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let transform = DAffine2::from_cols_array(&[x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]) * corner_to_center;
|
||||
let resolution = DVec2::new(width, height);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&transform_connector, NodeInput::value(TaggedValue::DAffine2(transform), *exposed), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&resolution_connector, NodeInput::value(TaggedValue::DVec2(resolution), *exposed), network_path);
|
||||
}
|
||||
NodeInput::Node { node_id: source, output_index: 0 } if document.network_interface.document_node(source, network_path).is_some_and(is_footprint_value) => {
|
||||
let footprint_value = document.network_interface.document_node(source, network_path)?;
|
||||
let (transform, resolution) = (footprint_value.inputs.get(1)?.clone(), footprint_value.inputs.get(2)?.clone());
|
||||
document.network_interface.set_input(&resolution_connector, resolution, network_path);
|
||||
|
||||
match transform {
|
||||
NodeInput::Value { tagged_value, exposed } => {
|
||||
let &TaggedValue::DAffine2(transform) = &*tagged_value else { return None };
|
||||
let transform = NodeInput::value(TaggedValue::DAffine2(transform * corner_to_center), exposed);
|
||||
document.network_interface.set_input(&transform_connector, transform, network_path);
|
||||
}
|
||||
// A wired transform goes through a Multiply node moving its unit square's anchor to the center
|
||||
wire => {
|
||||
document.network_interface.set_input(&transform_connector, wire, network_path);
|
||||
|
||||
let multiply_id = NodeId::new();
|
||||
document
|
||||
.network_interface
|
||||
.insert_node(multiply_id, resolve_proto_node_type(multiply::IDENTIFIER)?.default_node_template(), network_path);
|
||||
let multiplicand = NodeInput::value(TaggedValue::DAffine2(corner_to_center), false);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(multiply_id, 1), multiplicand, network_path);
|
||||
document.network_interface.insert_node_before_input(&multiply_id, &transform_connector, network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
for connector in [transform_connector, resolution_connector] {
|
||||
let default = document.network_interface.input_from_connector(&connector, network_path)?.as_value()?.clone();
|
||||
document.network_interface.set_input(&connector, NodeInput::value(default, true), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Deletes every 'Footprint Value' node once the Rasterize nodes it fed have taken over its inputs, disconnecting whatever else it fed.
|
||||
fn remove_footprint_value_nodes(document: &mut DocumentMessageHandler) {
|
||||
let footprint_value_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter(|(_, node, _)| is_footprint_value(node))
|
||||
.map(|(node_id, _, path)| (*node_id, path))
|
||||
.collect();
|
||||
|
||||
for (node_id, network_path) in footprint_value_nodes {
|
||||
document.network_interface.delete_nodes(vec![node_id], false, &network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 };
|
||||
@@ -2628,18 +2494,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);
|
||||
|
||||
@@ -2783,11 +2637,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)?;
|
||||
|
||||
@@ -2810,36 +2661,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();
|
||||
@@ -3256,16 +3077,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 2;
|
||||
}
|
||||
|
||||
// Rasterize, like the wrapper network collapsed into it above, took a footprint where it now takes an area transform and a resolution
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::platform_application_io::rasterize::IDENTIFIER) && matches!(inputs_count, 2 | 3) {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), node.inputs[0].clone(), network_path);
|
||||
set_rasterize_area_from_footprint(document, node_id, network_path, &node.inputs[1]);
|
||||
inputs_count = 4;
|
||||
}
|
||||
|
||||
// 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();
|
||||
@@ -3353,17 +3164,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
}
|
||||
|
||||
// Sample Image and Extend Image to Bounds nodes, now passthroughs, drop their old titles and any inputs past the first, like Extend Image to Bounds's bounds
|
||||
// Sample Image nodes, now passthroughs, drop their old title
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) {
|
||||
reset_default_display_name(document, node_id, network_path, "Sample Image");
|
||||
reset_default_display_name(document, node_id, network_path, "Extend Image to Bounds");
|
||||
|
||||
if 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);
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize became As String, whose input converts a wired value to text, while a stored value keeps the JSON text Serialize made of it
|
||||
@@ -4313,20 +4116,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",
|
||||
@@ -4833,8 +4622,11 @@ mod tests {
|
||||
let node_id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await;
|
||||
let document = editor.active_document_mut();
|
||||
|
||||
// A footprint can't be written any more, so a placeholder value stands in for it until the document is serialized
|
||||
let placeholder = NodeInput::value(TaggedValue::String("footprint placeholder".into()), false);
|
||||
let footprint = Footprint {
|
||||
resolution: glam::UVec2::new(64, 32),
|
||||
..Default::default()
|
||||
};
|
||||
let footprint_input = NodeInput::value(TaggedValue::Footprint(footprint), false);
|
||||
|
||||
// Save the node as the network that drew into a browser canvas, which took only the artwork and footprint
|
||||
let canvas_network = NodeNetworkTemplate {
|
||||
@@ -4852,111 +4644,27 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
let mut legacy = NodeTemplate {
|
||||
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), placeholder],
|
||||
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), footprint_input.clone()],
|
||||
implementation: NodeTemplateImplementation::Network(canvas_network),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_implementation(&node_id, &[], &mut legacy);
|
||||
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
|
||||
document.network_interface.set_reference(&node_id, &[], Some("Rasterize".into()));
|
||||
|
||||
// A 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40)
|
||||
let placeholder = r#"{"String":"footprint placeholder"}"#;
|
||||
let footprint = r#"{"Footprint":{"transform":[500.0,0.0,0.0,250.0,-20.0,40.0],"resolution":[64,32],"quality":"Full"}}"#;
|
||||
let serialized = document.serialize_document();
|
||||
assert!(serialized.contains(placeholder), "the placeholder should be serialized as expected");
|
||||
let serialized = serialized.replace(placeholder, footprint);
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
assert_eq!(interface.reference(&node_id, &[]), Some(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER)));
|
||||
|
||||
// The area's unit square is centered on its origin, so its translation is the rectangle's center
|
||||
let area = DAffine2::from_scale_angle_translation(DVec2::new(500., 250.), 0., DVec2::new(230., 165.));
|
||||
let input = |index| interface.input_from_connector(&InputConnector::node_at_index(node_id, index), &[]).cloned();
|
||||
assert_eq!(input(1), Some(NodeInput::value(TaggedValue::DAffine2(area), false)), "the footprint should cover the same area");
|
||||
assert_eq!(
|
||||
input(2),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(DVec2::new(64., 32.)), false)),
|
||||
"the footprint should keep its resolution"
|
||||
interface.input_from_connector(&InputConnector::node_at_index(node_id, 1), &[]),
|
||||
Some(&footprint_input),
|
||||
"the footprint should carry over"
|
||||
);
|
||||
|
||||
let definition_inputs = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition").node_template.inputs.len();
|
||||
assert_eq!(interface.number_of_inputs(&node_id, &[]), definition_inputs, "the node should gain the inputs the compiler fills in");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn opening_footprint_value_nodes_folds_them_into_the_rasterize_nodes_they_fed() {
|
||||
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::platform_application_io::rasterize;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let literal_rasterize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await;
|
||||
let wired_rasterize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 10).await;
|
||||
let transform_source = editor
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), -20, 10)
|
||||
.await;
|
||||
let reroute = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), -5, 10).await;
|
||||
let document = editor.active_document_mut();
|
||||
|
||||
let footprint_transform = DAffine2::from_scale_angle_translation(DVec2::new(300., 200.), 0., DVec2::new(10., 20.));
|
||||
let footprint_value = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::FootprintValueNode")),
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
NodeInput::value(TaggedValue::DAffine2(footprint_transform), false),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(30., 20.)), false),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let (literal_footprint, wired_footprint) = (NodeId(1), NodeId(2));
|
||||
document.network_interface.insert_node(literal_footprint, footprint_value.clone(), &[]);
|
||||
document.network_interface.insert_node(wired_footprint, footprint_value, &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(wired_footprint, 1), NodeInput::node(transform_source, 0), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(reroute, 0), NodeInput::node(wired_footprint, 0), &[]);
|
||||
|
||||
// Each Rasterize node as saved before its area and resolution, taking the artwork, the footprint, and the executor
|
||||
let definition = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition");
|
||||
let executor = definition.node_template.inputs.last().cloned().expect("Rasterize should take the executor");
|
||||
for (rasterize_node, footprint_node) in [(literal_rasterize, literal_footprint), (wired_rasterize, reroute)] {
|
||||
let mut old_inputs = NodeTemplate {
|
||||
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), NodeInput::node(footprint_node, 0), executor.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_inputs(&rasterize_node, &[], &mut old_inputs);
|
||||
}
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
let input = |node, index| interface.input_from_connector(&InputConnector::node_at_index(node, index), &[]).cloned();
|
||||
|
||||
assert!(interface.document_node(&literal_footprint, &[]).is_none(), "the Footprint Value node should be removed");
|
||||
assert!(interface.document_node(&wired_footprint, &[]).is_none(), "the Footprint Value node should be removed");
|
||||
|
||||
let corner_to_center = DAffine2::from_translation(DVec2::splat(0.5));
|
||||
let resolution = Some(NodeInput::value(TaggedValue::DVec2(DVec2::new(30., 20.)), false));
|
||||
assert_eq!(
|
||||
input(literal_rasterize, 1),
|
||||
Some(NodeInput::value(TaggedValue::DAffine2(footprint_transform * corner_to_center), false))
|
||||
);
|
||||
assert_eq!(input(literal_rasterize, 2), resolution);
|
||||
|
||||
// The wired transform reaches the area through a Multiply node centering its unit square
|
||||
let Some(NodeInput::Node { node_id: multiply, output_index: 0 }) = input(wired_rasterize, 1) else {
|
||||
panic!("the wired transform should reach the area through a node");
|
||||
};
|
||||
assert_eq!(input(multiply, 0), Some(NodeInput::node(transform_source, 0)));
|
||||
assert_eq!(input(multiply, 1), Some(NodeInput::value(TaggedValue::DAffine2(corner_to_center), false)));
|
||||
assert_eq!(input(wired_rasterize, 2), resolution);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn opening_a_document_with_the_removed_extract_node_turns_it_into_a_passthrough() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
@@ -5170,40 +4878,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() {
|
||||
@@ -5766,204 +5440,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();
|
||||
@@ -6513,35 +5989,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_image_to_bounds_opens_as_a_passthrough_of_its_image() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let (image, extend) = (NodeId(1), NodeId(2));
|
||||
let image_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
||||
.expect("the Image definition should exist")
|
||||
.default_node_template();
|
||||
let extend_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("raster_nodes::std_nodes::ExtendImageToBoundsNode")),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::DAffine2(DAffine2::IDENTITY), false)],
|
||||
display_name: "Extend Image to Bounds".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node(image, image_template, &[]);
|
||||
document.network_interface.insert_node(extend, extend_template, &[]);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(extend, 0), NodeInput::node(image, 0), &[]);
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let node = opened.network_interface.document_node(&extend, &[]).expect("the node should still exist");
|
||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||
assert!(matches!(node.inputs[..], [NodeInput::Node { node_id, output_index: 0, .. }] if node_id == image), "{:?}", node.inputs);
|
||||
assert_ne!(opened.network_interface.display_name(&extend, &[]), "Extend Image to Bounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use super::document::node_graph::graph_ui::GraphUiPart;
|
||||
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use super::history::HistoryMessage;
|
||||
use super::persistent_state::PersistentStateMessage;
|
||||
@@ -157,11 +158,6 @@ pub enum PortfolioMessage {
|
||||
artboard_name: Option<String>,
|
||||
artboard_count: usize,
|
||||
},
|
||||
RenderOverlays {
|
||||
#[serde(skip, default = "OverlayContext::default")]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
context: OverlayContext,
|
||||
},
|
||||
SubmitActiveGraphRender,
|
||||
SubmitGraphRender {
|
||||
document_id: DocumentId,
|
||||
@@ -175,6 +171,14 @@ pub enum PortfolioMessage {
|
||||
SubmitInspectContextOverrides {
|
||||
overrides: graphene_std::ContextOverrides,
|
||||
},
|
||||
UpdateGraphUi {
|
||||
part: GraphUiPart,
|
||||
},
|
||||
RenderOverlays {
|
||||
#[serde(skip, default = "OverlayContext::default")]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
context: OverlayContext,
|
||||
},
|
||||
PollNodeGraphEvaluation,
|
||||
ToggleResetNodesToDefinitionsOnOpen,
|
||||
ToggleRulers,
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::DocumentMessageContext;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions;
|
||||
use crate::messages::portfolio::document::node_graph::graph_ui;
|
||||
use crate::messages::portfolio::document_storage_io::{
|
||||
DocumentStoreHandle, attach_container, copy_stored_document, join_stored_session, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file,
|
||||
remove_stored_document,
|
||||
@@ -216,7 +217,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
// Send the information for tooltips and categories for each node/input.
|
||||
responses.add(FrontendMessage::SendUIMetadata {
|
||||
node_descriptions: document_node_definitions::collect_node_descriptions(),
|
||||
node_icons: document_node_definitions::collect_node_icons(),
|
||||
node_types: document_node_definitions::collect_node_types(),
|
||||
});
|
||||
|
||||
@@ -898,18 +898,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
// The document we are leaving won't get the pointer up that ends a wire drag in its graph, so abort the drag there before switching
|
||||
if self.active_document_id != Some(document_id)
|
||||
&& let Some(document) = self.active_document_mut()
|
||||
&& document.end_node_graph_wire_in_progress(responses)
|
||||
{
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
return;
|
||||
}
|
||||
|
||||
// The document we are leaving won't get the frames that settle what glides in its graph, so it settles at once
|
||||
if self.active_document_id != Some(document_id)
|
||||
&& let Some(document) = self.active_document_mut()
|
||||
{
|
||||
document.node_graph_handler.stop_gliding(&document.network_interface, responses);
|
||||
document.node_graph_handler.graph_ui.stop_animations(responses);
|
||||
let wire_ended = document.end_node_graph_wire_in_progress(responses);
|
||||
if wire_ended {
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
}
|
||||
let network_path = document.selection_network_path().to_vec();
|
||||
if wire_ended || document.node_graph_handler.abort_node_drag(&mut document.network_interface, &network_path, responses) {
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-save the document we are leaving
|
||||
@@ -958,8 +957,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(DocumentMessage::GraphViewOverlay { open: node_graph_open });
|
||||
if node_graph_open {
|
||||
responses.add(NodeGraphMessage::UpdateGraphBarRight);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires)
|
||||
} else {
|
||||
responses.add(PortfolioMessage::UpdateDocumentWidgets);
|
||||
}
|
||||
@@ -997,7 +994,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
artboard_name,
|
||||
artboard_count,
|
||||
};
|
||||
let result = self.executor.submit_document_export(document, document_id, export_config);
|
||||
let result = self.executor.submit_document_export(document, export_config);
|
||||
|
||||
if let Err(description) = result {
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
@@ -1012,6 +1009,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WakeNodeRuntime);
|
||||
}
|
||||
PortfolioMessage::UpdateGraphUi { part } => {
|
||||
let Some(document) = self.active_document_id.and_then(|id| self.documents.get_mut(&id)) else {
|
||||
return;
|
||||
};
|
||||
let edited = graph_ui::edited_name(document);
|
||||
document.node_graph_handler.graph_ui.update_name_field(edited, responses);
|
||||
let builder = graph_ui::GraphUiSceneBuilder::of(document);
|
||||
if self.executor.update_graph_ui(|scene| builder.update(part, scene)) {
|
||||
responses.add(PortfolioMessage::SubmitActiveGraphRender);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::SubmitActiveGraphRender => {
|
||||
if let Some(document_id) = self.active_document_id {
|
||||
responses.add(PortfolioMessage::SubmitGraphRender { document_id, ignore_hash: false });
|
||||
@@ -1025,9 +1033,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
return;
|
||||
};
|
||||
|
||||
// Skip rendering while a resource is still loading, so its error isn't shown in the meantime.
|
||||
// Each load queues `RunDocumentGraph` when it succeeds or fails, so the render goes ahead once none are left.
|
||||
if document.resources.awaiting_resources() {
|
||||
let graph_ui_config = graph_ui::config(document, preferences.graph_wire_style);
|
||||
if graph_ui_config.is_none() && document.resources.awaiting_resources() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1051,12 +1058,20 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
// TODO: See #3796.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add_front(FrontendMessage::UpdateViewportHolePunch {
|
||||
active: document.render_mode != graphene_std::vector::style::RenderMode::SvgPreview,
|
||||
active: document.render_mode != graphene_std::vector::style::RenderMode::SvgPreview || graph_ui_config.is_some(),
|
||||
});
|
||||
|
||||
let result = self
|
||||
.executor
|
||||
.submit_node_graph_evaluation(document, document_id, physical_resolution, scale, timing_information, node_to_inspect, ignore_hash, pointer_position);
|
||||
let result = self.executor.submit_node_graph_evaluation(
|
||||
document,
|
||||
document_id,
|
||||
physical_resolution,
|
||||
scale,
|
||||
timing_information,
|
||||
node_to_inspect,
|
||||
ignore_hash,
|
||||
pointer_position,
|
||||
graph_ui_config,
|
||||
);
|
||||
|
||||
match result {
|
||||
Err(description) => {
|
||||
@@ -1123,10 +1138,16 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
self.executor.submit_thumbnails_in_view(document, document_id);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::SubmitClipboardSvg { id } => match self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) {
|
||||
Some(document) => self.executor.submit_clipboard_svg(document, viewport.size().into_dvec2(), id),
|
||||
None => responses.add(ClipboardMessage::Rendered { id, svg: Ok(None) }),
|
||||
},
|
||||
PortfolioMessage::SubmitClipboardSvg { id } => {
|
||||
let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) else {
|
||||
responses.add(ClipboardMessage::Rendered { id, svg: None });
|
||||
return;
|
||||
};
|
||||
let selected = document.partition_selection().layers;
|
||||
let mut layers = document.metadata().all_layers().filter(|layer| selected.contains(layer)).collect::<Vec<_>>();
|
||||
layers.reverse();
|
||||
responses.add(self.executor.submit_clipboard_svg(document, id, &layers));
|
||||
}
|
||||
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::prelude::*;
|
||||
use graph_ui::wire::WireStyle;
|
||||
|
||||
#[impl_message(Message, Preferences)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
@@ -22,7 +22,7 @@ pub enum PreferencesMessage {
|
||||
zoom_with_scroll: bool,
|
||||
},
|
||||
GraphWireStyle {
|
||||
style: GraphWireStyle,
|
||||
style: WireStyle,
|
||||
},
|
||||
ViewportZoomWheelRate {
|
||||
rate: f64,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use crate::consts::{UI_SCALE_DEFAULT, VIEWPORT_ZOOM_WHEEL_RATE};
|
||||
use crate::messages::input_mapper::key_mapping::MappingVariant;
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
use graph_ui::wire::WireStyle;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct PreferencesMessageContext<'a> {
|
||||
@@ -17,7 +17,7 @@ pub struct PreferencesMessageHandler {
|
||||
pub selection_mode: SelectionMode,
|
||||
pub zoom_with_scroll: bool,
|
||||
pub brush_tool: bool,
|
||||
pub graph_wire_style: GraphWireStyle,
|
||||
pub graph_wire_style: WireStyle,
|
||||
pub viewport_zoom_wheel_rate: f64,
|
||||
pub ui_scale: f64,
|
||||
pub disable_ui_acceleration: bool,
|
||||
@@ -51,7 +51,7 @@ impl Default for PreferencesMessageHandler {
|
||||
selection_mode: SelectionMode::Touched,
|
||||
zoom_with_scroll: matches!(MappingVariant::default(), MappingVariant::ZoomWithScroll),
|
||||
brush_tool: false,
|
||||
graph_wire_style: GraphWireStyle::default(),
|
||||
graph_wire_style: WireStyle::default(),
|
||||
viewport_zoom_wheel_rate: VIEWPORT_ZOOM_WHEEL_RATE,
|
||||
ui_scale: UI_SCALE_DEFAULT,
|
||||
disable_ui_acceleration: true, // TODO: Set this back to false once we have ui acceleration working more reliably
|
||||
@@ -126,8 +126,7 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
|
||||
}
|
||||
PreferencesMessage::GraphWireStyle { style } => {
|
||||
self.graph_wire_style = style;
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
responses.add(PortfolioMessage::SubmitActiveGraphRender);
|
||||
}
|
||||
PreferencesMessage::ViewportZoomWheelRate { rate } => {
|
||||
self.viewport_zoom_wheel_rate = rate;
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
|
||||
@@ -29,8 +29,6 @@ pub struct GradientTool {
|
||||
#[derive(Default)]
|
||||
pub struct GradientOptions {
|
||||
gradient_form: GradientForm,
|
||||
/// Where the selected gradient's curvatures come from. Unless they make its form, neither form is shown as chosen.
|
||||
curvature_source: CurvatureSource,
|
||||
settings: GradientSettings,
|
||||
}
|
||||
|
||||
@@ -94,16 +92,12 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
||||
ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options {
|
||||
GradientOptionsUpdate::Form(gradient_form) => {
|
||||
self.options.gradient_form = gradient_form;
|
||||
self.options.curvature_source = CurvatureSource::Form;
|
||||
apply_gradient_update(
|
||||
&mut self.data,
|
||||
context,
|
||||
responses,
|
||||
|(_gradient, appearance)| appearance.gradient_form != gradient_form || appearance.curvature_source != CurvatureSource::Form,
|
||||
|(_gradient, appearance)| {
|
||||
appearance.gradient_form = gradient_form;
|
||||
appearance.curvature_source = CurvatureSource::Form;
|
||||
},
|
||||
|(_gradient, appearance)| appearance.gradient_form != gradient_form,
|
||||
|(_gradient, appearance)| appearance.gradient_form = gradient_form,
|
||||
);
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
responses.add(ToolMessage::UpdateCursor);
|
||||
@@ -198,19 +192,14 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
||||
|
||||
let mut needs_refresh = false;
|
||||
if let Some((_gradient, appearance)) = ¤t_gradient {
|
||||
if self.options.gradient_form != appearance.gradient_form || self.options.curvature_source != appearance.curvature_source {
|
||||
if self.options.gradient_form != appearance.gradient_form {
|
||||
self.options.gradient_form = appearance.gradient_form;
|
||||
self.options.curvature_source = appearance.curvature_source;
|
||||
needs_refresh = true;
|
||||
}
|
||||
if self.options.settings != appearance.settings {
|
||||
self.options.settings = appearance.settings;
|
||||
needs_refresh = true;
|
||||
}
|
||||
} else if self.options.curvature_source != CurvatureSource::Form {
|
||||
// With no gradient selected, the Form radio shows the form a new one gets
|
||||
self.options.curvature_source = CurvatureSource::Form;
|
||||
needs_refresh = true;
|
||||
}
|
||||
|
||||
let has_gradient = current_gradient.is_some();
|
||||
@@ -272,11 +261,7 @@ impl LayoutHolder for GradientTool {
|
||||
}
|
||||
.into()
|
||||
});
|
||||
let selected_form = (self.options.curvature_source == CurvatureSource::Form).then_some(self.options.gradient_form as u32);
|
||||
let gradient_form = RadioInput::new(gradient_form_entries)
|
||||
.selected_index(selected_form)
|
||||
.disabled(self.options.curvature_source == CurvatureSource::Graph)
|
||||
.widget_instance();
|
||||
let gradient_form = RadioInput::new(gradient_form_entries).selected_index(Some(self.options.gradient_form as u32)).widget_instance();
|
||||
|
||||
// Display priority: the selected layer's stops, then any user-customized tool default, then the working colors
|
||||
let stops_value = self
|
||||
@@ -396,12 +381,10 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
||||
let fill_node = network_interface.document_network().nodes.get(&fill_id)?;
|
||||
let gradient = graph_modification_utils::read_fill_node_gradient(fill_node, || network_interface.document_metadata().nonzero_bounding_box(layer))?;
|
||||
|
||||
let (gradient_form, curvature_source) = CurvatureSource::of(gradient.curvatures);
|
||||
return Some((
|
||||
gradient.stops,
|
||||
GradientAppearance {
|
||||
gradient_form,
|
||||
curvature_source,
|
||||
gradient_form: gradient.gradient_form,
|
||||
settings: gradient.settings,
|
||||
transform: gradient.transform,
|
||||
},
|
||||
@@ -421,48 +404,19 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
||||
struct GradientAppearance {
|
||||
transform: DAffine2,
|
||||
gradient_form: GradientForm,
|
||||
/// Where the chain's curvatures come from. Unless they make `gradient_form`, the tool draws the linear form's controls.
|
||||
// TODO: Draw the stops and midpoints of custom curvatures where their contours cross the line, since the ramp can then span just part of it
|
||||
curvature_source: CurvatureSource,
|
||||
settings: GradientSettings,
|
||||
}
|
||||
|
||||
/// Where a gradient's curvatures come from, as told by its 'Gradient Curvature' node or the Fill node holding it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum CurvatureSource {
|
||||
/// They make the form, or there's no node and the form's are implied.
|
||||
#[default]
|
||||
Form,
|
||||
/// They're values that make neither form.
|
||||
Custom,
|
||||
/// They're fed from the graph or exposed, so only the graph can change them.
|
||||
Graph,
|
||||
}
|
||||
|
||||
impl CurvatureSource {
|
||||
/// The form some curvatures make (linear if neither) and where they come from, given them unless the graph feeds them.
|
||||
fn of(curvatures: Option<[f64; 2]>) -> (GradientForm, Self) {
|
||||
let form = curvatures.and_then(GradientForm::from_curvatures);
|
||||
let source = match (curvatures, form) {
|
||||
(None, _) => Self::Graph,
|
||||
(Some(_), None) => Self::Custom,
|
||||
(Some(_), Some(_)) => Self::Form,
|
||||
};
|
||||
(form.unwrap_or_default(), source)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the gradient transform, form, and spread by walking the chain feeding the layer.
|
||||
fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance {
|
||||
let target_input = gradient_chain_target_input(layer, network_interface);
|
||||
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
||||
|
||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
|
||||
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
||||
let mut gradient_form: Option<GradientForm> = None;
|
||||
let mut curvature_source = CurvatureSource::Form;
|
||||
|
||||
for node_id in network_interface
|
||||
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
|
||||
@@ -476,9 +430,11 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
|
||||
if reference == transform_reference {
|
||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
||||
let (form, source) = CurvatureSource::of(graph_modification_utils::gradient_curvature_values(document_node));
|
||||
(gradient_form, curvature_source) = (Some(form), source);
|
||||
} else if reference == gradient_form_reference
|
||||
&& gradient_form.is_none()
|
||||
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||
{
|
||||
gradient_form = Some(*value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -488,7 +444,6 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
GradientAppearance {
|
||||
transform: composed_transform,
|
||||
gradient_form: gradient_form.unwrap_or_default(),
|
||||
curvature_source,
|
||||
settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
@@ -838,15 +793,12 @@ impl SelectedGradient {
|
||||
pub fn render_gradient(&mut self, responses: &mut VecDeque<Message>) {
|
||||
if let Some(layer) = self.layer {
|
||||
if self.is_gradient_chain {
|
||||
// Only a new gradient takes its form from the tool, as the Properties panel may have adjusted an existing one after it was selected
|
||||
let write_form = self.dragging == GradientDragTarget::New;
|
||||
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, write_form, responses);
|
||||
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, responses);
|
||||
} else {
|
||||
// Only a new gradient takes its form from the tool, as with a chain
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: self.gradient.clone(),
|
||||
gradient_form: (self.dragging == GradientDragTarget::New).then_some(self.appearance.gradient_form),
|
||||
gradient_form: self.appearance.gradient_form,
|
||||
gradient_settings: self.appearance.settings,
|
||||
transform: Some(self.appearance.transform),
|
||||
});
|
||||
@@ -877,8 +829,8 @@ impl SelectedGradient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer, including its form's curvatures if `write_form` is set.
|
||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, write_form: bool, responses: &mut VecDeque<Message>) {
|
||||
/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer.
|
||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
|
||||
responses.add(GraphOperationMessage::GradientCyclicSet {
|
||||
layer,
|
||||
gradient_cyclic: appearance.settings.cyclic,
|
||||
@@ -896,12 +848,10 @@ fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradien
|
||||
layer,
|
||||
transform: appearance.transform,
|
||||
});
|
||||
if write_form && appearance.curvature_source == CurvatureSource::Form {
|
||||
responses.add(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: appearance.gradient_form,
|
||||
});
|
||||
}
|
||||
responses.add(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: appearance.gradient_form,
|
||||
});
|
||||
responses.add(GraphOperationMessage::GradientSpreadSet {
|
||||
layer,
|
||||
gradient_spread: appearance.settings.spread,
|
||||
@@ -1572,7 +1522,6 @@ impl Fsm for GradientToolFsmState {
|
||||
GradientAppearance {
|
||||
transform: DAffine2::IDENTITY,
|
||||
gradient_form: tool_options.gradient_form,
|
||||
curvature_source: CurvatureSource::Form,
|
||||
settings: tool_options.settings,
|
||||
},
|
||||
// A blank layer, or one holding only the other tool's paint, starts a whole-expanse gradient chain; a layer with content gets its Fill painted
|
||||
@@ -1991,13 +1940,12 @@ fn apply_gradient_update(
|
||||
|
||||
// Only check for the gradient list once we know we'll write back, since this is a graph traversal per layer
|
||||
if get_upstream_gradient_value_node_id(layer, &context.document.network_interface).is_some() {
|
||||
// Read fresh from the layer, so its form's curvatures change only if the update chose another form
|
||||
dispatch_gradient_chain_writes(layer, &gradient, appearance, true, responses);
|
||||
dispatch_gradient_chain_writes(layer, &gradient, appearance, responses);
|
||||
} else {
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient,
|
||||
gradient_form: (appearance.curvature_source == CurvatureSource::Form).then_some(appearance.gradient_form),
|
||||
gradient_form: appearance.gradient_form,
|
||||
gradient_settings: appearance.settings,
|
||||
transform: Some(appearance.transform),
|
||||
});
|
||||
@@ -2063,7 +2011,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: new_gradient.clone(),
|
||||
gradient_form: None,
|
||||
gradient_form: appearance.gradient_form,
|
||||
gradient_settings: settings,
|
||||
transform: Some(appearance.transform),
|
||||
});
|
||||
@@ -2160,7 +2108,6 @@ mod test_gradient {
|
||||
use super::{GradientHoverTarget, detect_hover_target, gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at};
|
||||
use crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::layout::utility_types::layout_widget::{DiffUpdate, Layout, LayoutTarget, Widget, WidgetInstance};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
@@ -2168,8 +2115,8 @@ mod test_gradient {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id;
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation};
|
||||
@@ -3419,7 +3366,7 @@ mod test_gradient {
|
||||
.await;
|
||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
||||
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
editor
|
||||
@@ -3428,7 +3375,7 @@ mod test_gradient {
|
||||
})
|
||||
.await;
|
||||
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let form_node_id = {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
network_interface
|
||||
@@ -3437,10 +3384,10 @@ mod test_gradient {
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
||||
.expect("Gradient Curvature node should have been inserted")
|
||||
.expect("Gradient Form node should have been inserted")
|
||||
};
|
||||
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
|
||||
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
||||
|
||||
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
||||
@@ -3585,347 +3532,6 @@ mod test_gradient {
|
||||
assert!(matches!(positions_input, NodeInput::Node { .. }), "the wired positions input must survive the baked write");
|
||||
}
|
||||
|
||||
/// Drags the end of a layer's gradient by `offset` in the viewport with the Gradient tool, returning where the end was dragged to.
|
||||
async fn drag_gradient_end(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, offset: DVec2) -> DVec2 {
|
||||
let document = editor.active_document();
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
|
||||
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
|
||||
let dragged_end = end + offset;
|
||||
|
||||
editor.move_mouse(end.x, end.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(end.x, end.y, ModifierKeys::empty()).await;
|
||||
editor.move_mouse(dragged_end.x, dragged_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
editor
|
||||
.mouseup(
|
||||
EditorPointerState {
|
||||
editor_position: dragged_end,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
.await;
|
||||
|
||||
dragged_end
|
||||
}
|
||||
|
||||
/// Makes a layer drawing a gradient list along the line from (10, 50) to (200, 50) and selects it with the Gradient tool, then chooses
|
||||
/// the radial form, which inserts a 'Gradient Curvature' node. Returns the layer and that node.
|
||||
async fn radial_gradient_list_layer(editor: &mut EditorTestUtils) -> (LayerNodeIdentifier, NodeId) {
|
||||
editor.active_document_mut().snapping_state.snapping_enabled = false;
|
||||
let layer = create_gradient_list_layer(editor).await;
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::GradientTransformSet {
|
||||
layer,
|
||||
transform: transform_from_line(DVec2::new(10., 50.), DVec2::new(200., 50.)),
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
|
||||
editor
|
||||
.handle_message(GradientToolMessage::UpdateOptions {
|
||||
options: super::GradientOptionsUpdate::Form(GradientForm::Radial),
|
||||
})
|
||||
.await;
|
||||
let curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let curvature_node_id = network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&curvature_reference))
|
||||
.expect("Gradient Curvature node should have been inserted");
|
||||
assert_eq!(
|
||||
curvature_inputs(editor, curvature_node_id),
|
||||
inputs_holding(GradientForm::Radial.curvatures()),
|
||||
"the inserted node should hold the radial form's curvatures"
|
||||
);
|
||||
|
||||
(layer, curvature_node_id)
|
||||
}
|
||||
|
||||
/// Sets both curvatures of a 'Gradient Curvature' node, as its sliders in the Properties panel do.
|
||||
async fn set_curvatures(editor: &mut EditorTestUtils, curvature_node_id: NodeId, curvatures: [f64; 2]) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
for (input_index, curvature) in [StartCurvatureInput::INDEX, EndCurvatureInput::INDEX].into_iter().zip(curvatures) {
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: curvature_node_id,
|
||||
input_index,
|
||||
value: TaggedValue::Number(curvature).into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The start and end curvature inputs of a 'Gradient Curvature' node.
|
||||
fn curvature_inputs(editor: &EditorTestUtils, curvature_node_id: NodeId) -> [Option<NodeInput>; 2] {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let node = &editor.active_document().network_interface.document_network().nodes[&curvature_node_id];
|
||||
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
|
||||
}
|
||||
|
||||
/// The curvature inputs holding these values.
|
||||
fn inputs_holding(curvatures: [f64; 2]) -> [Option<NodeInput>; 2] {
|
||||
curvatures.map(|curvature| Some(NodeInput::value(TaggedValue::Number(curvature), false)))
|
||||
}
|
||||
|
||||
/// The Form radio's chosen entry and whether it's disabled, as last sent to the control bar among these frontend messages.
|
||||
fn latest_form_radio(frontend_messages: &[FrontendMessage]) -> Option<(Option<u32>, bool)> {
|
||||
let form_radio = |widget: &WidgetInstance| match &*widget.widget {
|
||||
Widget::RadioInput(radio_input) => Some((radio_input.selected_index, radio_input.disabled)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
frontend_messages
|
||||
.iter()
|
||||
.rev()
|
||||
.filter_map(|message| match message {
|
||||
FrontendMessage::UpdateLayout {
|
||||
layout_target: LayoutTarget::ToolOptions,
|
||||
diff,
|
||||
} => Some(diff),
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(|diff| diff.iter().rev())
|
||||
.find_map(|widget_diff| match &widget_diff.new_value {
|
||||
DiffUpdate::Widget(widget) => form_radio(widget),
|
||||
DiffUpdate::Layout(layout) => layout.iter().find_map(form_radio),
|
||||
DiffUpdate::LayoutGroup(group) => Layout(vec![group.clone()]).iter().find_map(form_radio),
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tool_edits_keep_custom_curvatures_until_a_form_is_chosen() {
|
||||
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
|
||||
|
||||
// Dragging the end writes every attribute the tool manages, but leaves the curvatures as they are
|
||||
let dragged_end = drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
|
||||
let document = editor.active_document();
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the gradient should survive the drag");
|
||||
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
|
||||
assert!(end.abs_diff_eq(dragged_end, 1.), "the drag should move the end to {dragged_end:?}, not {end:?}");
|
||||
assert_eq!(curvature_inputs(&editor, curvature_node_id), inputs_holding([0.5, 0.25]), "a drag shouldn't reset custom curvatures");
|
||||
|
||||
// Choosing a form in the control bar is what sets them
|
||||
editor
|
||||
.handle_message(GradientToolMessage::UpdateOptions {
|
||||
options: super::GradientOptionsUpdate::Form(GradientForm::Linear),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding(GradientForm::Linear.curvatures()),
|
||||
"choosing the linear form should set its curvatures"
|
||||
);
|
||||
|
||||
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
|
||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(number_node_id),
|
||||
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
|
||||
})
|
||||
.await;
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: GradientForm::Radial,
|
||||
})
|
||||
.await;
|
||||
let [start_input, end_input] = curvature_inputs(&editor, curvature_node_id);
|
||||
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
|
||||
assert_eq!(
|
||||
end_input,
|
||||
inputs_holding(GradientForm::Linear.curvatures())[1],
|
||||
"the end curvature beside a wired one should stay as it was"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn edits_of_a_fill_gradient_keep_its_curvatures_until_a_form_is_chosen() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_fill_node_id_with_direct_fill_input;
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.active_document_mut().snapping_state.snapping_enabled = false;
|
||||
editor.drag_tool(ToolType::Rectangle, -5., -3., 100., 100., ModifierKeys::empty()).await;
|
||||
editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layer = document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers(document.metadata())
|
||||
.next()
|
||||
.expect("the rectangle is selected");
|
||||
let fill_id = get_fill_node_id_with_direct_fill_input(layer, &document.network_interface).expect("the gradient is held by the Fill");
|
||||
let curvatures = |editor: &EditorTestUtils| {
|
||||
let node = &editor.active_document().network_interface.document_network().nodes[&fill_id];
|
||||
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
|
||||
};
|
||||
|
||||
// Curvatures making neither form survive a drag of the gradient's end
|
||||
for (input_index, curvature) in [(StartCurvatureInput::INDEX, 0.3), (EndCurvatureInput::INDEX, 0.2)] {
|
||||
let value = TaggedValue::Number(curvature).into();
|
||||
editor.handle_message(NodeGraphMessage::SetInputValue { node_id: fill_id, input_index, value }).await;
|
||||
}
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., 20.)).await;
|
||||
assert_eq!(curvatures(&editor), inputs_holding([0.3, 0.2]), "a drag shouldn't reset custom curvatures");
|
||||
|
||||
// Choosing a form in the control bar is what sets them
|
||||
let choose_form = |form| GradientToolMessage::UpdateOptions {
|
||||
options: super::GradientOptionsUpdate::Form(form),
|
||||
};
|
||||
editor.handle_message(choose_form(GradientForm::Radial)).await;
|
||||
assert_eq!(
|
||||
curvatures(&editor),
|
||||
inputs_holding(GradientForm::Radial.curvatures()),
|
||||
"choosing the radial form should set its curvatures"
|
||||
);
|
||||
|
||||
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
|
||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(number_node_id),
|
||||
input_connector: InputConnector::node(fill_id, StartCurvatureInput),
|
||||
})
|
||||
.await;
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
|
||||
editor.handle_message(choose_form(GradientForm::Linear)).await;
|
||||
let [start_input, end_input] = curvatures(&editor);
|
||||
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
|
||||
assert_eq!(
|
||||
end_input,
|
||||
inputs_holding(GradientForm::Radial.curvatures())[1],
|
||||
"the end curvature beside a wired one should stay as it was"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_edits_keep_curvatures_set_while_the_stop_was_selected() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
let stop_count = |editor: &EditorTestUtils| get_gradient_stops(layer, &editor.active_document().network_interface).map(|stops| stops.len());
|
||||
|
||||
// Clicking the line inserts a stop and selects it, and a double-click opens its color picker
|
||||
let document = editor.active_document();
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
|
||||
let stop = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::new(0.3, 0.));
|
||||
editor.move_mouse(stop.x, stop.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(stop.x, stop.y, ModifierKeys::empty()).await;
|
||||
editor.left_mouseup(stop.x, stop.y, ModifierKeys::empty()).await;
|
||||
editor.handle_message(GradientToolMessage::DoubleClick).await;
|
||||
assert_eq!(stop_count(&editor), Some(3), "the click should insert a stop");
|
||||
|
||||
// The Properties panel then adjusts curvatures of neither form while the stop stays selected
|
||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.5]).await;
|
||||
|
||||
editor.handle_message(GradientToolMessage::UpdateStopColor { color: Color::GREEN }).await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([0.5, 0.5]),
|
||||
"recoloring the stop shouldn't reset the curvatures"
|
||||
);
|
||||
|
||||
editor.press(Key::Delete, ModifierKeys::empty()).await;
|
||||
assert_eq!(stop_count(&editor), Some(2), "Delete should remove the selected stop");
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([0.5, 0.5]),
|
||||
"deleting the stop shouldn't reset the curvatures"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn curvatures_already_making_a_form_are_kept_by_writes_of_that_form() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
|
||||
// The start curvature's slider maximum is the same point as -1, so the tool draws these curvatures as the radial form
|
||||
set_curvatures(&mut editor, curvature_node_id, [1., 0.5]).await;
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &editor.active_document().network_interface).expect("the layer should have a gradient");
|
||||
assert_eq!((appearance.gradient_form, appearance.curvature_source), (GradientForm::Radial, super::CurvatureSource::Form));
|
||||
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([1., 0.5]),
|
||||
"a drag shouldn't rewrite curvatures making the form"
|
||||
);
|
||||
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: GradientForm::Radial,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([1., 0.5]),
|
||||
"setting the form they make shouldn't rewrite them"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_form_radio_shows_what_a_new_gradient_gets_once_a_custom_one_is_deselected() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
|
||||
|
||||
// Reselecting the layer has the tool read its curvatures, which make neither form
|
||||
let mut frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
assert_eq!(latest_form_radio(&frontend_messages), Some((None, false)), "custom curvatures should show neither form as chosen");
|
||||
|
||||
frontend_messages.extend(editor.handle_message(DocumentMessage::DeselectAllLayers).await);
|
||||
assert_eq!(
|
||||
latest_form_radio(&frontend_messages),
|
||||
Some((Some(GradientForm::Linear as u32), false)),
|
||||
"with nothing selected, the radio should show the linear form a new gradient gets"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_form_radio_is_disabled_for_curvatures_fed_from_the_graph() {
|
||||
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
|
||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(number_node_id),
|
||||
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
|
||||
})
|
||||
.await;
|
||||
|
||||
let frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
assert_eq!(
|
||||
latest_form_radio(&frontend_messages),
|
||||
Some((None, true)),
|
||||
"a wired curvature should leave no form chosen and the radio disabled"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn drag_on_blank_layer_starts_gradient_chain() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
||||
|
||||
+270
-182
@@ -1,13 +1,18 @@
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
|
||||
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::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, RootNode};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::resource::ResourceRegistry;
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
|
||||
use graph_craft::list;
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graph_ui::GraphUiConfig;
|
||||
use graph_ui::scene::{GraphUiScene, GraphUiSceneEdit};
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
@@ -17,8 +22,9 @@ use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
|
||||
use graphene_std::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic, NodeParameter};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use interpreted_executor::layer_paths::{layer_content, write_layer_paths};
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
@@ -28,10 +34,11 @@ mod recompile_tests;
|
||||
mod runtime;
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExecutionRequest {
|
||||
execution_id: u64,
|
||||
render_config: RenderConfig,
|
||||
graph_ui_config: Option<GraphUiConfig>,
|
||||
}
|
||||
|
||||
pub struct ExecutionResponse {
|
||||
@@ -98,7 +105,8 @@ impl std::fmt::Display for EvaluationErrors {
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
pub struct CompilationResponse {
|
||||
result: Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)>,
|
||||
result: Result<(), String>,
|
||||
resolved_types: ResolvedDocumentNodeTypesDelta,
|
||||
node_graph_errors: GraphErrors,
|
||||
node_graph_warnings: GraphErrors,
|
||||
}
|
||||
@@ -113,21 +121,26 @@ pub enum NodeGraphUpdate {
|
||||
},
|
||||
/// The latest result of each observation, sent outside an execution after one of them changed.
|
||||
Observations(HashMap<ObservationKey, InspectResult>),
|
||||
ClipboardSvg {
|
||||
Export {
|
||||
id: u64,
|
||||
/// The SVG, `None` if the layers add nothing, or why it couldn't be rendered.
|
||||
svg: Result<Option<String>, String>,
|
||||
result: Box<ExecutionResult>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NodeGraphExecutor {
|
||||
sender: Sender<GraphRuntimeRequest>,
|
||||
|
||||
receiver: Receiver<NodeGraphUpdate>,
|
||||
current_execution_id: u64,
|
||||
futures: VecDeque<(u64, ExecutionContext)>,
|
||||
pending: Option<(u64, ExecutionContext)>,
|
||||
|
||||
current_export_id: u64,
|
||||
exports: HashMap<u64, ExportTarget>,
|
||||
|
||||
node_graph_hash: u64,
|
||||
graph_ui_scene: GraphUiScene,
|
||||
/// The document whose network the graph runtime was last sent.
|
||||
node_graph_document: Option<DocumentId>,
|
||||
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
|
||||
@@ -148,9 +161,14 @@ pub struct NodeGraphExecutor {
|
||||
gradient_migration_attempted: HashSet<DocumentId>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ExportTarget {
|
||||
File(ExportConfig),
|
||||
Clipboard(u64),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ExecutionContext {
|
||||
export_config: Option<ExportConfig>,
|
||||
document_id: DocumentId,
|
||||
/// The view the render was asked for, which the footprints it reports back are measured in.
|
||||
document_to_viewport: DAffine2,
|
||||
@@ -185,7 +203,10 @@ impl NodeGraphExecutor {
|
||||
futures: Default::default(),
|
||||
pending: None,
|
||||
current_execution_id: 0,
|
||||
current_export_id: 0,
|
||||
exports: HashMap::new(),
|
||||
node_graph_hash: 0,
|
||||
graph_ui_scene: GraphUiScene::default(),
|
||||
node_graph_document: None,
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
inspect_context_overrides: ContextOverrides::default(),
|
||||
@@ -198,21 +219,35 @@ impl NodeGraphExecutor {
|
||||
(node_executor, node_runtime)
|
||||
}
|
||||
|
||||
/// Forgets which canvas images the frontend holds, for a frontend that started over without them.
|
||||
pub fn forget_canvas_images(&mut self) {
|
||||
self.canvas_images_sent.clear();
|
||||
}
|
||||
|
||||
/// Execute the network by flattening it and creating a borrow stack.
|
||||
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
|
||||
fn queue_execution(&mut self, render_config: RenderConfig, graph_ui_config: Option<GraphUiConfig>) -> u64 {
|
||||
let execution_id = self.current_execution_id;
|
||||
self.current_execution_id += 1;
|
||||
let request = ExecutionRequest { execution_id, render_config };
|
||||
let request = ExecutionRequest {
|
||||
execution_id,
|
||||
render_config,
|
||||
graph_ui_config,
|
||||
};
|
||||
self.sender.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request");
|
||||
|
||||
execution_id
|
||||
}
|
||||
|
||||
fn queue_export(&mut self, network: NodeNetwork, resources: ResourceRegistry, render_config: RenderConfig, target: ExportTarget) -> Result<(), String> {
|
||||
let id = self.current_export_id;
|
||||
self.current_export_id += 1;
|
||||
let request = GraphRuntimeRequest::Export {
|
||||
id,
|
||||
render_config,
|
||||
network,
|
||||
resources,
|
||||
};
|
||||
self.sender.send(request).map_err(|e| e.to_string())?;
|
||||
self.exports.insert(id, target);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
|
||||
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
|
||||
log::error!("Failed to send the overlays: {error}");
|
||||
@@ -231,28 +266,29 @@ impl NodeGraphExecutor {
|
||||
.expect("Failed to send the context overrides");
|
||||
}
|
||||
|
||||
/// Has the runtime render what the selected layers add as an SVG, which it sends back once their content is final.
|
||||
/// The `viewport_size` is in viewport pixels.
|
||||
pub fn submit_clipboard_svg(&self, document: &DocumentMessageHandler, viewport_size: DVec2, id: u64) {
|
||||
let network_interface = &document.network_interface;
|
||||
let view = (document.metadata().document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, viewport_size])).bounding_box();
|
||||
|
||||
// Painted from the bottom up
|
||||
let selected = document.partition_selection().layers;
|
||||
let mut layers: Vec<_> = document.metadata().all_layers().filter(|layer| selected.contains(layer)).map(|layer| layer.to_node()).collect();
|
||||
layers.reverse();
|
||||
|
||||
// The network as it is now, since the runtime applies a graph update sent before this one only after it reads this
|
||||
let request = ClipboardSvgRequest {
|
||||
id,
|
||||
network: network_interface.document_network().clone(),
|
||||
resources: document.resources.registry.clone(),
|
||||
previewed: network_interface.previewed_nodes(),
|
||||
layer_paths: network_interface.layer_paths(),
|
||||
layers,
|
||||
view,
|
||||
pub fn submit_clipboard_svg(&mut self, document: &DocumentMessageHandler, id: u64, layers: &[LayerNodeIdentifier]) -> Message {
|
||||
let no_svg = ClipboardMessage::Rendered { id, svg: None }.into();
|
||||
let Some((network, [min, max])) = copied_layers(&document.network_interface, layers) else {
|
||||
return no_svg;
|
||||
};
|
||||
self.sender.send(GraphRuntimeRequest::ClipboardSvg(request)).expect("Failed to send runtime request");
|
||||
|
||||
let viewport = Footprint {
|
||||
resolution: (max - min).round().as_uvec2(),
|
||||
transform: DAffine2::from_translation(-min),
|
||||
..Default::default()
|
||||
};
|
||||
let render_config = RenderConfig {
|
||||
viewport,
|
||||
scale: 1.,
|
||||
export_format: ExportFormat::Svg,
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
match self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::Clipboard(id)) {
|
||||
Ok(()) => Message::NoOp,
|
||||
Err(_) => no_svg,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
|
||||
@@ -262,8 +298,9 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
let layers = document.layers_in_view.all_in_view();
|
||||
let layers_panel = document.layers_in_view.layers_panel().clone();
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::ThumbnailsInView { layers, document_id })
|
||||
.send(GraphRuntimeRequest::ThumbnailsInView { layers, layers_panel, document_id })
|
||||
.expect("Failed to send the thumbnails in view");
|
||||
}
|
||||
|
||||
@@ -277,9 +314,11 @@ impl NodeGraphExecutor {
|
||||
|
||||
let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash());
|
||||
if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
let previewed = document.network_interface.previewed_nodes();
|
||||
let layers = document.network_interface.layer_paths();
|
||||
prepare_network(&mut network, &previewed, &layers);
|
||||
let thumbnails = thumbnail_sources(&network, &layers);
|
||||
self.node_graph_hash = graph_hash;
|
||||
self.node_graph_document = Some(document_id);
|
||||
|
||||
@@ -289,8 +328,7 @@ impl NodeGraphExecutor {
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
previewed,
|
||||
layers,
|
||||
thumbnails,
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
@@ -323,6 +361,7 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
/// Adds an evaluate request for whatever current network is cached.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn submit_current_node_graph_evaluation(
|
||||
&mut self,
|
||||
document: &mut DocumentMessageHandler,
|
||||
@@ -331,6 +370,7 @@ impl NodeGraphExecutor {
|
||||
viewport_scale: f64,
|
||||
time: TimingInformation,
|
||||
pointer: DVec2,
|
||||
graph_ui_config: Option<GraphUiConfig>,
|
||||
) -> Result<Message, String> {
|
||||
let viewport = Footprint {
|
||||
transform: document.metadata().document_to_viewport,
|
||||
@@ -349,12 +389,11 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
let execution_id = self.queue_execution(render_config, graph_ui_config);
|
||||
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: None,
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
@@ -376,9 +415,10 @@ impl NodeGraphExecutor {
|
||||
node_to_inspect: Vec<NodeId>,
|
||||
ignore_hash: bool,
|
||||
pointer: DVec2,
|
||||
graph_ui_config: Option<GraphUiConfig>,
|
||||
) -> Result<Message, String> {
|
||||
self.update_node_graph(document, document_id, node_to_inspect, ignore_hash)?;
|
||||
self.submit_current_node_graph_evaluation(document, document_id, viewport_resolution, viewport_scale, time, pointer)
|
||||
self.submit_current_node_graph_evaluation(document, document_id, viewport_resolution, viewport_scale, time, pointer, graph_ui_config)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -416,12 +456,11 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
let execution_id = self.queue_execution(render_config, None);
|
||||
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: None,
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
@@ -432,10 +471,9 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
/// Evaluates a node graph for export
|
||||
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, export_config: ExportConfig) -> Result<(), String> {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let previewed = document.network_interface.previewed_nodes();
|
||||
let resources = document.resources.registry.clone();
|
||||
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, export_config: ExportConfig) -> Result<(), String> {
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
prepare_network(&mut network, &document.network_interface.previewed_nodes(), &document.network_interface.layer_paths());
|
||||
|
||||
let export_format = if export_config.file_type == FileType::Svg {
|
||||
graphene_std::application_io::ExportFormat::Svg
|
||||
@@ -452,30 +490,29 @@ impl NodeGraphExecutor {
|
||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
||||
}
|
||||
.ok_or_else(|| "No bounding box".to_string())?;
|
||||
let render_config = export_render_config(bounds, export_config.scale_factor, export_format);
|
||||
|
||||
// Execute the node graph
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
previewed,
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: Some(export_config),
|
||||
document_id,
|
||||
document_to_viewport: render_config.viewport.transform,
|
||||
measure_fill: None,
|
||||
},
|
||||
));
|
||||
let resolution_in_document_space = bounds[1] - bounds[0];
|
||||
let export_resolution = resolution_in_document_space * export_config.scale_factor;
|
||||
let resolution = export_resolution.round().as_uvec2();
|
||||
let transform = DAffine2::from_translation(bounds[0]).inverse();
|
||||
let viewport = Footprint {
|
||||
resolution,
|
||||
transform,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Ok(())
|
||||
let render_config = RenderConfig {
|
||||
viewport,
|
||||
scale: export_config.scale_factor,
|
||||
time: Default::default(),
|
||||
pointer: DVec2::ZERO,
|
||||
export_format,
|
||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
};
|
||||
|
||||
self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::File(export_config))
|
||||
}
|
||||
|
||||
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
|
||||
@@ -487,8 +524,8 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
let mut all_dropped_thumbnails = Vec::new();
|
||||
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter();
|
||||
for response in results.by_ref() {
|
||||
let results = self.receiver.try_iter().collect::<Vec<_>>();
|
||||
for response in results {
|
||||
match response {
|
||||
NodeGraphUpdate::ExecutionResponse(execution_response) => {
|
||||
let ExecutionResponse {
|
||||
@@ -512,7 +549,7 @@ impl NodeGraphExecutor {
|
||||
|
||||
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
|
||||
let (_, execution_context) = self.futures.pop_front().expect("the front was just checked");
|
||||
if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() {
|
||||
if execution_context.measure_fill.is_none() {
|
||||
self.pending = Some((execution_id, execution_context.clone()));
|
||||
}
|
||||
execution_context
|
||||
@@ -535,7 +572,9 @@ impl NodeGraphExecutor {
|
||||
if let Some(bake_target) = execution_context.measure_fill {
|
||||
if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) {
|
||||
let measured = observations.remove(&ObservationKey::FillMeasurement);
|
||||
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(measured).flatten();
|
||||
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Partial(_) | ExecutionResult::Fallback(..))
|
||||
.then_some(measured)
|
||||
.flatten();
|
||||
self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses);
|
||||
}
|
||||
continue;
|
||||
@@ -566,8 +605,8 @@ impl NodeGraphExecutor {
|
||||
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
// A pending graph keeps the last frame, and the errors shown with it
|
||||
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
|
||||
// A pending graph keeps the last frame, and the errors shown with it; a provisional frame keeps the errors
|
||||
if !matches!(result, ExecutionResult::Pending | ExecutionResult::Partial(_)) {
|
||||
let errors = match &result {
|
||||
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
|
||||
let in_document = |path: &&[NodeId]| {
|
||||
@@ -640,11 +679,8 @@ impl NodeGraphExecutor {
|
||||
log::error!("Node graph evaluation failed:\n{message}");
|
||||
}
|
||||
|
||||
if execution_context.export_config.is_some() {
|
||||
responses.add(export_failure_dialog(message));
|
||||
}
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -662,10 +698,8 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
document.network_interface.update_vector_modify(path_contents(&observations));
|
||||
|
||||
match (node_graph_output, execution_context.export_config) {
|
||||
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
|
||||
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
|
||||
(None, _) => {}
|
||||
if let Some(node_graph_output) = node_graph_output {
|
||||
self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses);
|
||||
}
|
||||
responses.add(DeferMessage::TriggerGraphRun {
|
||||
execution_id,
|
||||
@@ -687,49 +721,42 @@ impl NodeGraphExecutor {
|
||||
node_graph_errors,
|
||||
node_graph_warnings,
|
||||
result,
|
||||
resolved_types,
|
||||
} = execution_response;
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
// The migration's temporary redirected-export compilations must not push types or a graph view to the frontend
|
||||
if self.gradient_migration.is_some() {
|
||||
if let Err((_, e)) = &result {
|
||||
if let Err(e) = &result {
|
||||
log::trace!("Gradient migration measurement compile: {e}");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let type_delta = match result {
|
||||
Err((incomplete_delta, e)) => {
|
||||
// Clear the click targets while the graph is in an un-renderable state
|
||||
if let Err(e) = &result {
|
||||
// Clear the click targets while the graph is in an un-renderable state
|
||||
|
||||
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
|
||||
document.network_interface.update_outlines(HashMap::new());
|
||||
document.network_interface.update_vector_modify(HashMap::new());
|
||||
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
|
||||
document.network_interface.update_outlines(HashMap::new());
|
||||
document.network_interface.update_vector_modify(HashMap::new());
|
||||
|
||||
// The graph only shows errors tied to nodes, so the console gets the others
|
||||
if node_graph_errors.is_empty() {
|
||||
log::error!("The node graph failed to compile:\n{e}");
|
||||
} else {
|
||||
log::trace!("{e}");
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::UpdateTypes {
|
||||
resolved_types: incomplete_delta,
|
||||
node_graph_errors,
|
||||
node_graph_warnings,
|
||||
});
|
||||
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
break;
|
||||
// The graph only shows errors tied to nodes, so the console gets the others
|
||||
if node_graph_errors.is_empty() {
|
||||
log::error!("The node graph failed to compile:\n{e}");
|
||||
} else {
|
||||
log::trace!("{e}");
|
||||
}
|
||||
Ok(result) => result,
|
||||
};
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::UpdateTypes {
|
||||
resolved_types: type_delta,
|
||||
resolved_types,
|
||||
node_graph_errors,
|
||||
node_graph_warnings,
|
||||
});
|
||||
|
||||
if result.is_err() {
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
}
|
||||
}
|
||||
NodeGraphUpdate::EyedropperPreview(raster) => {
|
||||
let (data, width, height) = raster.to_flat_u8();
|
||||
@@ -752,33 +779,7 @@ impl NodeGraphExecutor {
|
||||
Self::receive_thumbnails(document, thumbnails, responses);
|
||||
}
|
||||
}
|
||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
||||
}
|
||||
}
|
||||
|
||||
// An error leaves the later responses unapplied, but the runtime still dropped and rendered their thumbnails
|
||||
for response in results {
|
||||
match response {
|
||||
NodeGraphUpdate::ExecutionResponse(execution_response) => {
|
||||
let execution_context = self.execution_context(execution_response.execution_id);
|
||||
|
||||
if execution_context.is_some_and(|context| context.document_id == document_id) {
|
||||
document.layers_in_view.forget_thumbnails(&execution_response.dropped_thumbnails, responses);
|
||||
}
|
||||
if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) {
|
||||
responses.add(export_failure_dialog(None));
|
||||
}
|
||||
|
||||
all_dropped_thumbnails.extend(execution_response.dropped_thumbnails);
|
||||
}
|
||||
NodeGraphUpdate::Thumbnails {
|
||||
responses: thumbnails,
|
||||
document_id: thumbnails_document,
|
||||
} if thumbnails_document == document_id => {
|
||||
Self::receive_thumbnails(document, thumbnails, responses);
|
||||
}
|
||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
||||
_ => {}
|
||||
NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, responses),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -794,15 +795,6 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/// What an execution was submitted for, while it's still queued or pending.
|
||||
fn execution_context(&self, execution_id: u64) -> Option<&ExecutionContext> {
|
||||
self.futures
|
||||
.iter()
|
||||
.chain(&self.pending)
|
||||
.find(|(queued_execution_id, _)| *queued_execution_id == execution_id)
|
||||
.map(|(_, execution_context)| execution_context)
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
|
||||
/// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still
|
||||
@@ -837,6 +829,23 @@ impl NodeGraphExecutor {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn update_graph_ui(&mut self, change: impl FnOnce(&mut GraphUiSceneEdit)) -> bool {
|
||||
let mut edit = std::mem::take(&mut self.graph_ui_scene).edit();
|
||||
change(&mut edit);
|
||||
let (scene, delta) = edit.finish();
|
||||
self.graph_ui_scene = scene;
|
||||
|
||||
let changed = !delta.is_empty();
|
||||
if changed {
|
||||
self.sender.send(GraphRuntimeRequest::GraphUi(delta)).expect("Failed to send the graph UI delta");
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub fn forget_canvas_images(&mut self) {
|
||||
self.canvas_images_sent.clear();
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Run the graph with its export chain redirected down to the (possibly nested) Fill at `network_path`/`fill_node_id`
|
||||
/// (so its branch evaluates even when hidden or orphaned) and that node inspected, so its evaluated geometry returns
|
||||
@@ -872,6 +881,10 @@ impl NodeGraphExecutor {
|
||||
return;
|
||||
}
|
||||
|
||||
let layers = document.network_interface.layer_paths();
|
||||
prepare_network(&mut network, &[], &layers);
|
||||
let thumbnails = thumbnail_sources(&network, &layers);
|
||||
|
||||
let resources = document.resources.registry.clone();
|
||||
let fill_measurement = Observation {
|
||||
node_path: full_path,
|
||||
@@ -883,8 +896,7 @@ impl NodeGraphExecutor {
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
thumbnails,
|
||||
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
|
||||
}))
|
||||
.is_err()
|
||||
@@ -912,11 +924,10 @@ impl NodeGraphExecutor {
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
};
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
let execution_id = self.queue_execution(render_config, None);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: None,
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: Some((network_path, fill_node_id, gradient)),
|
||||
@@ -1076,6 +1087,51 @@ impl NodeGraphExecutor {
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
|
||||
}
|
||||
|
||||
fn receive_export(&mut self, export_id: u64, result: ExecutionResult, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let Some(target) = self.exports.remove(&export_id) else { return };
|
||||
|
||||
let failure = match (result, &target) {
|
||||
(ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _), _) => {
|
||||
return match target {
|
||||
ExportTarget::File(export_config) => self.process_export(value, export_config, document, responses),
|
||||
ExportTarget::Clipboard(id) => {
|
||||
let svg = match value {
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Svg { svg, .. },
|
||||
..
|
||||
}) => Some(svg),
|
||||
_ => None,
|
||||
};
|
||||
responses.add(ClipboardMessage::Rendered { id, svg });
|
||||
}
|
||||
};
|
||||
}
|
||||
(ExecutionResult::Error(errors), _) => Some(errors.to_string()),
|
||||
(ExecutionResult::Panic(payload), _) => {
|
||||
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
|
||||
Some(format!("Panicked: {}", message.unwrap_or("no message")))
|
||||
}
|
||||
(ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled, _) => None,
|
||||
};
|
||||
if let Some(message) = &failure {
|
||||
log::error!("Node graph evaluation failed:\n{message}");
|
||||
}
|
||||
|
||||
match target {
|
||||
ExportTarget::File(_) => responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Unable to export document".to_string(),
|
||||
description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
|
||||
}),
|
||||
ExportTarget::Clipboard(id) => {
|
||||
responses.add(ClipboardMessage::Rendered { id, svg: None });
|
||||
if let Some(description) = failure {
|
||||
let title = "Unable to copy as SVG".to_string();
|
||||
responses.add(DialogMessage::DisplayDialogError { title, description });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let ExportConfig {
|
||||
file_type,
|
||||
@@ -1175,6 +1231,61 @@ pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[Node
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_network(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)], layers: &[Vec<NodeId>]) {
|
||||
apply_previews(network, previewed);
|
||||
write_layer_paths(network, layers);
|
||||
}
|
||||
|
||||
/// Replaces each network's primary export with its previewed node.
|
||||
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
|
||||
for (network_path, previewed) in previewed {
|
||||
let Some(nested) = network.nested_network_mut(network_path) else { continue };
|
||||
let Some(export) = nested.exports.first_mut() else { continue };
|
||||
*export = NodeInput::node(previewed.node_id, previewed.output_index);
|
||||
}
|
||||
}
|
||||
|
||||
/// The node giving the content each layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
||||
fn thumbnail_sources(network: &NodeNetwork, layers: &[Vec<NodeId>]) -> Vec<(NodeId, Vec<NodeId>)> {
|
||||
// O(layers * depth)
|
||||
let source = |layer: &Vec<NodeId>| Some((*layer.last()?, layer_content(layer, network)?.source(network)?));
|
||||
|
||||
layers.iter().filter_map(source).collect()
|
||||
}
|
||||
|
||||
fn copied_layers(interface: &NodeNetworkInterface, layers: &[LayerNodeIdentifier]) -> Option<(NodeNetwork, [DVec2; 2])> {
|
||||
let metadata = interface.document_metadata();
|
||||
let is_artboard = |layer: &LayerNodeIdentifier| interface.is_artboard(&layer.to_node(), &[]);
|
||||
let stack = match layers.iter().filter(|layer| is_artboard(layer)).count() {
|
||||
0 if layers.iter().all(|layer| interface.is_merge(&layer.to_node(), &[])) => list!(Graphic),
|
||||
artboards if artboards == layers.len() => list!(Artboard),
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let mut network = interface.document_network().clone();
|
||||
prepare_network(&mut network, &interface.previewed_nodes(), &interface.layer_paths());
|
||||
let mut below = NodeInput::type_default(stack, true);
|
||||
let mut bounds = None;
|
||||
for &layer in layers {
|
||||
let mut node = network.nodes.get(&layer.to_node())?.clone();
|
||||
*node.inputs.first_mut()? = below;
|
||||
let copy = NodeId::new();
|
||||
network.nodes.insert(copy, node);
|
||||
below = NodeInput::node(copy, 0);
|
||||
|
||||
let from_document = match metadata.upstream_footprints.contains_key(&layer.to_node()) {
|
||||
true => metadata.downstream_transform_to_document(layer).inverse(),
|
||||
false => DAffine2::IDENTITY,
|
||||
};
|
||||
let in_document = metadata.bounding_box_document_with_stroke_and_effects(layer);
|
||||
let own = in_document.map(|bounds| (from_document * Quad::from_box(bounds)).bounding_box());
|
||||
bounds = [bounds, own].into_iter().flatten().reduce(Quad::combine_bounds);
|
||||
}
|
||||
network.exports = vec![below];
|
||||
|
||||
Some((network, bounds?))
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
|
||||
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
|
||||
@@ -1196,36 +1307,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
||||
None
|
||||
}
|
||||
|
||||
/// The render of an export framed to these bounds in document space, drawn at `scale` pixels per unit.
|
||||
fn export_render_config(bounds: [DVec2; 2], scale: f64, export_format: ExportFormat) -> RenderConfig {
|
||||
let resolution = ((bounds[1] - bounds[0]) * scale).round().as_uvec2();
|
||||
let viewport = Footprint {
|
||||
resolution,
|
||||
transform: DAffine2::from_translation(bounds[0]).inverse(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
RenderConfig {
|
||||
viewport,
|
||||
scale,
|
||||
time: Default::default(),
|
||||
pointer: DVec2::ZERO,
|
||||
export_format,
|
||||
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
|
||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
|
||||
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
||||
DialogMessage::DisplayDialogError {
|
||||
title: "Unable to export document".to_string(),
|
||||
description: evaluation_error.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
|
||||
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
|
||||
|
||||
@@ -1283,6 +1364,10 @@ mod test {
|
||||
self.evaluation_errors.take()
|
||||
}
|
||||
|
||||
pub fn graph_ui_scene(&self) -> &GraphUiScene {
|
||||
&self.graph_ui_scene
|
||||
}
|
||||
|
||||
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
|
||||
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
|
||||
// We should always invalidate the cache.
|
||||
@@ -1291,14 +1376,17 @@ mod test {
|
||||
network.inline_definitions().map_err(|error| error.to_string())?;
|
||||
let instrumented = Instrumented::new(&network);
|
||||
|
||||
let layers = document.network_interface.layer_paths();
|
||||
prepare_network(&mut network, &[], &layers);
|
||||
let thumbnails = thumbnail_sources(&network, &layers);
|
||||
|
||||
let resources = document.resources.registry.clone();
|
||||
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
thumbnails,
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -11,15 +11,15 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).unwrap();
|
||||
executor
|
||||
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO, None)
|
||||
.unwrap();
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
editor.dispatch(Message::Wake);
|
||||
}
|
||||
|
||||
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops
|
||||
/// for one more update, so a first update clears those of the graph before it.
|
||||
/// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network
|
||||
/// an update replaces for one more update, so a first update clears the nodes of the graph before it.
|
||||
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
|
||||
compile_and_run(editor).await;
|
||||
compile_and_run(editor).await;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,9 +1,9 @@
|
||||
use super::{artboard_clip_bounds, evaluated_output};
|
||||
use super::evaluated_output;
|
||||
use crate::messages::frontend::FrontendMessage;
|
||||
use atlas::ThumbnailAtlasLayout;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::application_io::{ApplicationIo, Texture};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::gradient::Gradient;
|
||||
@@ -17,8 +17,7 @@ use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::layer_paths::layer_content;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
mod atlas;
|
||||
@@ -41,22 +40,17 @@ pub struct Thumbnails {
|
||||
sources: HashMap<NodeId, NodeId>,
|
||||
/// The layers whose content changed since their thumbnail was last rendered.
|
||||
stale: HashSet<NodeId>,
|
||||
/// The layers whose thumbnails the frontend shows, the only ones rendered.
|
||||
in_view: HashSet<NodeId>,
|
||||
in_layers_panel: HashSet<NodeId>,
|
||||
stale_in_layers_panel: HashSet<NodeId>,
|
||||
/// The device pixel ratio thumbnails are rendered at.
|
||||
scale: f64,
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
canvases: HashMap<NodeId, ThumbnailCanvases>,
|
||||
canvases: HashMap<NodeId, CanvasHandle>,
|
||||
/// The layers whose thumbnails were sent to a page that can't show the runtime's canvases.
|
||||
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
|
||||
sent: HashSet<NodeId>,
|
||||
}
|
||||
|
||||
/// A layer's thumbnail is shown in both the Layers panel and the node graph, but a canvas element can only be in one place.
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
struct ThumbnailCanvases {
|
||||
layers_panel: CanvasHandle,
|
||||
node_graph: CanvasHandle,
|
||||
graphics: Arc<BTreeMap<NodeId, Graphic>>,
|
||||
}
|
||||
|
||||
impl Thumbnails {
|
||||
@@ -64,8 +58,14 @@ impl Thumbnails {
|
||||
Self { scale: 1., ..Default::default() }
|
||||
}
|
||||
|
||||
pub fn set_in_view(&mut self, layers: HashSet<NodeId>) {
|
||||
pub fn set_in_view(&mut self, layers: HashSet<NodeId>, layers_panel: HashSet<NodeId>) {
|
||||
self.stale.extend(self.stale_in_layers_panel.extract_if(|layer| layers_panel.contains(layer)));
|
||||
self.in_view = layers;
|
||||
self.in_layers_panel = layers_panel;
|
||||
}
|
||||
|
||||
pub fn graphics(&self) -> Arc<BTreeMap<NodeId, Graphic>> {
|
||||
self.graphics.clone()
|
||||
}
|
||||
|
||||
/// Whether the layer's thumbnail is waiting to be rendered.
|
||||
@@ -83,17 +83,15 @@ impl Thumbnails {
|
||||
}
|
||||
|
||||
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
|
||||
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, executor: &DynamicExecutor) {
|
||||
// O(layers * depth)
|
||||
let sources: HashMap<NodeId, NodeId> = layer_paths
|
||||
.iter()
|
||||
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
|
||||
.collect();
|
||||
pub fn update_sources(&mut self, layers: &[(NodeId, Vec<NodeId>)], executor: &DynamicExecutor) {
|
||||
let source_map = executor.tree().source_map();
|
||||
let sources: HashMap<NodeId, NodeId> = layers.iter().filter_map(|(layer, source)| Some((*layer, source_map.get(source.as_slice())?.0))).collect();
|
||||
|
||||
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
|
||||
let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source));
|
||||
self.stale.extend(changed.map(|(layer, _)| *layer));
|
||||
self.stale.retain(|layer| sources.contains_key(layer));
|
||||
self.stale_in_layers_panel.retain(|layer| sources.contains_key(layer));
|
||||
|
||||
self.sources = sources;
|
||||
}
|
||||
@@ -115,11 +113,13 @@ impl Thumbnails {
|
||||
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
|
||||
self.sent.retain(|layer| keep_sourced(layer));
|
||||
|
||||
Arc::make_mut(&mut self.graphics).retain(|layer, _| sources.contains_key(layer));
|
||||
|
||||
dropped
|
||||
}
|
||||
|
||||
/// Renders the thumbnails of the layers in view whose content changed since they were last rendered, keeping the others stale until they come into view.
|
||||
pub async fn render_stale(&mut self, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, responses: &mut VecDeque<FrontendMessage>) {
|
||||
pub async fn render_stale(&mut self, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, responses: &mut VecDeque<FrontendMessage>) -> bool {
|
||||
let mut contents = HashMap::new();
|
||||
for layer in std::mem::take(&mut self.stale) {
|
||||
let Some(&source) = self.sources.get(&layer) else { continue };
|
||||
@@ -136,10 +136,12 @@ impl Thumbnails {
|
||||
contents.insert(layer, content);
|
||||
}
|
||||
if contents.is_empty() {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
self.stale_in_layers_panel.extend(contents.keys().filter(|layer| !self.in_layers_panel.contains(layer)));
|
||||
|
||||
self.render_with_vello(&contents, editor_api, responses).await;
|
||||
true
|
||||
}
|
||||
|
||||
/// Renders the thumbnails into atlases with Vello and shows them.
|
||||
@@ -167,39 +169,55 @@ impl Thumbnails {
|
||||
}
|
||||
};
|
||||
|
||||
self.show_atlas(&layout, texture, executor, responses).await;
|
||||
self.keep_cells(&layout, &texture, executor);
|
||||
let shown: Vec<(usize, NodeId)> = layout.layers.iter().copied().enumerate().filter(|(_, layer)| self.in_layers_panel.contains(layer)).collect();
|
||||
if !shown.is_empty() {
|
||||
self.show_atlas(&layout, &shown, texture, executor, responses).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the atlas back and draws each cell into the canvases the layer's rows show.
|
||||
/// Copies each layer's cell out of the atlas into a texture of its own for the node graph.
|
||||
fn keep_cells(&mut self, layout: &ThumbnailAtlasLayout, atlas: &Texture, executor: &wgpu_executor::WgpuExecutor) {
|
||||
let mut encoder = executor.context().device.create_command_encoder(&Default::default());
|
||||
for (index, &layer) in layout.layers.iter().enumerate() {
|
||||
let cell = executor.request_texture(layout.cell_size);
|
||||
let mut source = atlas.as_image_copy();
|
||||
let origin = layout.cell_origin(index);
|
||||
(source.origin.x, source.origin.y) = (origin.x, origin.y);
|
||||
encoder.copy_texture_to_texture(source, cell.as_image_copy(), cell.size());
|
||||
Arc::make_mut(&mut self.graphics).insert(layer, Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(cell))));
|
||||
}
|
||||
executor.context().queue.submit([encoder.finish()]);
|
||||
}
|
||||
|
||||
/// Reads the atlas back and draws each shown cell into the canvas the layer's row in the Layers panel shows.
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
|
||||
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, shown: &[(usize, NodeId)], atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
|
||||
let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await;
|
||||
let (pixels, _, _) = raster.to_flat_u8();
|
||||
|
||||
for (index, &layer) in layout.layers.iter().enumerate() {
|
||||
for &(index, layer) in shown {
|
||||
let cell_pixels = layout.cell_pixels(&pixels, index);
|
||||
let Ok(image) = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&cell_pixels), layout.cell_size.x, layout.cell_size.y) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let canvases = self.canvases(layer);
|
||||
for canvas in [&mut canvases.layers_panel, &mut canvases.node_graph] {
|
||||
canvas.set_resolution(layout.cell_size);
|
||||
let _ = canvas.context().put_image_data(&image, 0, 0);
|
||||
}
|
||||
let canvas = self.canvas(layer);
|
||||
canvas.set_resolution(layout.cell_size);
|
||||
let _ = canvas.context().put_image_data(&image, 0, 0);
|
||||
|
||||
responses.push_back(canvases.update_message(layer));
|
||||
responses.push_back(canvas_message(layer, canvas));
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the atlas back for a page that can't show the runtime's canvases, like the desktop app's, and sends each layer its cell's pixels.
|
||||
/// Reads the atlas back for a page that can't show the runtime's canvases, like the desktop app's, and sends each shown layer its cell's pixels.
|
||||
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
|
||||
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
|
||||
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, shown: &[(usize, NodeId)], atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
|
||||
let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await;
|
||||
let (pixels, _, _) = raster.to_flat_u8();
|
||||
|
||||
for (index, &layer) in layout.layers.iter().enumerate() {
|
||||
for &(index, layer) in shown {
|
||||
self.sent.insert(layer);
|
||||
responses.push_back(FrontendMessage::UpdateNodeThumbnailPixels {
|
||||
id: layer,
|
||||
@@ -211,23 +229,14 @@ impl Thumbnails {
|
||||
}
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
fn canvases(&mut self, layer: NodeId) -> &mut ThumbnailCanvases {
|
||||
self.canvases.entry(layer).or_insert_with(|| ThumbnailCanvases {
|
||||
layers_panel: CanvasHandle::new(),
|
||||
node_graph: CanvasHandle::new(),
|
||||
})
|
||||
fn canvas(&mut self, layer: NodeId) -> &mut CanvasHandle {
|
||||
self.canvases.entry(layer).or_insert_with(CanvasHandle::new)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
impl ThumbnailCanvases {
|
||||
fn update_message(&mut self, layer: NodeId) -> FrontendMessage {
|
||||
FrontendMessage::UpdateNodeThumbnailCanvases {
|
||||
id: layer,
|
||||
layers_panel_canvas_id: self.layers_panel.id(),
|
||||
node_graph_canvas_id: self.node_graph.id(),
|
||||
}
|
||||
}
|
||||
fn canvas_message(layer: NodeId, canvas: &mut CanvasHandle) -> FrontendMessage {
|
||||
FrontendMessage::UpdateNodeThumbnailCanvas { id: layer, canvas_id: canvas.id() }
|
||||
}
|
||||
|
||||
enum ThumbnailContent {
|
||||
@@ -276,11 +285,11 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/// The area the content covers once rendered.
|
||||
/// The area the content covers once rendered, counting the effects drawn through maps and images.
|
||||
fn content_bounds(&self) -> RenderBoundingBox {
|
||||
match self {
|
||||
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
|
||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics),
|
||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, true),
|
||||
// The clipping rectangles rather than the content, since the renderer clips content to them
|
||||
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
||||
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
|
||||
@@ -297,13 +306,6 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||
let source = layer_content(layer_path, network)?.source(network)?;
|
||||
|
||||
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
|
||||
}
|
||||
|
||||
/// Converts the other kinds of graphical content into a graphic.
|
||||
fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
|
||||
macro_rules! downcast_into_graphic {
|
||||
@@ -329,6 +331,25 @@ fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
|
||||
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
|
||||
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
|
||||
let mut combined: Option<[DVec2; 2]> = None;
|
||||
for index in 0..artboards.len() {
|
||||
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
|
||||
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
|
||||
let bounds = [location, location + dimensions];
|
||||
combined = Some(match combined {
|
||||
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
||||
None => bounds,
|
||||
});
|
||||
}
|
||||
match combined {
|
||||
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
||||
None => RenderBoundingBox::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Expands an AABB outward (centered) to match the Layers panel thumbnail's 3:2 aspect ratio, padding the smaller axis
|
||||
/// so the input's extent is always preserved.
|
||||
fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
@@ -360,7 +381,7 @@ mod tests {
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).unwrap();
|
||||
executor
|
||||
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO, None)
|
||||
.unwrap();
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
|
||||
@@ -63,6 +63,7 @@ pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout,
|
||||
let render_params = RenderParams {
|
||||
footprint: Footprint::BOUNDLESS,
|
||||
render_output_type: RenderOutputType::Vello,
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let cell_size = layout.cell_size.as_dvec2();
|
||||
|
||||
+28
-32
@@ -75,7 +75,7 @@ impl EditorTestUtils {
|
||||
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
|
||||
};
|
||||
|
||||
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
|
||||
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO, None) {
|
||||
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
|
||||
}
|
||||
self.runtime.update();
|
||||
@@ -90,13 +90,22 @@ impl EditorTestUtils {
|
||||
return Err(TestGraphError::Evaluation(errors));
|
||||
}
|
||||
|
||||
for message in frontend_messages {
|
||||
message.check_node_graph_error();
|
||||
}
|
||||
self.check_node_graph_errors();
|
||||
|
||||
Ok(instrumented)
|
||||
}
|
||||
|
||||
fn check_node_graph_errors(&self) {
|
||||
let document = self.active_document();
|
||||
if !document.graph_view_overlay_open {
|
||||
return;
|
||||
}
|
||||
let errors = document.node_graph_handler.node_graph_errors(&document.network_interface, document.breadcrumb_network_path());
|
||||
if !errors.is_empty() {
|
||||
panic!("errors: {errors:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
|
||||
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
|
||||
const MAX_ITERATIONS: usize = 16;
|
||||
@@ -117,17 +126,10 @@ impl EditorTestUtils {
|
||||
panic!("Failed to evaluate graph: {e}");
|
||||
}
|
||||
|
||||
// The copied layers' SVG waits for the readbacks of the GPU images it holds, each landing before a later run
|
||||
let mut frontend_messages = self.dispatch(message);
|
||||
for _ in 0..100 {
|
||||
self.runtime.update();
|
||||
self.runtime.run().await;
|
||||
frontend_messages.extend(self.dispatch(Message::Wake));
|
||||
|
||||
if frontend_messages.iter().any(|message| matches!(message, FrontendMessage::TriggerClipboardWrite { .. })) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.runtime.update();
|
||||
self.runtime.run().await;
|
||||
frontend_messages.extend(self.dispatch(Message::Wake));
|
||||
|
||||
frontend_messages
|
||||
.into_iter()
|
||||
@@ -290,12 +292,11 @@ impl EditorTestUtils {
|
||||
|
||||
/// Sets the clock to a time in milliseconds and runs one animation frame, as the frontend does on each `requestAnimationFrame`.
|
||||
pub async fn animation_frame(&mut self, timestamp: u64) {
|
||||
let messages = Box::new([
|
||||
InputPreprocessorMessage::CurrentTime { timestamp }.into(),
|
||||
AnimationMessage::IncrementFrameCounter.into(),
|
||||
BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(),
|
||||
]);
|
||||
self.handle_message(Message::Batched { messages }).await;
|
||||
self.handle_message(animation_frame_batch(timestamp)).await;
|
||||
}
|
||||
|
||||
pub fn dispatch_animation_frame(&mut self, timestamp: u64) {
|
||||
self.dispatch(animation_frame_batch(timestamp));
|
||||
}
|
||||
|
||||
pub async fn left_mousedown(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys) {
|
||||
@@ -454,17 +455,13 @@ impl EditorTestUtils {
|
||||
}
|
||||
}
|
||||
|
||||
pub trait FrontendMessageTestUtils {
|
||||
fn check_node_graph_error(&self);
|
||||
}
|
||||
|
||||
impl FrontendMessageTestUtils for FrontendMessage {
|
||||
fn check_node_graph_error(&self) {
|
||||
let FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors } = self else { return };
|
||||
if !errors.is_empty() {
|
||||
panic!("errors: {errors:?}");
|
||||
}
|
||||
}
|
||||
fn animation_frame_batch(timestamp: u64) -> Message {
|
||||
let messages = Box::new([
|
||||
InputPreprocessorMessage::CurrentTime { timestamp }.into(),
|
||||
AnimationMessage::IncrementFrameCounter.into(),
|
||||
BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(),
|
||||
]);
|
||||
Message::Batched { messages }
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -561,7 +558,6 @@ impl Spawn for BlockingSpawner {
|
||||
|
||||
#[cfg(test)]
|
||||
pub mod test_prelude {
|
||||
pub use super::FrontendMessageTestUtils;
|
||||
pub use crate::application::Editor;
|
||||
pub use crate::float_eq;
|
||||
pub use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
|
||||
|
||||
@@ -680,7 +680,7 @@
|
||||
{:else if ["Fallback", "Error", "Panic"].includes($document.renderStatus)}
|
||||
<div class="render-status-outline failed"></div>
|
||||
{/if}
|
||||
{#if $document.renderStatus === "Error"}
|
||||
{#if $document.renderStatus === "Error" && !$document.graphViewOverlayOpen}
|
||||
<LayoutCol class="render-status-overlay">
|
||||
<TextLabel>
|
||||
<p>
|
||||
@@ -703,7 +703,7 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="graph-view" class:open={$document.graphViewOverlayOpen} style:--fade-artwork={`${$document.fadeArtwork}%`} data-graph>
|
||||
<div class="graph-view" class:open={$document.graphViewOverlayOpen}>
|
||||
<Graph />
|
||||
</div>
|
||||
</LayoutCol>
|
||||
@@ -1005,7 +1005,6 @@
|
||||
|
||||
.graph-view {
|
||||
pointer-events: none;
|
||||
transition: opacity 0.2s;
|
||||
opacity: 0;
|
||||
|
||||
&.open {
|
||||
@@ -1013,21 +1012,8 @@
|
||||
pointer-events: auto;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
&::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: var(--color-2-mildblack);
|
||||
opacity: var(--fade-artwork);
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
.fade-artwork,
|
||||
.graph {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
|
||||
@@ -1247,7 +1247,7 @@
|
||||
{/if}
|
||||
<div class="thumbnail">
|
||||
{#if $nodeGraph.thumbnailCanvases.has(listing.id)}
|
||||
<ThumbnailCanvas canvasId={$nodeGraph.thumbnailCanvases.get(listing.id)?.layersPanelCanvasId} />
|
||||
<ThumbnailCanvas canvasId={$nodeGraph.thumbnailCanvases.get(listing.id)} />
|
||||
{:else if $thumbnailImages.has(listing.id)}
|
||||
<ThumbnailImage image={$thumbnailImages.get(listing.id)} />
|
||||
{/if}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,28 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type { Readable } from "svelte/store";
|
||||
import type { WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export let wire: Readable<WirePath>;
|
||||
export let thick: boolean;
|
||||
export let undimmed: boolean;
|
||||
|
||||
$: dataColor = `var(--color-data-${$wire.dataType.toLowerCase()})`;
|
||||
$: dataColorDim = `var(--color-data-${$wire.dataType.toLowerCase()}-dim)`;
|
||||
$: dasharray = `3,${$wire.dashed ? 2 : 0}`;
|
||||
</script>
|
||||
|
||||
{#if $wire.thick === thick}
|
||||
<g class:dashed={$wire.dashed} class:undimmed>
|
||||
{#if thick}
|
||||
<path d={$wire.pathString} style:--data-line-width="8px" style:--data-color={dataColor} style:--data-color-dim={dataColorDim} style:--data-dasharray={dasharray} />
|
||||
<!-- A thin inner line splits the layer-stack wire down the middle reaching past the ends into the cleaved connector slots -->
|
||||
<path d={$wire.centerPathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={dasharray} />
|
||||
{:else if $wire.isList}
|
||||
<!-- A rank-1 List wire reads as two parallel lines: a triple-width data line split down the middle by a 1x background-colored overlay -->
|
||||
<path d={$wire.pathString} style:--data-line-width="4px" style:--data-color={dataColor} style:--data-color-dim={dataColorDim} style:--data-dasharray={dasharray} />
|
||||
<path d={$wire.pathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={dasharray} />
|
||||
{:else}
|
||||
<path d={$wire.pathString} style:--data-line-width="2px" style:--data-color={dataColor} style:--data-color-dim={dataColorDim} style:--data-dasharray={dasharray} />
|
||||
{/if}
|
||||
</g>
|
||||
{/if}
|
||||
@@ -558,10 +558,9 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// A label with no expose button before it lines up with the parameter names that follow one
|
||||
> .text-label:first-child {
|
||||
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||
> .text-label:only-child {
|
||||
margin-left: calc(20px + 8px + 8px);
|
||||
--wire-indent: 20px;
|
||||
}
|
||||
|
||||
> .separator.horizontal.unrelated {
|
||||
|
||||
@@ -191,6 +191,7 @@ import NodeFlattenGradient from "/../branding/assets/16x16-nodes/node-flatten-gr
|
||||
import NodeFlattenRaster from "/../branding/assets/16x16-nodes/node-flatten-raster.svg";
|
||||
import NodeFlattenVector from "/../branding/assets/16x16-nodes/node-flatten-vector.svg";
|
||||
import NodeFloor from "/../branding/assets/16x16-nodes/node-floor.svg";
|
||||
import NodeFootprintValue from "/../branding/assets/16x16-nodes/node-footprint-value.svg";
|
||||
import NodeFormatJson from "/../branding/assets/16x16-nodes/node-format-json.svg";
|
||||
import NodeFormatNumber from "/../branding/assets/16x16-nodes/node-format-number.svg";
|
||||
import NodeGammaCorrection from "/../branding/assets/16x16-nodes/node-gamma-correction.svg";
|
||||
@@ -484,6 +485,7 @@ export const ICON_16X16_NODES = {
|
||||
NodeFlattenRaster: { svg: NodeFlattenRaster, size: 16 },
|
||||
NodeFlattenVector: { svg: NodeFlattenVector, size: 16 },
|
||||
NodeFloor: { svg: NodeFloor, size: 16 },
|
||||
NodeFootprintValue: { svg: NodeFootprintValue, size: 16 },
|
||||
NodeFormatJson: { svg: NodeFormatJson, size: 16 },
|
||||
NodeFormatNumber: { svg: NodeFormatNumber, size: 16 },
|
||||
NodeGammaCorrection: { svg: NodeGammaCorrection, size: 16 },
|
||||
|
||||
@@ -14,7 +14,6 @@ type DocumentStoreState = {
|
||||
workingColorsLayout: Layout;
|
||||
nodeGraphControlBarLayout: Layout;
|
||||
graphViewOverlayOpen: boolean;
|
||||
fadeArtwork: number;
|
||||
renderStatus: RenderStatus;
|
||||
};
|
||||
const initialState: DocumentStoreState = {
|
||||
@@ -24,7 +23,6 @@ const initialState: DocumentStoreState = {
|
||||
workingColorsLayout: createLayout(),
|
||||
nodeGraphControlBarLayout: createLayout(),
|
||||
graphViewOverlayOpen: false,
|
||||
fadeArtwork: 100,
|
||||
renderStatus: "Rendering",
|
||||
};
|
||||
|
||||
@@ -44,13 +42,6 @@ export function createDocumentStore(subscriptions: SubscriptionsRouter) {
|
||||
|
||||
subscriptionsRouter = subscriptions;
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateGraphFadeArtwork", (data) => {
|
||||
update((state) => {
|
||||
state.fadeArtwork = data.percentage;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeLayoutUpdate("ToolOptions", (data) => {
|
||||
patchLayout(get(store).toolOptionsLayout, data);
|
||||
});
|
||||
@@ -99,7 +90,6 @@ export function destroyDocumentStore() {
|
||||
const subscriptions = subscriptionsRouter;
|
||||
if (!subscriptions) return;
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateGraphFadeArtwork");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateGraphViewOverlay");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateRenderStatus");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateRemoteCursors");
|
||||
|
||||
@@ -1,59 +1,27 @@
|
||||
import { get, writable } from "svelte/store";
|
||||
import type { Writable } from "svelte/store";
|
||||
import type { IconName } from "/src/icons";
|
||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import type { MessageBody } from "/src/subscriptions-router";
|
||||
import type { NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { ContextMenuInformation, FrontendNodeType } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
|
||||
|
||||
export type NodeGraphTransform = { scale: number; x: number; y: number };
|
||||
|
||||
export type ThumbnailCanvases = { layersPanelCanvasId: number; nodeGraphCanvasId: number };
|
||||
|
||||
type NodeGraphStoreState = {
|
||||
box: BoxSelection | undefined;
|
||||
contextMenuInformation: ContextMenuInformation | undefined;
|
||||
errors: NodeGraphErrorDiagnostic[];
|
||||
layerWidths: Map<bigint, number>;
|
||||
chainWidths: Map<bigint, number>;
|
||||
hasLeftInputWire: Map<bigint, boolean>;
|
||||
nodes: Map<bigint, FrontendNode>;
|
||||
wirePathInProgress: WirePath | undefined;
|
||||
wireInProgressDraggedFrom: [number, number] | undefined;
|
||||
wireInProgressSnappedTo: [number, number] | undefined;
|
||||
hoveredConnector: [number, number] | undefined;
|
||||
nodeDescriptions: Map<string, string>;
|
||||
nodeIcons: Map<string, IconName>;
|
||||
nodeTypes: FrontendNodeType[];
|
||||
thumbnailCanvases: Map<bigint, ThumbnailCanvases>;
|
||||
thumbnailCanvases: Map<bigint, number>;
|
||||
selected: bigint[];
|
||||
inSelectedNetwork: boolean;
|
||||
readOnly: boolean;
|
||||
reorderImportIndex: number | undefined;
|
||||
reorderExportIndex: number | undefined;
|
||||
};
|
||||
const initialState: NodeGraphStoreState = {
|
||||
box: undefined,
|
||||
contextMenuInformation: undefined,
|
||||
errors: [],
|
||||
layerWidths: new Map(),
|
||||
chainWidths: new Map(),
|
||||
hasLeftInputWire: new Map(),
|
||||
nodes: new Map(),
|
||||
wirePathInProgress: undefined,
|
||||
wireInProgressDraggedFrom: undefined,
|
||||
wireInProgressSnappedTo: undefined,
|
||||
hoveredConnector: undefined,
|
||||
nodeDescriptions: new Map(),
|
||||
nodeIcons: new Map(),
|
||||
nodeTypes: [],
|
||||
thumbnailCanvases: new Map(),
|
||||
selected: [],
|
||||
inSelectedNetwork: true,
|
||||
readOnly: false,
|
||||
reorderImportIndex: undefined,
|
||||
reorderExportIndex: undefined,
|
||||
};
|
||||
|
||||
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
|
||||
@@ -83,36 +51,14 @@ const store: Writable<NodeGraphStoreState> = import.meta.hot?.data?.store || wri
|
||||
if (import.meta.hot) import.meta.hot.data.store = store;
|
||||
const { subscribe, update } = store;
|
||||
|
||||
// Separate transform store so pan/zoom updates don't trigger re-rendering the entire node graph
|
||||
// Separate transform store so a pan or zoom re-renders only the menus and fields placed in graph space
|
||||
const transformStore: Writable<NodeGraphTransform> = import.meta.hot?.data?.transformStore || writable<NodeGraphTransform>({ scale: 1, x: 0, y: 0 });
|
||||
if (import.meta.hot) import.meta.hot.data.transformStore = transformStore;
|
||||
|
||||
// Separate imports/exports store so viewport-anchored position updates don't trigger node re-renders
|
||||
const importsExportsStore: Writable<MessageBody<"UpdateImportsExports"> | undefined> = import.meta.hot?.data?.importsExportsStore || writable(undefined);
|
||||
if (import.meta.hot) import.meta.hot.data.importsExportsStore = importsExportsStore;
|
||||
|
||||
// Kept apart from the node graph state so a thumbnail update doesn't re-render every node
|
||||
// Kept apart from the node graph state so a thumbnail update doesn't re-render every row of the Layers panel
|
||||
const thumbnailImagesStore: Writable<Map<bigint, ImageData>> = import.meta.hot?.data?.thumbnailImagesStore || writable(new Map());
|
||||
if (import.meta.hot) import.meta.hot.data.thumbnailImagesStore = thumbnailImagesStore;
|
||||
|
||||
// Separate visible nodes store so viewport culling changes don't trigger full node re-renders
|
||||
const visibleNodesStore: Writable<Set<bigint>> = import.meta.hot?.data?.visibleNodesStore || writable(new Set());
|
||||
if (import.meta.hot) import.meta.hot.data.visibleNodesStore = visibleNodesStore;
|
||||
|
||||
// Separate wires store so wire path updates (e.g. export connector movement during pan) don't trigger node re-renders.
|
||||
// It only changes when wires are added or removed, since each wire's path is kept in its own store so updating it only re-renders that wire.
|
||||
const wiresStore: Writable<Map<bigint, Map<number, Writable<WirePath>>>> = import.meta.hot?.data?.wiresStore || writable(new Map());
|
||||
if (import.meta.hot) import.meta.hot.data.wiresStore = wiresStore;
|
||||
|
||||
// Separate wire insertion preview store so the wires don't re-render with every node graph update
|
||||
const wireInsertionPreviewStore: Writable<[bigint, number] | undefined> = import.meta.hot?.data?.wireInsertionPreviewStore || writable(undefined);
|
||||
if (import.meta.hot) import.meta.hot.data.wireInsertionPreviewStore = wireInsertionPreviewStore;
|
||||
|
||||
// Separate glide offsets store so the per-frame offsets of whatever is gliding into the place it moved to don't trigger full node re-renders
|
||||
export type GlideOffsets = { nodes: Map<bigint, [number, number]>; imports: [number, number]; exports: [number, number] };
|
||||
const glideOffsetsStore: Writable<GlideOffsets> = import.meta.hot?.data?.glideOffsetsStore || writable<GlideOffsets>({ nodes: new Map(), imports: [0, 0], exports: [0, 0] });
|
||||
if (import.meta.hot) import.meta.hot.data.glideOffsetsStore = glideOffsetsStore;
|
||||
|
||||
export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
destroyNodeGraphStore();
|
||||
|
||||
@@ -121,19 +67,11 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
subscriptions.subscribeFrontendMessage("SendUIMetadata", (data) => {
|
||||
update((state) => {
|
||||
state.nodeDescriptions = new Map(data.nodeDescriptions);
|
||||
state.nodeIcons = new Map(data.nodeIcons);
|
||||
state.nodeTypes = data.nodeTypes;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateBox", (data) => {
|
||||
update((state) => {
|
||||
state.box = data.box;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => {
|
||||
update((state) => {
|
||||
state.contextMenuInformation = data.contextMenuInformation;
|
||||
@@ -141,42 +79,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateImportReorderIndex", (data) => {
|
||||
update((state) => {
|
||||
state.reorderImportIndex = data.importIndex;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateExportReorderIndex", (data) => {
|
||||
update((state) => {
|
||||
state.reorderExportIndex = data.exportIndex;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateWireInsertionPreview", (data) => {
|
||||
wireInsertionPreviewStore.set(data.wire);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateHoveredConnector", (data) => {
|
||||
update((state) => {
|
||||
state.hoveredConnector = data.center;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateImportsExports", (data) => {
|
||||
importsExportsStore.set(data);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateInSelectedNetwork", (data) => {
|
||||
update((state) => {
|
||||
state.inSelectedNetwork = data.inSelectedNetwork;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateNetworkReadOnly", (data) => {
|
||||
update((state) => {
|
||||
state.readOnly = data.readOnly;
|
||||
@@ -184,86 +86,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateLayerWidths", (data) => {
|
||||
update((state) => {
|
||||
state.layerWidths = data.layerWidths;
|
||||
state.chainWidths = data.chainWidths;
|
||||
state.hasLeftInputWire = data.hasLeftInputWire;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateNodeGraphNodes", (data) => {
|
||||
update((state) => {
|
||||
state.nodes.clear();
|
||||
data.nodes.forEach((node) => {
|
||||
state.nodes.set(node.id, node);
|
||||
});
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics", (data) => {
|
||||
update((state) => {
|
||||
state.errors = data.errors;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => {
|
||||
const newNodes = new Set<bigint>(data.nodes);
|
||||
|
||||
// Short-circuit when the visible set hasn't changed to avoid unnecessary re-renders
|
||||
let changed = false;
|
||||
const unsubscribe = visibleNodesStore.subscribe((current) => {
|
||||
if (current.size !== newNodes.size) {
|
||||
changed = true;
|
||||
} else {
|
||||
newNodes.forEach((node) => {
|
||||
if (!current.has(node)) changed = true;
|
||||
});
|
||||
}
|
||||
});
|
||||
unsubscribe();
|
||||
|
||||
if (!changed) return;
|
||||
|
||||
visibleNodesStore.set(newNodes);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateGlideOffsets", (data) => {
|
||||
glideOffsetsStore.set({ nodes: new Map(data.nodes), imports: data.imports, exports: data.exports });
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateNodeGraphWires", (data) => {
|
||||
const wires = get(wiresStore);
|
||||
let wiresChanged = false;
|
||||
|
||||
data.wires.forEach(({ id, inputIndex, wirePathUpdate }) => {
|
||||
let inputMap = wires.get(id);
|
||||
const wire = inputMap?.get(inputIndex);
|
||||
|
||||
if (wirePathUpdate === undefined) {
|
||||
if (inputMap?.delete(inputIndex)) wiresChanged = true;
|
||||
} else if (wire) {
|
||||
wire.set(wirePathUpdate);
|
||||
} else {
|
||||
if (!inputMap) {
|
||||
inputMap = new Map();
|
||||
wires.set(id, inputMap);
|
||||
}
|
||||
inputMap.set(inputIndex, writable(wirePathUpdate));
|
||||
wiresChanged = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (wiresChanged) wiresStore.set(wires);
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("ClearAllNodeGraphWires", () => {
|
||||
wiresStore.set(new Map());
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateNodeGraphSelection", (data) => {
|
||||
update((state) => {
|
||||
state.selected = data.selected;
|
||||
@@ -275,14 +97,11 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
transformStore.set({ scale: data.scale, x: data.translation[0], y: data.translation[1] });
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateNodeThumbnailCanvases", (data) => {
|
||||
const { id, ...canvases } = data;
|
||||
|
||||
const current = get(store).thumbnailCanvases.get(id);
|
||||
if (current?.layersPanelCanvasId === canvases.layersPanelCanvasId && current?.nodeGraphCanvasId === canvases.nodeGraphCanvasId) return;
|
||||
subscriptions.subscribeFrontendMessage("UpdateNodeThumbnailCanvas", (data) => {
|
||||
if (get(store).thumbnailCanvases.get(data.id) === data.canvasId) return;
|
||||
|
||||
update((state) => {
|
||||
state.thumbnailCanvases.set(id, canvases);
|
||||
state.thumbnailCanvases.set(data.id, data.canvasId);
|
||||
return state;
|
||||
});
|
||||
});
|
||||
@@ -303,16 +122,7 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateWirePathInProgress", (data) => {
|
||||
update((state) => {
|
||||
state.wirePathInProgress = data.wirePath;
|
||||
state.wireInProgressDraggedFrom = data.draggedFrom;
|
||||
state.wireInProgressSnappedTo = data.snappedTo;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
return { subscribe, transformStore, importsExportsStore, visibleNodesStore, thumbnailImagesStore, wiresStore, wireInsertionPreviewStore, glideOffsetsStore };
|
||||
return { subscribe, transformStore, thumbnailImagesStore };
|
||||
}
|
||||
|
||||
export function destroyNodeGraphStore() {
|
||||
@@ -320,28 +130,13 @@ export function destroyNodeGraphStore() {
|
||||
if (!subscriptions) return;
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateBox");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateWireInsertionPreview");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHoveredConnector");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateImportsExports");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateInSelectedNetwork");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNetworkReadOnly");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateVisibleNodes");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateGlideOffsets");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphWires");
|
||||
subscriptions.unsubscribeFrontendMessage("ClearAllNodeGraphWires");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphSelection");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphTransform");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailCanvases");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailCanvas");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailPixels");
|
||||
subscriptions.unsubscribeFrontendMessage("ClearNodeThumbnails");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateWirePathInProgress");
|
||||
}
|
||||
|
||||
export function closeContextMenu() {
|
||||
|
||||
@@ -29,7 +29,7 @@ type Listener = { eventName: keyof DocumentEventMap; action(event: Event): void;
|
||||
const tooltipEventListeners: Listener[] = [
|
||||
{ eventName: "mouseover", action: onMouseOver },
|
||||
{ eventName: "mousemove", action: onMouseMove },
|
||||
{ eventName: "mouseleave", action: onMouseLeave },
|
||||
{ eventName: "mouseleave", action: closeTooltip },
|
||||
{ eventName: "mousedown", action: closeTooltip },
|
||||
// Heard on the way down, since a floating menu or a field with its menu open stops these from bubbling up
|
||||
{ eventName: "keydown", action: closeTooltip, capture: true },
|
||||
@@ -38,6 +38,7 @@ const tooltipEventListeners: Listener[] = [
|
||||
|
||||
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
|
||||
let tooltipTimeout: ReturnType<typeof setTimeout> | undefined = undefined;
|
||||
let latestMouseMove: MouseEvent | undefined = undefined;
|
||||
|
||||
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
|
||||
const store: Writable<TooltipStoreState> = import.meta.hot?.data?.store || writable<TooltipStoreState>(initialState);
|
||||
@@ -107,12 +108,29 @@ function onMouseOver(e: MouseEvent) {
|
||||
|
||||
// Listen for mouse movements to schedule and position the tooltip, or hide it immediately upon further movement
|
||||
function onMouseMove(e: MouseEvent) {
|
||||
latestMouseMove = e;
|
||||
|
||||
// Hide the tooltip now that the cursor has moved
|
||||
update((state) => {
|
||||
state.visible = false;
|
||||
return state;
|
||||
});
|
||||
|
||||
scheduleTooltip(e);
|
||||
}
|
||||
|
||||
// For an element whose tooltip changes while the cursor rests on it
|
||||
export function retargetTooltip(element: Element | undefined) {
|
||||
update((state) => {
|
||||
state.visible = false;
|
||||
state.element = element;
|
||||
return state;
|
||||
});
|
||||
|
||||
if (latestMouseMove) scheduleTooltip(latestMouseMove);
|
||||
}
|
||||
|
||||
function scheduleTooltip(e: MouseEvent) {
|
||||
// Before we schedule a new future tooltip appearance, we clear the existing one
|
||||
if (tooltipTimeout) clearTimeout(tooltipTimeout);
|
||||
|
||||
@@ -131,14 +149,11 @@ function onMouseMove(e: MouseEvent) {
|
||||
}, SHOW_TOOLTIP_DELAY_MS);
|
||||
}
|
||||
|
||||
// Hide tooltip and cancel any pending timeout when the mouse leaves the application window
|
||||
function onMouseLeave() {
|
||||
if (tooltipTimeout) clearTimeout(tooltipTimeout);
|
||||
closeTooltip();
|
||||
}
|
||||
|
||||
// Stop showing a tooltip if the user clicks or presses a key, and require the user to first move out of the element before it can re-appear
|
||||
function closeTooltip() {
|
||||
if (tooltipTimeout) clearTimeout(tooltipTimeout);
|
||||
latestMouseMove = undefined;
|
||||
|
||||
update((state) => {
|
||||
state.visible = false;
|
||||
state.element = undefined;
|
||||
|
||||
@@ -188,9 +188,9 @@ export function onPointerUp(e: PointerEvent, editor: EditorWrapper) {
|
||||
export function onPotentialDoubleClick(e: MouseEvent, editor: EditorWrapper) {
|
||||
if (isObserveOnly(e) || textToolInteractiveInputElement || inPointerLock) return;
|
||||
|
||||
// Allow only events within the viewport or node graph boundaries
|
||||
// Allow only events within the viewport or node graph boundaries, but not in a text field laid over them
|
||||
const isTargetingCanvas = e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
|
||||
if (!(isTargetingCanvas instanceof Element)) return;
|
||||
if (!(isTargetingCanvas instanceof Element) || targetIsTextField(e.target || undefined)) return;
|
||||
|
||||
// Allow only double-clicks (2, 4, etc.), not 0 for a canceled click
|
||||
if (e.detail === 0 || e.detail % 2 === 1) return;
|
||||
|
||||
@@ -19,8 +19,9 @@ mod editor_commands {
|
||||
use editor::messages::input_mapper::utility_types::keyboard::ModifierKeys;
|
||||
use editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta};
|
||||
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use editor::messages::portfolio::document::node_graph::graph_ui::GraphName;
|
||||
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
|
||||
use editor::messages::portfolio::document::utility_types::network_interface::NetworkConnectorKey;
|
||||
use editor::messages::portfolio::ingest::utility_types::DataTransferItem;
|
||||
use editor::messages::portfolio::utility_types::PanelGroupId;
|
||||
use editor::messages::prelude::*;
|
||||
@@ -673,11 +674,6 @@ mod editor_commands {
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Set the name for a layer in the network shown by the node graph, which may be a subgraph
|
||||
fn set_layer_name_in_graph(id: u64, name: String) -> Message {
|
||||
DocumentMessage::SetLayerNameInGraph { node_id: NodeId(id), name }.into()
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
fn pan_canvas_abort_prepare(x_not_y_axis: bool) -> Message {
|
||||
NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis }.into()
|
||||
@@ -800,29 +796,20 @@ mod editor_commands {
|
||||
DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer }.into()
|
||||
}
|
||||
|
||||
/// Set the name of an import.
|
||||
fn set_import_name(index: usize, name: String) -> Message {
|
||||
NodeGraphMessage::SetImportExportName {
|
||||
name,
|
||||
index: ImportOrExport::Import(index),
|
||||
}
|
||||
.into()
|
||||
fn begin_network_connector_name_edit(is_import: bool, index: usize) -> Message {
|
||||
let name = GraphName::NetworkConnector(if is_import { NetworkConnectorKey::Import(index) } else { NetworkConnectorKey::Export(index) });
|
||||
NodeGraphMessage::BeginEditName { name }.into()
|
||||
}
|
||||
|
||||
/// Set the name of an export.
|
||||
fn set_export_name(index: usize, name: String) -> Message {
|
||||
NodeGraphMessage::SetImportExportName {
|
||||
name,
|
||||
index: ImportOrExport::Export(index),
|
||||
}
|
||||
.into()
|
||||
fn end_graph_name_edit(name: Option<String>) -> Message {
|
||||
NodeGraphMessage::EndEditName { name }.into()
|
||||
}
|
||||
|
||||
/// Set the description of an import.
|
||||
fn set_import_description(index: usize, description: String) -> Message {
|
||||
NodeGraphMessage::SetImportExportDescription {
|
||||
description,
|
||||
index: ImportOrExport::Import(index),
|
||||
index: NetworkConnectorKey::Import(index),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
@@ -831,7 +818,7 @@ mod editor_commands {
|
||||
fn set_export_description(index: usize, description: String) -> Message {
|
||||
NodeGraphMessage::SetImportExportDescription {
|
||||
description,
|
||||
index: ImportOrExport::Export(index),
|
||||
index: NetworkConnectorKey::Export(index),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
@@ -841,7 +828,10 @@ mod editor_commands {
|
||||
Message::Batched {
|
||||
messages: Box::new([
|
||||
DocumentMessage::AddTransaction.into(),
|
||||
NodeGraphMessage::RemoveImportExport { index: ImportOrExport::Import(index) }.into(),
|
||||
NodeGraphMessage::RemoveImportExport {
|
||||
index: NetworkConnectorKey::Import(index),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
}
|
||||
}
|
||||
@@ -851,7 +841,10 @@ mod editor_commands {
|
||||
Message::Batched {
|
||||
messages: Box::new([
|
||||
DocumentMessage::AddTransaction.into(),
|
||||
NodeGraphMessage::RemoveImportExport { index: ImportOrExport::Export(index) }.into(),
|
||||
NodeGraphMessage::RemoveImportExport {
|
||||
index: NetworkConnectorKey::Export(index),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
}
|
||||
}
|
||||
@@ -899,7 +892,10 @@ mod editor_commands {
|
||||
Message::Batched {
|
||||
messages: Box::new([
|
||||
DocumentMessage::AddTransaction.into(),
|
||||
NodeGraphMessage::DisconnectImportExport { index: ImportOrExport::Import(index) }.into(),
|
||||
NodeGraphMessage::DisconnectImportExport {
|
||||
index: NetworkConnectorKey::Import(index),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
}
|
||||
}
|
||||
@@ -909,7 +905,10 @@ mod editor_commands {
|
||||
Message::Batched {
|
||||
messages: Box::new([
|
||||
DocumentMessage::AddTransaction.into(),
|
||||
NodeGraphMessage::DisconnectImportExport { index: ImportOrExport::Export(index) }.into(),
|
||||
NodeGraphMessage::DisconnectImportExport {
|
||||
index: NetworkConnectorKey::Export(index),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ raster-nodes = { workspace = true, features = ["serde"] }
|
||||
vector-nodes = { workspace = true, features = ["serde"] }
|
||||
graphic-types = { workspace = true, features = ["serde"] }
|
||||
text-nodes = { workspace = true, features = ["serde"] }
|
||||
graph-ui-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
log = { workspace = true }
|
||||
|
||||
@@ -5,13 +5,14 @@ use brush_nodes::{BrushCache, Stroke};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor};
|
||||
pub use dyn_any::StaticType;
|
||||
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphene_application_io::resource::ResourceHash;
|
||||
use graphene_application_io::resource::ResourceId;
|
||||
use graphic_types::raster_types::{CPU, Image, Pixels, Raster};
|
||||
use graphic_types::raster_types::{CPU, Image, Raster};
|
||||
use graphic_types::vector_types::vector::misc::BoxCorners;
|
||||
use graphic_types::vector_types::vector::style::DashPattern;
|
||||
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
|
||||
@@ -74,7 +75,7 @@ macro_rules! tagged_value {
|
||||
TypeDefault(Type),
|
||||
/// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||
#[serde(deserialize_with = "core_types::misc::migrate_to_numbers")] // TODO: Eventually remove this document upgrade code
|
||||
#[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4", alias = "Footprint")]
|
||||
#[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
|
||||
Numbers(Vec<f64>),
|
||||
/// Stored compactly as a `Vec<f64>` of dash lengths, materializes as an `Item<DashPattern>` at runtime via `to_dynany`/`to_any`.
|
||||
DashPattern(Vec<f64>),
|
||||
@@ -109,6 +110,8 @@ macro_rules! tagged_value {
|
||||
Runtime(RuntimeHandle),
|
||||
#[serde(skip)]
|
||||
EditorApi(Arc<PlatformEditorApi>),
|
||||
#[serde(skip)]
|
||||
GraphUi(graph_ui_types::TaggedGraphUiValue),
|
||||
/// Only used by the `resource` node, should never be serialized
|
||||
#[serde(skip)]
|
||||
ResourceHash(ResourceHash),
|
||||
@@ -143,6 +146,7 @@ macro_rules! tagged_value {
|
||||
Self::Runtime(runtime) => runtime.cache_hash(state),
|
||||
Self::RenderOutput(x) => x.cache_hash(state),
|
||||
Self::EditorApi(x) => x.cache_hash(state),
|
||||
Self::GraphUi(x) => x.cache_hash(state),
|
||||
Self::ResourceHash(x) => x.cache_hash(state),
|
||||
}
|
||||
}
|
||||
@@ -207,6 +211,7 @@ macro_rules! tagged_value {
|
||||
Self::SourceId(source) => Box::new(Item::new_from_element(source)),
|
||||
Self::Runtime(runtime) => Box::new(Item::new_from_element(runtime)),
|
||||
Self::EditorApi(x) => Box::new(Item::new_from_element(x)),
|
||||
Self::GraphUi(x) => x.to_dynany(),
|
||||
Self::ResourceHash(x) => Box::new(Item::new_from_element(x)),
|
||||
}
|
||||
}
|
||||
@@ -267,6 +272,7 @@ macro_rules! tagged_value {
|
||||
Self::SourceId(source) => Arc::new(Item::new_from_element(source)),
|
||||
Self::Runtime(runtime) => Arc::new(Item::new_from_element(runtime)),
|
||||
Self::EditorApi(x) => Arc::new(Item::new_from_element(x)),
|
||||
Self::GraphUi(x) => x.to_any(),
|
||||
Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)),
|
||||
}
|
||||
}
|
||||
@@ -299,6 +305,7 @@ macro_rules! tagged_value {
|
||||
Self::SourceId(_) => item!(SourceId),
|
||||
Self::Runtime(_) => item!(RuntimeHandle),
|
||||
Self::EditorApi(_) => item!(Arc<PlatformEditorApi>),
|
||||
Self::GraphUi(x) => x.ty(),
|
||||
Self::ResourceHash(_) => item!(ResourceHash),
|
||||
};
|
||||
|
||||
@@ -399,11 +406,6 @@ macro_rules! tagged_value {
|
||||
Type::Fn(_, output) => TaggedValue::from_type(output),
|
||||
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
|
||||
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
|
||||
// Pixels are read back from an image, so a `Pixels` input holds the empty image
|
||||
if **element == concrete!(Pixels) {
|
||||
return Some(TaggedValue::TypeDefault(item!(Raster<CPU>)));
|
||||
}
|
||||
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||
@@ -420,9 +422,6 @@ macro_rules! tagged_value {
|
||||
if **element == concrete!(Stroke) {
|
||||
return Some(TaggedValue::Strokes(Vec::new()));
|
||||
}
|
||||
if **element == concrete!(Pixels) {
|
||||
return Some(TaggedValue::TypeDefault(list!(Raster<CPU>)));
|
||||
}
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||
@@ -465,6 +464,7 @@ macro_rules! tagged_value {
|
||||
Self::SourceId(source) => format!("SourceId({source:?})"),
|
||||
Self::Runtime(_) => "Runtime".to_string(),
|
||||
Self::EditorApi(_) => "PlatformEditorApi".to_string(),
|
||||
Self::GraphUi(_) => "GraphUi".to_string(),
|
||||
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
|
||||
}
|
||||
}
|
||||
@@ -513,6 +513,7 @@ tagged_value! {
|
||||
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
|
||||
Color(Color),
|
||||
Font(Font),
|
||||
Footprint(Footprint),
|
||||
VectorModification(Box<VectorModification>),
|
||||
ImageData(Image<Color>),
|
||||
Resource(ResourceId),
|
||||
@@ -576,7 +577,6 @@ tagged_value! {
|
||||
StrokeAlign(vector::style::StrokeAlign),
|
||||
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
||||
GradientForm(vector::style::GradientForm),
|
||||
GradientModel(vector::style::GradientModel),
|
||||
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
|
||||
GradientSpread(vector::style::GradientSpread),
|
||||
GradientSpace(vector::style::GradientSpace),
|
||||
@@ -704,6 +704,17 @@ impl TaggedValue {
|
||||
Some(DAffine2::from_scale_angle_translation(DVec2::new(width, height), 0., DVec2::new(x, y)))
|
||||
}
|
||||
|
||||
// The Inspector's X, Y, W, H, rendered at 100% resolution
|
||||
fn to_footprint(input: &str) -> Option<Footprint> {
|
||||
let transform = to_daffine2(input)?;
|
||||
|
||||
Some(Footprint {
|
||||
transform,
|
||||
resolution: transform.matrix2.diagonal().as_uvec2(),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
||||
let mut choices = input.split("::");
|
||||
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
||||
@@ -779,6 +790,7 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||
() if ty == TypeId::of::<Footprint>() => to_footprint(string).map(TaggedValue::Footprint)?,
|
||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
|
||||
() if ty == TypeId::of::<vector::style::GradientSpread>() => to_gradient_spread(string).map(TaggedValue::GradientSpread)?,
|
||||
@@ -1134,6 +1146,20 @@ mod number_default_parsing {
|
||||
assert_eq!(TaggedValue::from_primitive_string("- 1., 2.", &item!(DVec2)), Some(TaggedValue::DVec2(DVec2::new(-1., 2.))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footprint_defaults_parse_as_x_y_width_height() {
|
||||
let expected = Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(DVec2::new(10_000., 500.), 0., DVec2::new(-50., 20.)),
|
||||
resolution: glam::UVec2::new(10_000, 500),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
TaggedValue::from_primitive_string("- 50., 20., 10_000., 500.", &item!(Footprint)),
|
||||
Some(TaggedValue::Footprint(expected))
|
||||
);
|
||||
assert_eq!(TaggedValue::from_primitive_string("1., 2., 3.", &item!(Footprint)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_defaults_parse_as_x_y_width_height() {
|
||||
let expected = DAffine2::from_scale_angle_translation(DVec2::new(500., 400.), 0., DVec2::new(250., -20.));
|
||||
@@ -1275,29 +1301,3 @@ mod retired_numeric_variants {
|
||||
assert_ne!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::Number(2.2_f32 as f64));
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
#[cfg(test)]
|
||||
mod retired_footprint_variant {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_footprint_reads_as_its_transform_then_its_resolution() {
|
||||
let payload = serde_json::json!({ "Footprint": { "transform": [500., 0., 0., 250., -20., 40.], "resolution": [64, 32], "quality": "Full" } });
|
||||
let expected = TaggedValue::Numbers(vec![500., 0., 0., 250., -20., 40., 64., 32.]);
|
||||
|
||||
let legacy = deserialize_tagged_value_with_legacy_migration(payload.clone()).expect("The footprint payload should deserialize");
|
||||
assert_eq!(*legacy.into_inner(), expected);
|
||||
|
||||
let stored: TaggedValue = serde_json::from_value(payload).expect("The footprint payload should deserialize");
|
||||
assert_eq!(stored, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_in_a_footprint_transform_reads_as_zero() {
|
||||
let payload = serde_json::json!({ "Footprint": { "transform": [1., 0., 0., 1., null, 0.], "resolution": [64, 32], "quality": "Full" } });
|
||||
let loaded: TaggedValue = serde_json::from_value(payload).expect("The footprint payload should deserialize");
|
||||
|
||||
assert_eq!(loaded, TaggedValue::Numbers(vec![1., 0., 0., 1., 0., 0., 64., 32.]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "graph-ui"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
serde = ["graph-ui-types/serde"]
|
||||
wasm = ["graph-ui-types/wasm"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
graph-ui-icons = { workspace = true }
|
||||
graph-ui-types = { workspace = true }
|
||||
graphene-std = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
rendering = { workspace = true }
|
||||
svg-convert = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "graph-ui-icons"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,39 @@
|
||||
// TODO(Timon): Replace with generalized icon crate
|
||||
|
||||
use std::fmt::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const FOLDERS: [&str; 2] = ["16x16-nodes", "16x16-ui-general"];
|
||||
|
||||
fn main() {
|
||||
let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("../../..");
|
||||
let assets = root.join("branding/assets");
|
||||
|
||||
let mut sources = Vec::new();
|
||||
println!("cargo:rerun-if-changed={}", assets.display());
|
||||
if assets.is_dir() {
|
||||
for folder in FOLDERS {
|
||||
for entry in std::fs::read_dir(assets.join(folder)).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_some_and(|extension| extension == "svg") {
|
||||
sources.push((icon_name(&path.file_stem().unwrap().to_string_lossy()), path));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!("cargo:warning=No branding folder, icons will be missing");
|
||||
}
|
||||
sources.sort();
|
||||
|
||||
let mut table = String::from("static SOURCES: &[(&str, &str)] = &[\n");
|
||||
for (name, path) in &sources {
|
||||
writeln!(table, "\t({name:?}, include_str!({:?})),", path.display().to_string()).unwrap();
|
||||
}
|
||||
table.push_str("];\n");
|
||||
std::fs::write(PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("icons.rs"), table).unwrap();
|
||||
}
|
||||
|
||||
fn icon_name(file_stem: &str) -> String {
|
||||
let capitalized = |word: &str| word[..1].to_uppercase() + &word[1..];
|
||||
file_stem.split('-').filter(|word| !word.is_empty()).map(capitalized).collect()
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// TODO(Timon): Replace with generalized icon crate
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
|
||||
|
||||
pub fn svg(name: &str) -> Option<&'static str> {
|
||||
let index = SOURCES.binary_search_by_key(&name, |&(name, _)| name).ok()?;
|
||||
Some(SOURCES[index].1)
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
use crate::metrics::{BORDER_DASHES, BORDER_WIDTH};
|
||||
use glam::DVec2;
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
use std::ops::Range;
|
||||
use vello_gpu::kurbo::{Arc, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez};
|
||||
|
||||
const MEASURE_TOLERANCE: f64 = 0.5;
|
||||
const MEASURE_DEPTH: u32 = 20;
|
||||
const ARC_TOLERANCE: f64 = 0.1;
|
||||
|
||||
struct Measured {
|
||||
distance: f64,
|
||||
segment: usize,
|
||||
t: f64,
|
||||
}
|
||||
|
||||
pub(crate) fn dashed(path: &BezPath, [dash, gap]: [f64; 2]) -> BezPath {
|
||||
let mut dashes = BezPath::new();
|
||||
for contour in contours(path) {
|
||||
let measured = measure(&contour);
|
||||
let Some(length) = measured.last().map(|last| last.distance) else { continue };
|
||||
let mut distance = 0.;
|
||||
for (index, interval) in [dash, gap].into_iter().cycle().enumerate() {
|
||||
if distance >= length {
|
||||
break;
|
||||
}
|
||||
if index % 2 == 0 {
|
||||
piece(&contour, &measured, distance..(distance + interval).min(length), &mut dashes);
|
||||
}
|
||||
distance += interval;
|
||||
}
|
||||
}
|
||||
dashes
|
||||
}
|
||||
|
||||
fn contours(path: &BezPath) -> Vec<Vec<PathSeg>> {
|
||||
let mut contours: Vec<Vec<PathSeg>> = Vec::new();
|
||||
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
|
||||
for element in path.elements() {
|
||||
let segment = match *element {
|
||||
PathEl::MoveTo(point) => {
|
||||
contours.push(Vec::new());
|
||||
(start, last) = (point, point);
|
||||
continue;
|
||||
}
|
||||
PathEl::LineTo(point) => PathSeg::Line(Line::new(last, point)),
|
||||
PathEl::QuadTo(control, point) => PathSeg::Cubic(QuadBez::new(last, control, point).raise()),
|
||||
PathEl::CurveTo(first, second, point) => PathSeg::Cubic(CubicBez::new(last, first, second, point)),
|
||||
PathEl::ClosePath => PathSeg::Line(Line::new(last, start)),
|
||||
};
|
||||
last = segment.end();
|
||||
if let Some(contour) = contours.last_mut() {
|
||||
contour.push(segment);
|
||||
}
|
||||
}
|
||||
contours
|
||||
}
|
||||
|
||||
fn measure(contour: &[PathSeg]) -> Vec<Measured> {
|
||||
let mut measured = Vec::new();
|
||||
let mut distance = 0.;
|
||||
for (segment, piece) in contour.iter().enumerate() {
|
||||
distance = match piece {
|
||||
PathSeg::Cubic(cubic) => measure_cubic(*cubic, distance, 0_f64..1., MEASURE_DEPTH, segment, &mut measured),
|
||||
_ => chord(piece.start(), piece.end(), distance, segment, 1., &mut measured),
|
||||
};
|
||||
}
|
||||
measured
|
||||
}
|
||||
|
||||
fn measure_cubic(cubic: CubicBez, distance: f64, range: Range<f64>, depth: u32, segment: usize, measured: &mut Vec<Measured>) -> f64 {
|
||||
let strays = |control: Point, fraction: f64| {
|
||||
let on_chord = cubic.p0.lerp(cubic.p3, fraction);
|
||||
(control.x - on_chord.x).abs().max((control.y - on_chord.y).abs()) > MEASURE_TOLERANCE
|
||||
};
|
||||
if depth == 0 || !(strays(cubic.p1, 1. / 3.) || strays(cubic.p2, 2. / 3.)) {
|
||||
return chord(cubic.p0, cubic.p3, distance, segment, range.end, measured);
|
||||
}
|
||||
let (first, second) = cubic.subdivide();
|
||||
let middle = (range.start + range.end) / 2.;
|
||||
let distance = measure_cubic(first, distance, range.start..middle, depth - 1, segment, measured);
|
||||
measure_cubic(second, distance, middle..range.end, depth - 1, segment, measured)
|
||||
}
|
||||
|
||||
fn chord(from: Point, to: Point, distance: f64, segment: usize, t: f64, measured: &mut Vec<Measured>) -> f64 {
|
||||
let next = distance + from.distance(to);
|
||||
if next > distance {
|
||||
measured.push(Measured { distance: next, segment, t });
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
fn at(measured: &[Measured], distance: f64) -> (usize, f64) {
|
||||
let index = measured.partition_point(|entry| entry.distance < distance).min(measured.len() - 1);
|
||||
let entry = &measured[index];
|
||||
let (start_distance, start_t) = match index.checked_sub(1).map(|previous| &measured[previous]) {
|
||||
Some(previous) if previous.segment == entry.segment => (previous.distance, previous.t),
|
||||
Some(previous) => (previous.distance, 0.),
|
||||
None => (0., 0.),
|
||||
};
|
||||
(entry.segment, start_t + (entry.t - start_t) * (distance - start_distance) / (entry.distance - start_distance))
|
||||
}
|
||||
|
||||
fn piece(contour: &[PathSeg], measured: &[Measured], range: Range<f64>, dashes: &mut BezPath) {
|
||||
let (start_segment, start_t) = at(measured, range.start);
|
||||
let (end_segment, end_t) = at(measured, range.end);
|
||||
dashes.move_to(contour[start_segment].eval(start_t));
|
||||
let mut push = |segment: usize, range: Range<f64>| match contour[segment].subsegment(range) {
|
||||
PathSeg::Line(line) => dashes.line_to(line.p1),
|
||||
PathSeg::Quad(quad) => dashes.quad_to(quad.p1, quad.p2),
|
||||
PathSeg::Cubic(cubic) => dashes.curve_to(cubic.p1, cubic.p2, cubic.p3),
|
||||
};
|
||||
if start_segment == end_segment {
|
||||
push(start_segment, start_t..end_t);
|
||||
return;
|
||||
}
|
||||
push(start_segment, start_t..1.);
|
||||
for segment in start_segment + 1..end_segment {
|
||||
push(segment, 0. ..1.);
|
||||
}
|
||||
push(end_segment, 0. ..end_t);
|
||||
}
|
||||
|
||||
enum BorderPart {
|
||||
Line(DVec2, DVec2),
|
||||
Corner(DVec2, f64),
|
||||
}
|
||||
|
||||
pub(crate) fn border(min: DVec2, max: DVec2, radius: f64, gaps: &[[DVec2; 2]], dashed: bool) -> BezPath {
|
||||
let inset = BORDER_WIDTH / 2.;
|
||||
let arc_radius = radius - inset;
|
||||
let corner_length = flattened_arc_length(radius, [0., FRAC_PI_2]);
|
||||
let [left, top] = (min + inset).to_array();
|
||||
let [right, bottom] = (max - inset).to_array();
|
||||
let parts = [
|
||||
BorderPart::Line(DVec2::new(left + arc_radius, top), DVec2::new(right - arc_radius, top)),
|
||||
BorderPart::Corner(DVec2::new(right - arc_radius, top + arc_radius), -FRAC_PI_2),
|
||||
BorderPart::Line(DVec2::new(right, top + arc_radius), DVec2::new(right, bottom - arc_radius)),
|
||||
BorderPart::Corner(DVec2::new(right - arc_radius, bottom - arc_radius), 0.),
|
||||
BorderPart::Line(DVec2::new(right - arc_radius, bottom), DVec2::new(left + arc_radius, bottom)),
|
||||
BorderPart::Corner(DVec2::new(left + arc_radius, bottom - arc_radius), FRAC_PI_2),
|
||||
BorderPart::Line(DVec2::new(left, bottom - arc_radius), DVec2::new(left, top + arc_radius)),
|
||||
BorderPart::Corner(DVec2::new(left + arc_radius, top + arc_radius), PI),
|
||||
];
|
||||
let length = |part: &BorderPart| match part {
|
||||
BorderPart::Line(from, to) => from.distance(*to),
|
||||
BorderPart::Corner(..) => corner_length,
|
||||
};
|
||||
let point = |part: &BorderPart, fraction: f64| match *part {
|
||||
BorderPart::Line(from, to) => from.lerp(to, fraction),
|
||||
BorderPart::Corner(center, start_angle) => center + arc_radius * DVec2::from_angle(start_angle + fraction * FRAC_PI_2),
|
||||
};
|
||||
let starts: Vec<f64> = parts.iter().scan(0., |start, part| Some(std::mem::replace(start, *start + length(part)))).collect();
|
||||
let perimeter: f64 = parts.iter().map(length).sum();
|
||||
|
||||
let mut left_out: Vec<[f64; 2]> = parts
|
||||
.iter()
|
||||
.zip(&starts)
|
||||
.flat_map(|(part, &start)| {
|
||||
let straight = matches!(part, BorderPart::Line(..));
|
||||
let inside = gaps.iter().filter_map(move |&gap| fractions_inside(|fraction| point(part, fraction), straight, gap));
|
||||
inside.map(move |[from, to]| [start + from * length(part), start + to * length(part)])
|
||||
})
|
||||
.collect();
|
||||
left_out.sort_by(|a, b| a[0].total_cmp(&b[0]));
|
||||
|
||||
let shown = if dashed {
|
||||
let [dash, gap] = BORDER_DASHES;
|
||||
let length = perimeter.floor();
|
||||
let fewer = (length / (dash + gap)).floor();
|
||||
let gaps = [fewer, fewer + 1.].map(|count| (length - count * dash) / count);
|
||||
let (count, gap) = if gaps[1] > 0. && (gaps[1] - gap).abs() <= (gaps[0] - gap).abs() {
|
||||
(fewer + 1., gaps[1])
|
||||
} else {
|
||||
(fewer, gaps[0])
|
||||
};
|
||||
(0..count as usize).map(|index| [index as f64 * (dash + gap), index as f64 * (dash + gap) + dash]).collect()
|
||||
} else {
|
||||
vec![[0., perimeter]]
|
||||
};
|
||||
let visible = shown.into_iter().flat_map(|[mut from, to]| {
|
||||
let mut pieces = Vec::new();
|
||||
for &[gap_from, gap_to] in &left_out {
|
||||
if gap_from < to && gap_to > from {
|
||||
pieces.extend((gap_from > from).then_some([from, gap_from]));
|
||||
from = from.max(gap_to);
|
||||
}
|
||||
}
|
||||
pieces.extend((from < to).then_some([from, to]));
|
||||
pieces
|
||||
});
|
||||
|
||||
let mut border = BezPath::new();
|
||||
for [from, to] in visible {
|
||||
let mut started = false;
|
||||
for (part, start) in parts.iter().zip(&starts) {
|
||||
if length(part) == 0. {
|
||||
continue;
|
||||
}
|
||||
let [a, b] = [from, to].map(|at| ((at - start) / length(part)).clamp(0., 1.));
|
||||
if b <= a {
|
||||
continue;
|
||||
}
|
||||
if !started {
|
||||
border.move_to(<(f64, f64)>::from(point(part, a)));
|
||||
started = true;
|
||||
}
|
||||
match *part {
|
||||
BorderPart::Line(..) => border.line_to(<(f64, f64)>::from(point(part, b))),
|
||||
BorderPart::Corner(center, start_angle) => {
|
||||
border.extend(Arc::new(<(f64, f64)>::from(center), (arc_radius, arc_radius), start_angle + a * FRAC_PI_2, (b - a) * FRAC_PI_2, 0.).append_iter(ARC_TOLERANCE))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
border
|
||||
}
|
||||
|
||||
fn flattened_arc_length(radius: f64, [from, to]: [f64; 2]) -> f64 {
|
||||
let point = |angle: f64| radius * DVec2::from_angle(angle);
|
||||
let middle = (from + to) / 2.;
|
||||
let bulge = point(middle) - (point(from) + point(to)) / 2.;
|
||||
if bulge.abs().max_element() > MEASURE_TOLERANCE {
|
||||
flattened_arc_length(radius, [from, middle]) + flattened_arc_length(radius, [middle, to])
|
||||
} else {
|
||||
point(from).distance(point(to))
|
||||
}
|
||||
}
|
||||
|
||||
fn fractions_inside(point: impl Fn(f64) -> DVec2, straight: bool, [low, high]: [DVec2; 2]) -> Option<[f64; 2]> {
|
||||
let mut range = [0_f64, 1_f64];
|
||||
for axis in 0..2 {
|
||||
let value = |fraction: f64| point(fraction)[axis];
|
||||
let [start, end] = [value(0.), value(1.)];
|
||||
if start.min(end) > high[axis] || start.max(end) < low[axis] {
|
||||
return None;
|
||||
}
|
||||
if start == end {
|
||||
continue;
|
||||
}
|
||||
let fraction_at = |bound: f64| {
|
||||
if (bound - start) * (end - start) <= 0. {
|
||||
return 0.;
|
||||
}
|
||||
if (bound - end) * (end - start) >= 0. {
|
||||
return 1.;
|
||||
}
|
||||
if straight {
|
||||
return (bound - start) / (end - start);
|
||||
}
|
||||
let [mut before, mut after] = [0_f64, 1_f64];
|
||||
for _ in 0..f64::MANTISSA_DIGITS {
|
||||
let middle = (before + after) / 2.;
|
||||
if (value(middle) - bound) * (end - start) < 0. {
|
||||
before = middle;
|
||||
} else {
|
||||
after = middle;
|
||||
}
|
||||
}
|
||||
after
|
||||
};
|
||||
let [a, b] = [fraction_at(low[axis]), fraction_at(high[axis])];
|
||||
range = [range[0].max(a.min(b)), range[1].min(a.max(b))];
|
||||
}
|
||||
(range[0] < range[1]).then_some(range)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// TODO(Timon): Replace with generalized icon crate
|
||||
|
||||
use crate::card::DataType;
|
||||
use crate::look::data_type_colors;
|
||||
use crate::metrics::ICON_SIZE;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use glam::DAffine2;
|
||||
use graphic_types::{IntoGraphicList, Vector};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use svg_convert::Options;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Icon {
|
||||
pub(crate) shapes: List<Vector>,
|
||||
pub(crate) overflows: bool,
|
||||
}
|
||||
|
||||
type Converted = HashMap<SRGBA8, HashMap<String, Option<Icon>>>;
|
||||
|
||||
static CONVERTED: LazyLock<Mutex<Converted>> = LazyLock::new(Mutex::default);
|
||||
|
||||
pub fn icon(name: &str, current: SRGBA8) -> Option<Icon> {
|
||||
let mut converted = CONVERTED.lock().unwrap();
|
||||
let converted = converted.entry(current).or_default();
|
||||
if let Some(icon) = converted.get(name) {
|
||||
return icon.clone();
|
||||
}
|
||||
let icon = graph_ui_icons::svg(name).and_then(|svg| convert(svg, current));
|
||||
converted.insert(name.to_string(), icon.clone());
|
||||
icon
|
||||
}
|
||||
|
||||
fn convert(svg: &str, current: SRGBA8) -> Option<Icon> {
|
||||
let mut style_sheet = format!("svg {{ fill: {}; }}", hex_color(current));
|
||||
for (class, _) in svg.split("class=\"").skip(1).filter_map(|rest| rest.split_once('"')) {
|
||||
write!(style_sheet, " .{class} {{ fill: {}; }}", hex_color(class_color(class)?)).unwrap();
|
||||
}
|
||||
let options = Options {
|
||||
style_sheet: Some(style_sheet),
|
||||
..Options::default()
|
||||
};
|
||||
let shapes: List<Vector> = svg_convert::convert(svg, &options).ok()?.into_flattened_list();
|
||||
|
||||
let overflows = match shapes.bounding_box(DAffine2::IDENTITY, false) {
|
||||
RenderBoundingBox::Rectangle([min, max]) => min.min_element() < 0. || max.max_element() > ICON_SIZE,
|
||||
RenderBoundingBox::Infinite => true,
|
||||
RenderBoundingBox::None => false,
|
||||
};
|
||||
Some(Icon { shapes, overflows })
|
||||
}
|
||||
|
||||
fn hex_color(color: SRGBA8) -> String {
|
||||
format!("#{:02x}{:02x}{:02x}", color.red, color.green, color.blue)
|
||||
}
|
||||
|
||||
fn class_color(class: &str) -> Option<SRGBA8> {
|
||||
let token = class.strip_prefix("color-")?;
|
||||
let Some(mix) = token.strip_prefix("mix-") else { return token_color(token) };
|
||||
let (pair, percent) = mix.rsplit_once('-')?;
|
||||
let percent: u16 = percent.parse().ok().filter(|&percent| percent <= 100)?;
|
||||
let (a, b) = pair.match_indices('-').find_map(|(index, _)| Some((token_color(&pair[..index])?, token_color(&pair[index + 1..])?)))?;
|
||||
let mix = |a: u8, b: u8| ((u16::from(a) * (100 - percent) + u16::from(b) * percent + 50) / 100) as u8;
|
||||
Some(SRGBA8::new_opaque(mix(a.red, b.red), mix(a.green, b.green), mix(a.blue, b.blue)))
|
||||
}
|
||||
|
||||
fn token_color(token: &str) -> Option<SRGBA8> {
|
||||
if let Some((digit, _)) = token.split_once('-').filter(|(digit, _)| digit.len() == 1) {
|
||||
let value = u8::from_str_radix(digit, 16).ok()? * 0x11;
|
||||
return Some(SRGBA8::new_opaque(value, value, value));
|
||||
}
|
||||
let (name, dim) = token.strip_suffix("-dim").map_or((token, false), |name| (name, true));
|
||||
let data_type = match name {
|
||||
"general" => DataType::General,
|
||||
"number" => DataType::Number,
|
||||
"artboard" => DataType::Artboard,
|
||||
"graphic" => DataType::Graphic,
|
||||
"raster" => DataType::Raster,
|
||||
"vector" => DataType::Vector,
|
||||
"color" => DataType::Color,
|
||||
"gradient" => DataType::Gradient,
|
||||
"typography" => DataType::Typography,
|
||||
_ => return None,
|
||||
};
|
||||
let [bright, dimmed] = data_type_colors(data_type);
|
||||
Some(if dim { dimmed } else { bright })
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use graph_ui_types::inputs;
|
||||
pub use graph_ui_types::{GraphUiConfig, animation, card, dot, error_badge, geometry, highlights, layer, metrics, network_connector, placed, replicated_map, scene, wire};
|
||||
pub use network::{network, render_config};
|
||||
pub use text::{error_text_size, label_width};
|
||||
|
||||
mod dashes;
|
||||
pub mod icons;
|
||||
mod look;
|
||||
mod network;
|
||||
pub mod nodes;
|
||||
pub mod router;
|
||||
mod text;
|
||||
@@ -0,0 +1,168 @@
|
||||
use crate::card::{Connector, DataType};
|
||||
use crate::highlights::Highlight;
|
||||
use crate::icons;
|
||||
use crate::metrics::{CHECKER_CELL, HOVERED_CONNECTOR_RING, HOVERED_CONNECTOR_SCALE, ICON_SIZE};
|
||||
use core_types::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::ApplyTransform;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||
use std::sync::LazyLock;
|
||||
use vector_types::vector::algorithms::shapes::rounded_rectangle_bezpath;
|
||||
use vector_types::vector::style::{Stroke, StrokeJoin};
|
||||
use vello_gpu::kurbo::{Affine, BezPath, Rect, Shape};
|
||||
|
||||
pub(crate) const CARD_OPACITY: f32 = 0.33;
|
||||
pub(crate) const GRID_DOT_OPACITY: f32 = 0.2;
|
||||
pub(crate) const BACKDROP: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
|
||||
pub(crate) const SELECTED_DOT_RING_OPACITY: f32 = 0.5;
|
||||
pub(crate) const BORDER: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
|
||||
pub(crate) const PREVIEWED_BORDER: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee);
|
||||
pub(crate) const TEXT: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee);
|
||||
pub(crate) const LAYER_IN_INACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
|
||||
pub(crate) const LAYER_IN_ACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x66, 0x66, 0x66);
|
||||
pub(crate) const HIDDEN_CARD: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44);
|
||||
pub(crate) const HIDDEN_TEXT: SRGBA8 = SRGBA8::new_opaque(0xaa, 0xaa, 0xaa);
|
||||
pub(crate) const SEPARATOR: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88);
|
||||
pub(crate) const HOVERED_BUTTON: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
|
||||
pub(crate) const DISABLED_ICON: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88);
|
||||
pub(crate) const BOX_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x00, 0xa8, 0xff);
|
||||
pub(crate) const BOX_SELECTION_FILL_OPACITY: f32 = 0.05;
|
||||
pub(crate) const ERROR_RED: SRGBA8 = SRGBA8::new_opaque(0xd6, 0x53, 0x6e);
|
||||
pub(crate) const ERROR_TEXT: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
|
||||
pub(crate) const ERROR_OPACITY: f64 = 0.5;
|
||||
pub(crate) const WIRE_SPLIT: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44);
|
||||
pub(crate) const THUMBNAIL_BACKGROUND: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
|
||||
const CHECKER_LIGHT: SRGBA8 = SRGBA8::new_opaque(0xff, 0xff, 0xff);
|
||||
const CHECKER_DARK: SRGBA8 = SRGBA8::new_opaque(0xcc, 0xcc, 0xcc);
|
||||
pub(crate) const CIRCLE_TOLERANCE: f64 = 1e-3;
|
||||
|
||||
pub(crate) static CONNECTOR_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,6.306A1.474,1.474,0,0,0,2.356,7.724L7.028,5.248c1.3-.687,1.3-1.809,0-2.5L2.356.276A1.474,1.474,0,0,0,0,1.694Z"));
|
||||
pub(crate) static STACK_OUTPUT_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,6.953l2.521,-1.694a2.649,2.649,0,0,1,2.959,0l2.52,1.694v5.047h-8z"));
|
||||
pub(crate) static STACK_INPUT_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,0H8V8L5.479,6.319a2.666,2.666,0,0,0-2.959,0L0,8Z"));
|
||||
pub(crate) static STACK_OUTPUT_WIRE_END: LazyLock<BezPath> = LazyLock::new(|| {
|
||||
parsed(
|
||||
"M0,4.5 C0,4.5 0,-3.5 0,-3.5 C0,-3.5 3,-3.5 3,-3.5 C3,-3.5 3,2.565 3,2.565 C2.834,2.632 2.673,2.717 2.52,2.819 C2.52,2.819 0,4.5 0,4.5 Z\
|
||||
M5,2.566 C5,2.566 5,-3.5 5,-3.5 C5,-3.5 8,-3.5 8,-3.5 C8,-3.5 8,4.5 8,4.5 C8,4.5 5.479,2.819 5.479,2.819 C5.326,2.717 5.166,2.633 5,2.566 Z",
|
||||
)
|
||||
});
|
||||
pub(crate) static STACK_INPUT_WIRE_END: LazyLock<BezPath> = LazyLock::new(|| {
|
||||
parsed(
|
||||
"M2.512,9.26 C2.673,9.157 2.834,9.072 3,9 C3,9 3,16 3,16 C3,16 0,16 0,16 C0,16 0,10.95 0,10.95 C0,10.95 2.512,9.26 2.512,9.26 Z\
|
||||
M5,16 C5,16 5,9 5,9 C5.166,9.073 5.327,9.158 5.48,9.26 C5.48,9.26 8,10.95 8,10.95 C8,10.95 8,16 8,16 C8,16 5,16 5,16 Z",
|
||||
)
|
||||
});
|
||||
|
||||
fn parsed(path_data: &str) -> BezPath {
|
||||
BezPath::from_svg(path_data).expect("A connector outline is valid path data")
|
||||
}
|
||||
|
||||
pub(crate) fn data_type_colors(data_type: DataType) -> [SRGBA8; 2] {
|
||||
let colors = match data_type {
|
||||
DataType::General => [0xcfcfcf, 0x8a8a8a],
|
||||
DataType::Number => [0xc9a699, 0x886b60],
|
||||
DataType::Artboard => [0xfbf9eb, 0xb9b9a9],
|
||||
DataType::Graphic => [0x68c587, 0x37754c],
|
||||
DataType::Raster => [0xe4bb72, 0x9a7b43],
|
||||
DataType::Vector => [0x65bbe5, 0x417892],
|
||||
DataType::Color => [0xce6ea7, 0x924071],
|
||||
DataType::Gradient => [0xaf81eb, 0x6c489b],
|
||||
DataType::Typography => [0xeea7a7, 0x955252],
|
||||
DataType::Invalid => [0xd6536e, 0xa7324a],
|
||||
};
|
||||
colors.map(|color| {
|
||||
let [_, red, green, blue] = u32::to_be_bytes(color);
|
||||
SRGBA8::new_opaque(red, green, blue)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn connector(outline: &BezPath, top_left: DVec2, connector: &Connector, highlight: Highlight, grown: f64) -> List<Vector> {
|
||||
drawn_connector(outline, top_left, connector.data_type, connector.connected, highlight, grown)
|
||||
}
|
||||
|
||||
pub(crate) fn drawn_connector(outline: &BezPath, top_left: DVec2, data_type: DataType, connected: bool, highlight: Highlight, grown: f64) -> List<Vector> {
|
||||
let [bright, dim] = data_type_colors(data_type);
|
||||
let resting = if connected || highlight == Highlight::WireSource { bright } else { dim };
|
||||
let ringed = highlight.is_grown();
|
||||
if grown == 0. && !ringed {
|
||||
return List::new_from_item(outlined(outline, top_left, resting));
|
||||
}
|
||||
|
||||
let scale = 1. + (HOVERED_CONNECTOR_SCALE - 1.) * grown;
|
||||
let grown_outline = Affine::translate((top_left.x, top_left.y)) * Affine::scale_about(scale, outline.bounding_box().center()) * outline.clone();
|
||||
let grown_outline = Vector::item_from_bezpath(&grown_outline);
|
||||
let mut graphic = List::new();
|
||||
if ringed {
|
||||
let ring = Stroke {
|
||||
join: StrokeJoin::Round,
|
||||
..Stroke::new(HOVERED_CONNECTOR_RING * scale)
|
||||
};
|
||||
graphic.push(painted(grown_outline.clone(), Coverage::new_stroke(&ring), dim.into()));
|
||||
}
|
||||
let channel = |from: u8, to: u8| (from as f64 + (to as f64 - from as f64) * grown).round() as u8;
|
||||
let fill = SRGBA8::new(
|
||||
channel(resting.red, bright.red),
|
||||
channel(resting.green, bright.green),
|
||||
channel(resting.blue, bright.blue),
|
||||
channel(resting.alpha, bright.alpha),
|
||||
);
|
||||
graphic.push(painted(grown_outline, Coverage::new_fill(), fill.into()));
|
||||
graphic
|
||||
}
|
||||
|
||||
pub(crate) fn outlined(outline: &BezPath, top_left: DVec2, color: SRGBA8) -> Item<Vector> {
|
||||
let mut outline = Vector::item_from_bezpath(outline);
|
||||
outline.left_apply_transform(&DAffine2::from_translation(top_left));
|
||||
painted(outline, Coverage::new_fill(), color.into())
|
||||
}
|
||||
|
||||
pub(crate) fn rounded_rect(min: DVec2, max: DVec2, radii: [f64; 4]) -> Item<Vector> {
|
||||
Vector::item_from_bezpath(&rounded_rectangle_bezpath(min, max, radii))
|
||||
}
|
||||
|
||||
pub(crate) fn icon(name: &str, top_left: DVec2, current: SRGBA8) -> List<Vector> {
|
||||
let Some(icon) = icons::icon(name, current) else { return List::new() };
|
||||
let mut graphic = icon.shapes;
|
||||
if icon.overflows {
|
||||
let mut clip = rounded_rect(DVec2::ZERO, DVec2::splat(ICON_SIZE), [0.; 4]);
|
||||
stamp_coverage(&mut clip, Coverage::new_fill(), Graphic::VectorList(graphic), CoverPlacement::Above);
|
||||
graphic = List::new_from_item(clip);
|
||||
}
|
||||
graphic.left_apply_transform(&DAffine2::from_translation(top_left));
|
||||
graphic
|
||||
}
|
||||
|
||||
pub(crate) fn text(outline: &List<Vector>, top_left: DVec2, color: SRGBA8) -> List<Vector> {
|
||||
let glyphs = outline.clone().into_iter();
|
||||
let mut glyphs: List<Vector> = glyphs.map(|glyph| painted(glyph, Coverage::new_fill(), color.into())).collect();
|
||||
glyphs.left_apply_transform(&DAffine2::from_translation(top_left));
|
||||
glyphs
|
||||
}
|
||||
|
||||
pub(crate) fn checkerboard(min: DVec2, max: DVec2) -> List<Vector> {
|
||||
let mut dark = BezPath::new();
|
||||
let cells = ((max - min) / CHECKER_CELL).ceil().as_uvec2();
|
||||
for (column, row) in (0..cells.y)
|
||||
.flat_map(|row| (0..cells.x).map(move |column| (column, row)))
|
||||
.filter(|(column, row)| (column + row) % 2 == 1)
|
||||
{
|
||||
let cell_min = min + DVec2::new(column as f64, row as f64) * CHECKER_CELL;
|
||||
let cell_max = (cell_min + CHECKER_CELL).min(max);
|
||||
dark.extend(Rect::new(cell_min.x, cell_min.y, cell_max.x, cell_max.y).path_elements(0.));
|
||||
}
|
||||
let light = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), CHECKER_LIGHT.into());
|
||||
List::from_iter([light, painted(Vector::item_from_bezpath(&dark), Coverage::new_fill(), CHECKER_DARK.into())])
|
||||
}
|
||||
|
||||
pub(crate) fn painted(mut item: Item<Vector>, coverage: Coverage, color: Color) -> Item<Vector> {
|
||||
stamp_coverage(&mut item, coverage, Graphic::from(color), CoverPlacement::Above);
|
||||
item
|
||||
}
|
||||
|
||||
pub(crate) fn image(content: Graphic, unit_square_to_place: DAffine2) -> Item<Vector> {
|
||||
let mut image = rounded_rect(DVec2::ZERO, DVec2::ONE, [0.; 4]);
|
||||
image.left_apply_transform(&unit_square_to_place);
|
||||
stamp_coverage(&mut image, Coverage::new_fill(), content, CoverPlacement::Above);
|
||||
image
|
||||
}
|
||||
Loaded 100 of 239 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user