mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-06 08:13:40 -10:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7298ccc78e | ||
|
|
58e32134a3 | ||
|
|
f76d89a6ca | ||
|
|
f7a62a4bad | ||
|
|
a6a08c6f5f | ||
|
|
55bd023a76 | ||
|
|
9a574b891c | ||
|
|
8d6efb057c | ||
|
|
6cbf7f0618 | ||
|
|
5d0005f7cf | ||
|
|
51e2003fea | ||
|
|
4059949762 | ||
|
|
d684bade6a |
No files matched your search
@@ -29,6 +29,8 @@ 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
|
||||
@@ -175,14 +177,15 @@ async function listBranchRuns(workflowId: number, before?: number): Promise<Work
|
||||
return newestFirst(runs);
|
||||
}
|
||||
|
||||
// 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)
|
||||
// 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)
|
||||
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,6 +37,7 @@ 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) {
|
||||
@@ -47,10 +48,10 @@ if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" &&
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`::${passed ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
|
||||
console.log(`::${passed || superseded ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
|
||||
|
||||
// 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";
|
||||
// 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";
|
||||
fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`);
|
||||
|
||||
function readDecision(): Decision {
|
||||
|
||||
@@ -64,7 +64,12 @@ 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' }}
|
||||
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' && steps.report.outputs.result != 'superseded' }}
|
||||
run: exit 1
|
||||
Generated
+3
-3
@@ -8084,7 +8084,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -8099,7 +8099,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -8113,7 +8113,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
|
||||
+3
-3
@@ -315,6 +315,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 = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
|
||||
@@ -234,11 +234,7 @@ impl RenderState {
|
||||
WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true),
|
||||
WgpuCurrentSurfaceTexture::Occluded => return Ok(()),
|
||||
WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
|
||||
WgpuCurrentSurfaceTexture::Outdated => {
|
||||
self.surface.configure(&self.executor.context().device, &self.config);
|
||||
window.request_redraw();
|
||||
return Ok(());
|
||||
}
|
||||
WgpuCurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated),
|
||||
WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
|
||||
WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
|
||||
};
|
||||
@@ -331,6 +327,7 @@ impl RenderState {
|
||||
pub(crate) enum RenderError {
|
||||
OutdatedUITextureError,
|
||||
SurfaceLost,
|
||||
SurfaceOutdated,
|
||||
SurfaceTimeout,
|
||||
SurfaceValidation,
|
||||
}
|
||||
|
||||
@@ -44,8 +44,6 @@ 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
|
||||
@@ -561,11 +559,7 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
||||
}
|
||||
|
||||
// Nodes the binary doesn't register, such as in tests, are at their first version
|
||||
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 version = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|metadata| metadata.version)).unwrap_or(1);
|
||||
let EncodedDeclaration { id, hash, bytes, proto } =
|
||||
EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
|
||||
|
||||
|
||||
@@ -657,41 +657,6 @@ 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]
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
GradientModel(GradientModel),
|
||||
GradientDirection(GradientDirection),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GradientModel {
|
||||
Standard,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GradientDirection {
|
||||
Along,
|
||||
}
|
||||
|
||||
/// 'Fill' gained the model and direction it gives the gradient it paints, set to the Standard model and the Along direction a gradient without them already has.
|
||||
#[migration("graphene_core::vector::FillNode"@2 => @3)]
|
||||
pub fn fill_v2(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// The model and the direction.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::GradientModel(GradientModel::Standard)), literal(Tagged::GradientDirection(GradientDirection::Along))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&FillV2, &contract());
|
||||
check_undo(&FillV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_the_default_model_and_direction() {
|
||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&FillV2);
|
||||
let fill = fixture.add(decl!("graphene_core::vector::FillNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&FillV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, fill), Some(decl!("graphene_core::vector::FillNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, fill), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
//! Migrations of the nodes in `graphene_core`.
|
||||
|
||||
mod fill_v1;
|
||||
mod fill_v2;
|
||||
mod passthrough_from_read_attribute_gradient_form_node;
|
||||
mod passthrough_from_upload_texture_node;
|
||||
mod renames;
|
||||
mod vary_colors_from_assign_colors;
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
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,3 +1,3 @@
|
||||
//! Migrations of the nodes in `graphene_std`.
|
||||
|
||||
mod rasterize_v1;
|
||||
mod renames;
|
||||
@@ -1,68 +0,0 @@
|
||||
use migration_core::{Inputs, MigrationError, NodeInput, migration};
|
||||
use serde::Serialize;
|
||||
|
||||
const EXECUTOR: u32 = 2;
|
||||
const EXECUTOR_SCOPE: &str = "graphene_std::platform_application_io::WgpuExecutorNode";
|
||||
|
||||
/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses.
|
||||
#[derive(Serialize)]
|
||||
enum Reflected {
|
||||
DocumentNodePath,
|
||||
}
|
||||
|
||||
/// Rasterize gained an input holding its own document node path. Nodes stored without the executor input get it first, so the path lands after it.
|
||||
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
|
||||
pub fn rasterize_v1(inputs: &mut Inputs) -> Result<(), MigrationError> {
|
||||
if inputs.len() < EXECUTOR as usize {
|
||||
return Err(MigrationError::invariant("Rasterize has Data and Footprint inputs"));
|
||||
}
|
||||
if inputs.len() == EXECUTOR as usize {
|
||||
inputs.push(NodeInput::Scope(EXECUTOR_SCOPE.into()));
|
||||
}
|
||||
|
||||
inputs.push_reflection(Reflected::DocumentNodePath);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
|
||||
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))
|
||||
}
|
||||
|
||||
fn migrate(inputs: Vec<NodeInput>) -> Vec<NodeInput> {
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let rasterize = fixture.add(decl!("graphene_std::platform_application_io::RasterizeNode"@1), inputs);
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let own_path = &migrated.node_instances[&rasterize].inputs()[3];
|
||||
assert_eq!(own_path.attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
|
||||
|
||||
fixture.inputs(&migrated, rasterize)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RasterizeV1, &contract());
|
||||
check_undo(&RasterizeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gives_the_node_its_path() {
|
||||
let inputs = vec![literal(1.), literal(2.), NodeInput::Scope(EXECUTOR_SCOPE.into())];
|
||||
|
||||
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Reflection]].concat());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_stored_without_its_executor_gets_it_before_its_path() {
|
||||
let inputs = vec![literal(1.), literal(2.)];
|
||||
|
||||
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Scope(EXECUTOR_SCOPE.into()), NodeInput::Reflection]].concat());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! 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);
|
||||
@@ -0,0 +1,127 @@
|
||||
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,4 +1,5 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod gradient_curvature_from_gradient_form;
|
||||
mod math_formula_from_math_f;
|
||||
mod renames;
|
||||
@@ -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: Vec<NodeSource> = baseline_nodes?.into_iter().filter(|node| !node.transient).collect();
|
||||
let baseline_nodes = baseline_nodes?;
|
||||
|
||||
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| !new.transient && !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
|
||||
.find(|new| !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,9 +83,6 @@ 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));
|
||||
@@ -126,7 +123,6 @@ 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(),
|
||||
@@ -172,15 +168,6 @@ 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,7 +117,6 @@ 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,7 +10,6 @@ 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.
|
||||
@@ -120,9 +119,7 @@ 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(' ', "");
|
||||
@@ -150,7 +147,6 @@ 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,
|
||||
@@ -175,24 +171,4 @@ 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: Vec<NodeSource> = find_nodes(&workspace.join(NODE_CRATES))?.into_iter().filter(|node| !node.transient).collect();
|
||||
let nodes = find_nodes(&workspace.join(NODE_CRATES))?;
|
||||
let migrations = workspace.join(MIGRATIONS);
|
||||
|
||||
match (command, arguments) {
|
||||
|
||||
@@ -148,10 +148,24 @@ pub const CURVATURE_COMB_MAX_TEETH_PER_SEGMENT: f64 = 128.;
|
||||
pub const CURVATURE_COMB_MAX_TOOTH_LENGTH: f64 = 2000.;
|
||||
|
||||
// GRADIENT TOOL
|
||||
pub const GRADIENT_LINE_WIDTH: f64 = 2.;
|
||||
// Half the height of a midpoint diamond across the gradient line
|
||||
pub const GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT: f64 = 5.;
|
||||
// Half the width of a midpoint diamond along the gradient line
|
||||
pub const GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH: f64 = 3.;
|
||||
// The radius of the circle approximating a midpoint diamond, which a press is measured against
|
||||
pub const GRADIENT_MIDPOINT_DIAMOND_RADIUS: f64 = 4.;
|
||||
// The radius of a color stop dot at its regular size, which a press is measured against
|
||||
pub const GRADIENT_STOP_RADIUS: f64 = MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1.;
|
||||
pub const GRADIENT_MIDPOINT_MIN: f64 = 0.01;
|
||||
pub const GRADIENT_MIDPOINT_MAX: f64 = 0.99;
|
||||
pub const GRADIENT_STOP_MIN_VIEWPORT_GAP: f64 = 10.;
|
||||
// In viewport pixels from a contour's dashed rim, within which a press takes hold of it
|
||||
pub const GRADIENT_CONTOUR_RIM_GRAB_DISTANCE: f64 = 5.;
|
||||
// In viewport pixels, within which a dragged contour handle snaps onto making its contour a line or a point
|
||||
pub const GRADIENT_CONTOUR_SNAP_DISTANCE: f64 = 4.;
|
||||
// In viewport pixels, the shortest an end circle's semi-minor axis lines are drawn, below which they have no aspect handles at their tips
|
||||
pub const GRADIENT_SEMI_MINOR_AXIS_MIN_LENGTH: f64 = 20.;
|
||||
|
||||
// PEN TOOL
|
||||
pub const CREATE_CURVE_THRESHOLD: f64 = 5.;
|
||||
|
||||
@@ -665,18 +665,6 @@ mod test {
|
||||
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
|
||||
}
|
||||
|
||||
#[cfg_attr(miri, ignore)]
|
||||
#[tokio::test]
|
||||
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 clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
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
|
||||
/// - assert that ellipse was copied
|
||||
#[tokio::test]
|
||||
|
||||
@@ -31,7 +31,8 @@ use graphene_std::vector::misc::{
|
||||
WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
DashPattern, FillChoice, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign,
|
||||
StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{
|
||||
@@ -408,7 +409,6 @@ macro_rules! inspectable_types {
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<BlendMode>,
|
||||
List<GradientForm>,
|
||||
List<GradientSpread>,
|
||||
List<GradientSpace>,
|
||||
List<GradientHueDirection>,
|
||||
@@ -469,6 +469,8 @@ macro_rules! inspectable_types {
|
||||
Item<DAffine2>,
|
||||
Item<BlendMode>,
|
||||
Item<GradientForm>,
|
||||
Item<GradientModel>,
|
||||
Item<GradientDirection>,
|
||||
Item<GradientSpread>,
|
||||
Item<GradientSpace>,
|
||||
Item<GradientHueDirection>,
|
||||
@@ -1284,6 +1286,8 @@ impl_table_item_layout_for_choice_enum!(
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientDirection,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -1479,6 +1483,8 @@ macro_rules! known_item_types {
|
||||
TransferCurve,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientDirection,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
|
||||
@@ -319,9 +319,6 @@ pub enum DocumentMessage {
|
||||
UpdateTextFrames {
|
||||
text_frames: HashMap<NodeId, DAffine2>,
|
||||
},
|
||||
UpdateFootprintAreas {
|
||||
footprint_areas: HashMap<NodeId, DAffine2>,
|
||||
},
|
||||
UpdateClipTargets {
|
||||
clip_targets: HashSet<NodeId>,
|
||||
},
|
||||
|
||||
@@ -1921,9 +1921,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_text_frames(layer_text_frames);
|
||||
}
|
||||
DocumentMessage::UpdateFootprintAreas { footprint_areas } => {
|
||||
self.network_interface.update_footprint_areas(footprint_areas);
|
||||
}
|
||||
DocumentMessage::UpdateClipTargets { clip_targets } => {
|
||||
self.network_interface.update_clip_targets(clip_targets);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::style::{GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, VectorModificationType};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -26,7 +26,8 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
#[serde(skip)]
|
||||
gradient: Gradient,
|
||||
gradient_form: GradientForm,
|
||||
/// The form whose curvatures the Fill takes, or `None` to keep its own.
|
||||
gradient_form: Option<GradientForm>,
|
||||
gradient_settings: GradientSettings,
|
||||
/// `None` lets the gradient cover the layer's bounding box, following it as the layer changes.
|
||||
transform: Option<DAffine2>,
|
||||
@@ -56,6 +57,19 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
gradient_form: GradientForm,
|
||||
},
|
||||
GradientCurvatureSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
/// The start and end curvatures.
|
||||
curvatures: [f64; 2],
|
||||
},
|
||||
GradientModelSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
model: GradientModel,
|
||||
},
|
||||
GradientDirectionSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
direction: GradientDirection,
|
||||
},
|
||||
GradientSpreadSet {
|
||||
layer: LayerNodeIdentifier,
|
||||
gradient_spread: GradientSpread,
|
||||
|
||||
+17
-2
@@ -86,6 +86,21 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
modify_inputs.gradient_form_set(gradient_form);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientCurvatureSet { layer, curvatures } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_curvature_set(curvatures);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientModelSet { layer, model } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_model_set(model);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientDirectionSet { layer, direction } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_direction_set(direction);
|
||||
}
|
||||
}
|
||||
GraphOperationMessage::GradientSpreadSet { layer, gradient_spread } => {
|
||||
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
|
||||
modify_inputs.gradient_spread_set(gradient_spread);
|
||||
@@ -1034,7 +1049,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, gradient_form, settings, Some(transform));
|
||||
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
|
||||
}
|
||||
usvg::Paint::RadialGradient(radial) => {
|
||||
let gradient_transform = usvg_transform(radial.transform());
|
||||
@@ -1062,7 +1077,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, gradient_form, settings, Some(transform));
|
||||
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
|
||||
}
|
||||
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
|
||||
};
|
||||
|
||||
@@ -6,7 +6,8 @@ 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, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
|
||||
ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_fill_node_id_with_direct_fill_input, get_upstream_gradient_value_node_id, gradient_chain_target_input,
|
||||
gradient_curvature_values, replaceable_paint_chain,
|
||||
};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::application_io::resource::ResourceId;
|
||||
@@ -15,7 +16,7 @@ use graph_craft::document::{NodeId, NodeInput};
|
||||
use graph_craft::{ProtoNodeIdentifier, list};
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::style::{GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
|
||||
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
|
||||
use graphene_std::{Artboard, Color, Graphic};
|
||||
use kurbo::BezPath;
|
||||
@@ -450,7 +451,8 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: Option<DAffine2>) {
|
||||
/// 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>) {
|
||||
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;
|
||||
@@ -490,17 +492,31 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientFormInput),
|
||||
NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
|
||||
false,
|
||||
);
|
||||
// Only a chosen form sets the curvatures, leaving any the graph feeds or that already make it
|
||||
if let Some(gradient_form) = gradient_form {
|
||||
self.write_fill_curvatures(fill_node_id, gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form));
|
||||
}
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
|
||||
if existing_fill_node_id.is_none() {
|
||||
self.restore_default_stroke_order();
|
||||
}
|
||||
}
|
||||
|
||||
/// Write both curvatures to a Fill node's hidden curvature inputs unless the graph feeds them or its current ones are `already_written`, for the caller to then run the graph.
|
||||
fn write_fill_curvatures(&mut self, fill_node_id: NodeId, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) {
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let current = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
|
||||
if current.is_none_or(already_written) {
|
||||
return;
|
||||
}
|
||||
|
||||
let [start, end] = curvatures;
|
||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
|
||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), true);
|
||||
}
|
||||
|
||||
/// A freshly created Fill node lands at the chain start, downstream of any Stroke node, where it would
|
||||
/// paint over the stroke. This hops the stroke back downstream so it keeps painting above by default.
|
||||
fn restore_default_stroke_order(&mut self) {
|
||||
@@ -761,20 +777,96 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||
/// from the default (`Linear`).
|
||||
/// 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.
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
self.write_gradient_curvatures(gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form));
|
||||
}
|
||||
|
||||
/// Write both curvatures to the layer's gradient: a Fill node holding it, or else the last 'Gradient Curvature' node in its chain, inserting
|
||||
/// one only when they differ from the default form's (`Linear`). Curvatures fed from the graph (procedural authorship) are left untouched.
|
||||
pub fn gradient_curvature_set(&mut self, curvatures: [f64; 2]) {
|
||||
if let Some(output_layer) = self.get_output_layer()
|
||||
&& let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(output_layer, self.network_interface)
|
||||
{
|
||||
self.write_fill_curvatures(fill_node_id, curvatures, |current| current == curvatures);
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
return;
|
||||
}
|
||||
|
||||
self.write_gradient_curvatures(curvatures, |current| current == curvatures);
|
||||
}
|
||||
|
||||
/// Write these curvatures to the last 'Gradient Curvature' node in the chain unless its current ones are `already_written`.
|
||||
fn write_gradient_curvatures(&mut self, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let 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 create_if_nonexistent = curvatures != GradientForm::default().curvatures();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return };
|
||||
let Some(current) = gradient_curvature_values(node) else { return };
|
||||
if already_written(current) {
|
||||
return;
|
||||
}
|
||||
|
||||
let [start, end] = curvatures;
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
}
|
||||
|
||||
/// Set the model of the layer's gradient, as [`Self::gradient_choice_set`] sets a choice.
|
||||
pub fn gradient_model_set(&mut self, model: GradientModel) {
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::math_nodes::gradient_model;
|
||||
|
||||
let value = TaggedValue::GradientModel(model);
|
||||
let fill_input = graphene_std::vector::fill::ModelInput::INDEX;
|
||||
self.gradient_choice_set(fill_input, gradient_model::IDENTIFIER, gradient_model::ModelInput::INDEX, value, model == GradientModel::default());
|
||||
}
|
||||
|
||||
/// Set the direction of the layer's gradient, as [`Self::gradient_choice_set`] sets a choice.
|
||||
pub fn gradient_direction_set(&mut self, direction: GradientDirection) {
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::math_nodes::gradient_direction;
|
||||
|
||||
let value = TaggedValue::GradientDirection(direction);
|
||||
let fill_input = graphene_std::vector::fill::DirectionInput::INDEX;
|
||||
self.gradient_choice_set(
|
||||
fill_input,
|
||||
gradient_direction::IDENTIFIER,
|
||||
gradient_direction::DirectionInput::INDEX,
|
||||
value,
|
||||
direction == GradientDirection::default(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Set a choice of how the layer's gradient is drawn: in the Fill node's input at `fill_input` where the Fill holds the gradient as a value, or else in the input at
|
||||
/// `node_input` of the last node of this `identifier` in the chain, inserting one only for a value other than the default. A choice the graph feeds is left as it is.
|
||||
fn gradient_choice_set(&mut self, fill_input: usize, identifier: ProtoNodeIdentifier, node_input: usize, value: TaggedValue, is_default: bool) {
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let (node_id, input_index) = match get_fill_node_id_with_direct_fill_input(output_layer, self.network_interface) {
|
||||
Some(fill_node_id) => (fill_node_id, fill_input),
|
||||
None => {
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, !is_default) else {
|
||||
return;
|
||||
};
|
||||
(node_id, node_input)
|
||||
}
|
||||
};
|
||||
|
||||
let node = self.network_interface.document_network().nodes.get(&node_id);
|
||||
let current = node.and_then(|node| node.inputs.get(input_index)).and_then(NodeInput::as_non_exposed_value);
|
||||
if current.is_some_and(|current| *current != value) {
|
||||
self.set_input_with_refresh(InputConnector::node_at_index(node_id, input_index), NodeInput::value(value, false), false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||
|
||||
@@ -686,6 +686,7 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
||||
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
||||
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
||||
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
|
||||
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
|
||||
@@ -37,8 +37,8 @@ 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, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
build_transform_with_y_preservation,
|
||||
FillChoice, Gradient, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, 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,6 +254,23 @@ 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 {
|
||||
@@ -417,6 +434,8 @@ 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::<GradientDirection>(x) => enum_choice::<GradientDirection>().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(),
|
||||
@@ -3286,6 +3305,80 @@ 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::*;
|
||||
|
||||
@@ -3443,18 +3536,7 @@ 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 {
|
||||
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,
|
||||
};
|
||||
options = ParameterOptions::from(field);
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
@@ -3843,9 +3925,25 @@ 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(update_value(move |_| TaggedValue::GradientForm(gradient_form), node_id, GradientFormInput))
|
||||
.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_commit(commit_value)
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::consts::{
|
||||
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLACK, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_WHITE_05, COLOR_OVERLAY_YELLOW,
|
||||
COLOR_OVERLAY_YELLOW_DULL, COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, CURVATURE_COMB_DEFAULT_SCALE,
|
||||
DOWEL_PIN_RADIUS, GRADIENT_MIDPOINT_DIAMOND_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET,
|
||||
SKEW_TRIANGLE_SIZE,
|
||||
DOWEL_PIN_RADIUS, GRADIENT_LINE_WIDTH, GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT, GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH, GRADIENT_STOP_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH,
|
||||
PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
|
||||
};
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::hex_to_rgba_u8;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -24,7 +24,7 @@ use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::misc::point_to_dvec2;
|
||||
use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, NodeParameter};
|
||||
use graphene_std::{ATTR_TRANSFORM, Color, NodeParameter};
|
||||
use kurbo::{self, BezPath, ParamCurve};
|
||||
use kurbo::{Affine, PathSeg};
|
||||
use std::borrow::Cow;
|
||||
@@ -404,6 +404,12 @@ impl OverlayContext {
|
||||
self.record(move |overlays| overlays.dashed_polygon(&polygon, stroke_color.as_deref(), color_fill.as_deref(), dash_width, dash_gap_width, dash_offset));
|
||||
}
|
||||
|
||||
/// Strokes the open path through these points, unlike [`Self::dashed_polygon`], which closes it.
|
||||
pub fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
let (points, color) = (points.to_vec(), owned(color));
|
||||
self.record(move |overlays| overlays.dashed_polyline(&points, color.as_deref(), dash_width, dash_gap_width, dash_offset));
|
||||
}
|
||||
|
||||
pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.line(start, end, color.as_deref(), thickness));
|
||||
@@ -428,6 +434,12 @@ impl OverlayContext {
|
||||
self.record(move |overlays| overlays.manipulator_handle(position, selected, color.as_deref()));
|
||||
}
|
||||
|
||||
/// Draws a handle like [`Self::manipulator_handle`] outlined in `color`, and filled with it too where `selected`.
|
||||
pub fn colored_manipulator_handle(&mut self, position: DVec2, selected: bool, color: &str) {
|
||||
let color = color.to_owned();
|
||||
self.record(move |overlays| overlays.filled_manipulator_handle(position, if selected { &color } else { COLOR_OVERLAY_WHITE }, &color));
|
||||
}
|
||||
|
||||
pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
let color = owned(color);
|
||||
self.record(move |overlays| overlays.manipulator_anchor(position, selected, color.as_deref()));
|
||||
@@ -438,8 +450,15 @@ impl OverlayContext {
|
||||
self.record(move |overlays| overlays.gradient_color_stop(position, emphasis, &color, small));
|
||||
}
|
||||
|
||||
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
|
||||
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, angle));
|
||||
/// Draws a gradient midpoint's diamond filled with `color`, taller across the gradient line at `angle` than it is wide, bordered like a color stop's dot.
|
||||
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
|
||||
let color = color.to_owned();
|
||||
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, &color, angle));
|
||||
}
|
||||
|
||||
/// Draws a line in a gradient's own colors, from its color `stops` at fractions of the way from `start` to `end`, outlined in white and then black like its color stops.
|
||||
pub fn gradient_line(&mut self, start: DVec2, end: DVec2, stops: Vec<(f64, Color)>) {
|
||||
self.record(move |overlays| overlays.gradient_line(start, end, &stops));
|
||||
}
|
||||
|
||||
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
|
||||
@@ -785,6 +804,24 @@ impl OverlayContextInternal {
|
||||
self.stroke_in_view(&stroke, Self::parse_color(stroke_color), &path);
|
||||
}
|
||||
|
||||
fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
|
||||
let mut points = points.iter().map(|&point| self.snap_to_physical_pixel_center(point));
|
||||
let Some(first) = points.next() else { return };
|
||||
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(kurbo::Point::new(first.x, first.y));
|
||||
for point in points {
|
||||
path.line_to(kurbo::Point::new(point.x, point.y));
|
||||
}
|
||||
|
||||
let mut stroke = kurbo::Stroke::new(1.);
|
||||
if let Some(dash_width) = dash_width {
|
||||
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap_width.unwrap_or(1.)]);
|
||||
}
|
||||
|
||||
self.stroke_in_view(&stroke, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), &path);
|
||||
}
|
||||
|
||||
fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
|
||||
self.dashed_line(start, end, color, thickness, None, None, None)
|
||||
}
|
||||
@@ -809,16 +846,17 @@ impl OverlayContextInternal {
|
||||
}
|
||||
|
||||
fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
|
||||
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
|
||||
self.filled_manipulator_handle(position, fill, color.unwrap_or(COLOR_OVERLAY_BLUE));
|
||||
}
|
||||
|
||||
fn filled_manipulator_handle(&mut self, position: DVec2, fill: &str, stroke: &str) {
|
||||
let transform = self.get_transform();
|
||||
let position = self.snap_to_physical_pixel_center(position);
|
||||
|
||||
let circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.);
|
||||
|
||||
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &circle);
|
||||
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &circle);
|
||||
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(stroke), None, &circle);
|
||||
}
|
||||
|
||||
fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
|
||||
@@ -860,7 +898,7 @@ impl OverlayContextInternal {
|
||||
GizmoEmphasis::Active => 1.,
|
||||
};
|
||||
let stroke_width = radius_offset * 2. + 1.;
|
||||
let radius = (MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1. + radius_offset) * if small { 0.5 } else { 1. };
|
||||
let radius = (GRADIENT_STOP_RADIUS + radius_offset) * if small { 0.5 } else { 1. };
|
||||
|
||||
let mut draw_circle = |radius: f64, width: Option<f64>, color: &str| {
|
||||
let circle = kurbo::Circle::new((position.x, position.y), radius);
|
||||
@@ -878,33 +916,59 @@ impl OverlayContextInternal {
|
||||
draw_circle(radius, Some(stroke_width), COLOR_OVERLAY_WHITE);
|
||||
}
|
||||
|
||||
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
|
||||
let transform = self.get_transform();
|
||||
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
|
||||
let position = position.round() - DVec2::splat(0.5);
|
||||
let transform = self.get_transform() * kurbo::Affine::translate((position.x, position.y)) * kurbo::Affine::rotate(angle);
|
||||
|
||||
// Rotate diamond points by the gradient line angle
|
||||
let (sin, cos) = angle.sin_cos();
|
||||
let rotate = |dx: f64, dy: f64| DVec2::new(dx * cos - dy * sin, dx * sin + dy * cos);
|
||||
|
||||
let top = rotate(0., -GRADIENT_MIDPOINT_DIAMOND_RADIUS);
|
||||
let right = rotate(GRADIENT_MIDPOINT_DIAMOND_RADIUS, 0.);
|
||||
let bottom = rotate(0., GRADIENT_MIDPOINT_DIAMOND_RADIUS);
|
||||
let left = rotate(-GRADIENT_MIDPOINT_DIAMOND_RADIUS, 0.);
|
||||
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(kurbo::Point::new(position.x + top.x, position.y + top.y));
|
||||
path.line_to(kurbo::Point::new(position.x + right.x, position.y + right.y));
|
||||
path.line_to(kurbo::Point::new(position.x + bottom.x, position.y + bottom.y));
|
||||
path.line_to(kurbo::Point::new(position.x + left.x, position.y + left.y));
|
||||
path.close_path();
|
||||
|
||||
let (fill, stroke_width) = match emphasis {
|
||||
GizmoEmphasis::Regular => (COLOR_OVERLAY_WHITE, 1.),
|
||||
GizmoEmphasis::Hovered => (COLOR_OVERLAY_WHITE, 2.),
|
||||
GizmoEmphasis::Active => (COLOR_OVERLAY_BLUE, 1.),
|
||||
// Grown for emphasis with a thicker white border, as a color stop's dot is
|
||||
let radius_offset = match emphasis {
|
||||
GizmoEmphasis::Regular => 0.,
|
||||
GizmoEmphasis::Hovered => 0.5,
|
||||
GizmoEmphasis::Active => 1.,
|
||||
};
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &path);
|
||||
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
|
||||
let stroke_width = radius_offset * 2. + 1.;
|
||||
|
||||
// Taller across the gradient line than it is wide along it
|
||||
let (half_width, half_height) = (GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH + radius_offset, GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT + radius_offset);
|
||||
let mut diamond = BezPath::new();
|
||||
diamond.move_to((half_width, 0.));
|
||||
diamond.line_to((0., half_height));
|
||||
diamond.line_to((-half_width, 0.));
|
||||
diamond.line_to((0., -half_height));
|
||||
diamond.close_path();
|
||||
|
||||
// The black border shows half a pixel past the white one, as around a color stop's dot
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(stroke_width + 1.), transform, Self::parse_color(COLOR_OVERLAY_BLACK), None, &diamond);
|
||||
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color), None, &diamond);
|
||||
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &diamond);
|
||||
}
|
||||
|
||||
fn gradient_line(&mut self, start: DVec2, end: DVec2, stops: &[(f64, Color)]) {
|
||||
let transform = self.get_transform();
|
||||
|
||||
// Centered on whole pixels, the even widths have crisp edges
|
||||
let [start, end] = [start, end].map(|point| self.snap_to_physical_pixel(point));
|
||||
let line = kurbo::Line::new((start.x, start.y), (end.x, end.y));
|
||||
|
||||
// Bordered like a color stop's dot, by a pixel of white and then half a pixel of black
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH + 3.), transform, Self::parse_color(COLOR_OVERLAY_BLACK), None, &line);
|
||||
self.scene
|
||||
.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH + 2.), transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &line);
|
||||
|
||||
// Opaque like the stops' dots
|
||||
let stops = stops.iter().map(|&(offset, color)| {
|
||||
let [red, green, blue, _] = color.to_gamma_srgb_channels();
|
||||
peniko::ColorStop {
|
||||
offset: offset as f32,
|
||||
color: peniko::color::DynamicColor::from_alpha_color(peniko::Color::new([red, green, blue, 1.])),
|
||||
}
|
||||
});
|
||||
let mut gradient = peniko::Gradient::new_linear((start.x, start.y), (end.x, end.y));
|
||||
gradient.stops = peniko::ColorStops(stops.collect());
|
||||
|
||||
self.scene.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH), transform, &gradient, None, &line);
|
||||
}
|
||||
|
||||
fn resize_handle(&mut self, position: DVec2, rotation: f64) {
|
||||
|
||||
@@ -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(), 7, "the legacy Fill should upgrade to the 7-input shape");
|
||||
assert_eq!(fill_node.inputs.len(), 10, "the legacy Fill should upgrade to the 10-input shape");
|
||||
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
|
||||
assert!(
|
||||
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
|
||||
@@ -1033,7 +1033,13 @@ 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(), 7, "the eight-input Fill should fold down to the 7-input shape");
|
||||
assert_eq!(fill_node.inputs.len(), 10, "the eight-input Fill should come out in the modern 10-input shape");
|
||||
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"
|
||||
);
|
||||
|
||||
let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
|
||||
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
|
||||
|
||||
@@ -46,8 +46,6 @@ pub struct DocumentMetadata {
|
||||
pub text_frames: HashMap<LayerNodeIdentifier, DAffine2>,
|
||||
pub clip_targets: HashSet<NodeId>,
|
||||
pub vector_modify: HashMap<NodeId, VectorGeometry>,
|
||||
/// Per node with a footprint input, the unit square mapped onto its area in document space.
|
||||
pub footprint_areas: HashMap<NodeId, DAffine2>,
|
||||
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
|
||||
/// This provides accurate SegmentIds for layers without explicit Path nodes.
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
|
||||
|
||||
@@ -138,7 +138,6 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.upstream_footprints.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.local_transforms.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.vector_modify.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.footprint_areas.retain(|node, _| nodes.contains(node));
|
||||
self.document_metadata.click_targets.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
self.document_metadata.outlines.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
self.document_metadata.text_frames.retain(|layer, _| self.document_metadata.structure.contains_key(layer));
|
||||
@@ -190,11 +189,6 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.vector_modify = new_vector_modify;
|
||||
}
|
||||
|
||||
/// Update the cached document space areas of the nodes with a footprint input
|
||||
pub fn update_footprint_areas(&mut self, new_footprint_areas: HashMap<NodeId, DAffine2>) {
|
||||
self.document_metadata.footprint_areas = new_footprint_areas;
|
||||
}
|
||||
|
||||
/// Update the layer vector data (for layers without Path nodes)
|
||||
pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>) {
|
||||
self.document_metadata.mark_changed();
|
||||
|
||||
@@ -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::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -181,10 +181,6 @@ 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"],
|
||||
@@ -301,10 +297,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
aliases: &["math_nodes::GradientTypeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
aliases: &["math_nodes::SpreadMethodNode"],
|
||||
@@ -1689,6 +1681,52 @@ 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";
|
||||
@@ -2494,6 +2532,18 @@ 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);
|
||||
|
||||
@@ -2637,8 +2687,11 @@ 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
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 8 {
|
||||
// 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 {
|
||||
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)?;
|
||||
|
||||
@@ -2661,6 +2714,36 @@ 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();
|
||||
@@ -4116,6 +4199,20 @@ 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",
|
||||
@@ -4878,6 +4975,40 @@ 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() {
|
||||
@@ -5440,6 +5571,216 @@ 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),
|
||||
TaggedValue::GradientModel(Default::default()),
|
||||
TaggedValue::GradientDirection(Default::default()),
|
||||
]
|
||||
.map(Some);
|
||||
assert_eq!(
|
||||
values, expected,
|
||||
"the form should become its curvatures before the placement, followed by the default model and direction"
|
||||
);
|
||||
}
|
||||
|
||||
// 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_GRADIENT_DIRECTION),
|
||||
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..8]].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();
|
||||
|
||||
@@ -997,7 +997,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
artboard_name,
|
||||
artboard_count,
|
||||
};
|
||||
let result = self.executor.submit_document_export(document, export_config);
|
||||
let result = self.executor.submit_document_export(document, document_id, export_config);
|
||||
|
||||
if let Err(description) = result {
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
@@ -1124,14 +1124,18 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
}
|
||||
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));
|
||||
let layers = self.active_document().map(|document| {
|
||||
let selected = document.partition_selection().layers;
|
||||
let mut layers = document
|
||||
.metadata()
|
||||
.all_layers()
|
||||
.filter(|layer| selected.contains(layer))
|
||||
.map(|layer| layer.to_node())
|
||||
.collect::<Vec<_>>();
|
||||
layers.reverse();
|
||||
layers
|
||||
});
|
||||
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
|
||||
}
|
||||
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||
|
||||
@@ -217,7 +217,7 @@ impl DrawingToolState {
|
||||
Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: graphene_std::vector::Gradient::from(&ramp),
|
||||
gradient_form: Default::default(),
|
||||
gradient_form: None,
|
||||
gradient_settings: (&ramp).into(),
|
||||
transform: None,
|
||||
}),
|
||||
|
||||
@@ -1,332 +0,0 @@
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::transformation_cage::{BoundingBoxManager, SelectedEdges};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::context::bake_footprint;
|
||||
use graphene_std::platform_application_io::rasterize;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::transform::Footprint;
|
||||
|
||||
/// A transform cage that resizes and moves the area of the selected node with a footprint input.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FootprintCage {
|
||||
target: Option<CageTarget>,
|
||||
drag: Option<CageDrag>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct CageTarget {
|
||||
footprint_input: InputConnector,
|
||||
area: Footprint,
|
||||
/// Spans the area, with the unit square as its bounds.
|
||||
bounding_box: BoundingBoxManager,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct CageDrag {
|
||||
footprint_input: InputConnector,
|
||||
original_area: Footprint,
|
||||
unit_square_to_viewport: DAffine2,
|
||||
kind: CageDragKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum CageDragKind {
|
||||
Resize(SelectedEdges),
|
||||
Move { grab: DVec2 },
|
||||
}
|
||||
|
||||
impl FootprintCage {
|
||||
/// Places the cage on the area of the selected node with a footprint input, or removes it if it is hidden or there is none.
|
||||
pub fn refresh(&mut self, document: &DocumentMessageHandler, visible: bool) {
|
||||
self.target = visible.then(|| Self::find_target(document)).flatten();
|
||||
}
|
||||
|
||||
fn find_target(document: &DocumentMessageHandler) -> Option<CageTarget> {
|
||||
let network_path = document.selection_network_path();
|
||||
let network_interface = &document.network_interface;
|
||||
|
||||
let selected_nodes = network_interface.selected_nodes_in_nested_network(network_path)?;
|
||||
let mut footprint_inputs = selected_nodes.selected_nodes().filter_map(|&node_id| footprint_input(node_id, network_interface, network_path));
|
||||
let footprint_input = footprint_inputs.next()?;
|
||||
if footprint_inputs.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
let node_id = footprint_input.node_id()?;
|
||||
|
||||
let input = network_interface.input_from_connector(&footprint_input, network_path)?;
|
||||
let &TaggedValue::Footprint(area) = input.as_non_exposed_value()? else { return None };
|
||||
|
||||
let unit_square_to_document = *document.metadata().footprint_areas.get(&node_id)?;
|
||||
let unit_square_to_viewport = document.metadata().document_to_viewport * unit_square_to_document;
|
||||
if unit_square_to_viewport.matrix2.determinant() == 0. {
|
||||
return None;
|
||||
}
|
||||
|
||||
let bounding_box = BoundingBoxManager {
|
||||
bounds: [DVec2::ZERO, DVec2::ONE],
|
||||
transform: unit_square_to_viewport,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
Some(CageTarget { footprint_input, area, bounding_box })
|
||||
}
|
||||
|
||||
pub fn overlays(&mut self, overlay_context: &mut OverlayContext) {
|
||||
if let Some(target) = &mut self.target {
|
||||
target.bounding_box.render_overlays(overlay_context, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The cursor for the part of the cage under the pointer, if any.
|
||||
pub fn cursor(&self, input: &InputPreprocessorMessageHandler) -> Option<MouseCursorIcon> {
|
||||
let target = self.target.as_ref()?;
|
||||
|
||||
let edge_cursor = target.bounding_box.get_cursor(input, false, false, None);
|
||||
if edge_cursor != MouseCursorIcon::Default {
|
||||
return Some(edge_cursor);
|
||||
}
|
||||
|
||||
target.contains(input.mouse.position).then_some(MouseCursorIcon::Move)
|
||||
}
|
||||
|
||||
/// Begins resizing or moving the area if the pointer is on the cage, returning whether it did.
|
||||
pub fn begin_drag(&mut self, mouse: DVec2, responses: &mut VecDeque<Message>) -> bool {
|
||||
let Some(target) = &self.target else { return false };
|
||||
let bounding_box = &target.bounding_box;
|
||||
|
||||
let kind = if let Some((top, bottom, left, right)) = bounding_box.check_selected_edges(mouse) {
|
||||
CageDragKind::Resize(SelectedEdges::new(top, bottom, left, right, bounding_box.bounds))
|
||||
} else if target.contains(mouse) {
|
||||
CageDragKind::Move {
|
||||
grab: bounding_box.transform.inverse().transform_point2(mouse),
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
|
||||
self.drag = Some(CageDrag {
|
||||
footprint_input: target.footprint_input,
|
||||
original_area: target.area,
|
||||
unit_square_to_viewport: bounding_box.transform,
|
||||
kind,
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
responses.add(DocumentMessage::NameInteraction { action: "Changed a Footprint".into() });
|
||||
true
|
||||
}
|
||||
|
||||
/// Moves or resizes the area to follow the pointer, keeping its pixel density.
|
||||
pub fn update_drag(&mut self, mouse: DVec2, centered: bool, constrain: bool, responses: &mut VecDeque<Message>) {
|
||||
let Some(drag) = &self.drag else { return };
|
||||
|
||||
let (position, size) = match &drag.kind {
|
||||
CageDragKind::Resize(edges) => {
|
||||
let center = drag.unit_square_to_viewport.transform_point2(DVec2::splat(0.5));
|
||||
let (position, size) = edges.new_size(mouse, drag.unit_square_to_viewport, centered.then_some(center), constrain, None);
|
||||
(position.min(position + size), size.abs())
|
||||
}
|
||||
CageDragKind::Move { grab } => {
|
||||
let pointer = drag.unit_square_to_viewport.inverse().transform_point2(mouse);
|
||||
(pointer - *grab, DVec2::ONE)
|
||||
}
|
||||
};
|
||||
|
||||
let original_area = drag.original_area;
|
||||
let one_pixel = original_area.resolution.as_dvec2().recip();
|
||||
let size = size.max(one_pixel);
|
||||
|
||||
let area = Footprint {
|
||||
transform: original_area.transform * DAffine2::from_scale_angle_translation(size, 0., position),
|
||||
resolution: (original_area.resolution.as_dvec2() * size).round().as_uvec2().max(UVec2::ONE),
|
||||
..original_area
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: drag.footprint_input,
|
||||
input: NodeInput::value(TaggedValue::Footprint(area), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Keeps the drag in place on the document while the viewport pans by `shift`.
|
||||
pub fn pan(&mut self, shift: DVec2) {
|
||||
if let Some(drag) = &mut self.drag {
|
||||
drag.unit_square_to_viewport.translation += shift;
|
||||
}
|
||||
}
|
||||
|
||||
/// Finishes the drag, undoing its changes if it was aborted.
|
||||
pub fn end_drag(&mut self, aborted: bool, responses: &mut VecDeque<Message>) {
|
||||
if self.drag.take().is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
responses.add(if aborted { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction });
|
||||
}
|
||||
}
|
||||
|
||||
/// The input holding the footprint of a node that has one.
|
||||
fn footprint_input(node_id: NodeId, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option<InputConnector> {
|
||||
let reference = network_interface.reference(&node_id, network_path)?;
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER) {
|
||||
Some(InputConnector::node(node_id, bake_footprint::FootprintInput))
|
||||
} else if reference == DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER) {
|
||||
Some(InputConnector::node(node_id, rasterize::FootprintInput))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl CageTarget {
|
||||
fn contains(&self, viewport_point: DVec2) -> bool {
|
||||
(self.bounding_box.transform * Quad::from_box(self.bounding_box.bounds)).contains(viewport_point)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_bake_footprint_node_in_a_layer_reports_where_its_area_lies() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
|
||||
let document = editor.active_document();
|
||||
let input = document.network_interface.input_from_connector(&InputConnector::node(node_id, bake_footprint::FootprintInput), &[]);
|
||||
let Some(&TaggedValue::Footprint(area)) = input.and_then(NodeInput::as_non_exposed_value) else {
|
||||
panic!("the node should have a footprint value")
|
||||
};
|
||||
|
||||
let metadata = document.metadata();
|
||||
let baked_area = metadata.footprint_areas.get(&node_id).expect("the render should report where the node baked its area");
|
||||
let layer_content_to_viewport = metadata.upstream_footprints.get(&layer.to_node()).expect("the render should report the layer's footprint").transform;
|
||||
let expected = metadata.rendered_document_to_viewport.inverse() * layer_content_to_viewport * area.transform;
|
||||
assert!(baked_area.abs_diff_eq(expected, 1e-9), "{baked_area:?} should be {expected:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_baked_area_moves_with_a_transform_applied_after_it() {
|
||||
use graphene_std::transform_nodes::transform;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let bake_footprint_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
|
||||
node_id: bake_footprint_node,
|
||||
parent: layer,
|
||||
})
|
||||
.await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
let untransformed = *editor.active_document().metadata().footprint_areas.get(&bake_footprint_node).expect("the area should be reported");
|
||||
|
||||
let transform_node = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(transform::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::MoveNodeToChainStart {
|
||||
node_id: transform_node,
|
||||
parent: layer,
|
||||
})
|
||||
.await;
|
||||
let translation = DVec2::new(100., 50.);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(transform_node, transform::TranslationInput),
|
||||
input: NodeInput::value(TaggedValue::DVec2(translation), false),
|
||||
})
|
||||
.await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
|
||||
let transformed = *editor
|
||||
.active_document()
|
||||
.metadata()
|
||||
.footprint_areas
|
||||
.get(&bake_footprint_node)
|
||||
.expect("the area should still be reported");
|
||||
let expected = DAffine2::from_translation(translation) * untransformed;
|
||||
assert!(transformed.abs_diff_eq(expected, 1e-9), "{transformed:?} should be {expected:?}");
|
||||
}
|
||||
|
||||
/// Drags the cage of a 'Bake Footprint' node in a layer between two points of its unit square, giving its area before and after.
|
||||
async fn drag_cage(from: DVec2, to: DVec2) -> (Footprint, Footprint) {
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("drawing a rectangle should create a layer");
|
||||
let node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(bake_footprint::IDENTIFIER)).await;
|
||||
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
|
||||
|
||||
let area = Footprint {
|
||||
transform: DAffine2::from_scale(DVec2::splat(100.)),
|
||||
resolution: UVec2::splat(200),
|
||||
..Default::default()
|
||||
};
|
||||
let footprint_input = InputConnector::node(node_id, bake_footprint::FootprintInput);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInput {
|
||||
input_connector: footprint_input,
|
||||
input: NodeInput::value(TaggedValue::Footprint(area), false),
|
||||
})
|
||||
.await;
|
||||
editor.eval_graph_until_finished().await.expect("the graph should evaluate");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }).await;
|
||||
|
||||
let metadata = editor.active_document().metadata();
|
||||
let unit_square_to_viewport = metadata.document_to_viewport * *metadata.footprint_areas.get(&node_id).expect("the area should be reported");
|
||||
let (from, to) = (unit_square_to_viewport.transform_point2(from), unit_square_to_viewport.transform_point2(to));
|
||||
|
||||
editor.select_tool(ToolType::Select).await;
|
||||
editor.handle_message(SelectToolMessage::Overlays { context: OverlayContext::default() }).await;
|
||||
editor.move_mouse(from.x, from.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(from.x, from.y, ModifierKeys::empty()).await;
|
||||
editor.move_mouse(to.x, to.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
editor.left_mouseup(to.x, to.y, ModifierKeys::empty()).await;
|
||||
|
||||
let input = editor.active_document().network_interface.input_from_connector(&footprint_input, &[]);
|
||||
let Some(&TaggedValue::Footprint(dragged)) = input.and_then(NodeInput::as_non_exposed_value) else {
|
||||
panic!("the node should have a footprint value")
|
||||
};
|
||||
(area, dragged)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dragging_the_right_edge_of_the_cage_widens_the_area_and_its_resolution() {
|
||||
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(1.5, 0.5)).await;
|
||||
|
||||
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(1.5, 1.));
|
||||
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
|
||||
assert_eq!(dragged.resolution, UVec2::new(300, 200));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dragging_the_right_edge_onto_the_left_one_keeps_one_pixel_of_width() {
|
||||
let (area, dragged) = drag_cage(DVec2::new(1., 0.5), DVec2::new(0., 0.5)).await;
|
||||
|
||||
let one_pixel = 1. / area.resolution.x as f64;
|
||||
let expected_transform = area.transform * DAffine2::from_scale(DVec2::new(one_pixel, 1.));
|
||||
assert!(dragged.transform.abs_diff_eq(expected_transform, 1e-9), "{:?} should be {expected_transform:?}", dragged.transform);
|
||||
assert_eq!(dragged.resolution, UVec2::new(1, 200));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,2 @@
|
||||
pub mod footprint_cage;
|
||||
pub mod gizmo_manager;
|
||||
pub mod shape_gizmos;
|
||||
@@ -0,0 +1,454 @@
|
||||
//! Geometry of the Gradient tool's gizmos, in gradient space, where the gradient line runs from the start point at the origin to the end
|
||||
//! point at (1, 0). Each end's contour passes through its endpoint with its center on the line, set by its curvature, as described
|
||||
//! in [`graphene_std::vector::gradient_standard`].
|
||||
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature};
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
|
||||
/// The farthest a drawn contour bows from its chords between the points it's drawn through, in viewport pixels.
|
||||
const CONTOUR_SAG_TOLERANCE: f64 = 0.25;
|
||||
|
||||
/// The most chords a contour is drawn with.
|
||||
const CONTOUR_MAX_CHORDS: usize = 1024;
|
||||
|
||||
/// One of the gradient line's two ends, each with its own contour.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GradientEnd {
|
||||
Start,
|
||||
End,
|
||||
}
|
||||
|
||||
impl GradientEnd {
|
||||
/// Its index in a `[start, end]` pair of curvatures.
|
||||
pub fn index(self) -> usize {
|
||||
match self {
|
||||
Self::Start => 0,
|
||||
Self::End => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Its endpoint in gradient space.
|
||||
pub fn endpoint(self) -> DVec2 {
|
||||
match self {
|
||||
Self::Start => DVec2::ZERO,
|
||||
Self::End => DVec2::X,
|
||||
}
|
||||
}
|
||||
|
||||
/// Which way along the gradient line points toward the other end, which a positive curvature bows this end's contour toward.
|
||||
fn inward(self) -> f64 {
|
||||
match self {
|
||||
Self::Start => 1.,
|
||||
Self::End => -1.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The center of this end's contour in gradient space for its `curvature`, or `None` for a line.
|
||||
pub fn contour_center(end: GradientEnd, curvature: f64) -> Option<DVec2> {
|
||||
let radius = curvature_radius(curvature);
|
||||
radius.is_finite().then(|| end.endpoint() + DVec2::new(end.inward() * radius, 0.))
|
||||
}
|
||||
|
||||
/// The curvature that centers this end's contour at `axis_position` along the gradient line, as dragging its center dot there does.
|
||||
pub fn center_curvature(end: GradientEnd, axis_position: f64) -> f64 {
|
||||
radius_curvature((axis_position - end.endpoint().x) * end.inward())
|
||||
}
|
||||
|
||||
/// The curvature of this end's contour through `point`, the circle through it and the endpoint with its center on the gradient line,
|
||||
/// which is the line across the gradient line where `point` lies across from the endpoint. `None` at the endpoint itself.
|
||||
pub fn rim_curvature(end: GradientEnd, point: DVec2) -> Option<f64> {
|
||||
let offset = point - end.endpoint();
|
||||
let distance_squared = offset.length_squared();
|
||||
|
||||
// The inverse of the radius `|offset|² / 2 offset.x`, which stays finite where the radius doesn't
|
||||
(distance_squared > 0.).then(|| (2. * offset.x * end.inward() / distance_squared).atan() / FRAC_PI_2)
|
||||
}
|
||||
|
||||
/// The signed radius that resizes this end's contour (from its `curvature`) to bring the place on its rim nearest `grabbed` as near `pointer` as it gets,
|
||||
/// both in the space `unit_to_viewport` maps to, and where that place lands there. `None` for a line or a point, which no resizing moves a place on.
|
||||
pub fn rim_resized_toward(end: GradientEnd, curvature: f64, grabbed: DVec2, pointer: DVec2, unit_to_viewport: DAffine2) -> Option<(f64, DVec2)> {
|
||||
let radius = curvature_radius(curvature);
|
||||
if !radius.is_finite() || radius == 0. {
|
||||
return None;
|
||||
}
|
||||
let inward = DVec2::new(end.inward(), 0.);
|
||||
|
||||
// Each circle through the endpoint is the others scaled about it, so the place keeps its angle around them from the endpoint, measured at the center
|
||||
let to_endpoint = -radius * inward;
|
||||
let to_grabbed = unit_to_viewport.inverse().transform_point2(grabbed) - end.endpoint() - radius * inward;
|
||||
let angle = to_endpoint.perp_dot(to_grabbed).atan2(to_endpoint.dot(to_grabbed));
|
||||
|
||||
// At that angle, the place lies the radius times this from the endpoint, a line the pointer projects onto
|
||||
let direction = unit_to_viewport.transform_vector2(inward - DVec2::from_angle(angle).rotate(inward));
|
||||
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
|
||||
let resized = (pointer - endpoint).dot(direction) / direction.length_squared();
|
||||
resized.is_finite().then(|| (resized, endpoint + resized * direction))
|
||||
}
|
||||
|
||||
/// Whether a gradient with these curvatures has a focus to move: a point for its start contour and a circle for its end contour.
|
||||
pub fn has_focus(curvatures: [f64; 2]) -> bool {
|
||||
let end_radius = curvature_radius(curvatures[1]);
|
||||
curvature_radius(curvatures[0]) == 0. && end_radius.is_finite() && end_radius != 0.
|
||||
}
|
||||
|
||||
/// A gradient line in the gradient space of the line it replaces, with the curvature it gives the end contour.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RefocusedLine {
|
||||
pub start: DVec2,
|
||||
pub end: DVec2,
|
||||
pub end_curvature: f64,
|
||||
}
|
||||
|
||||
/// The line of a gradient whose start point (its focus) moves to `focus` while its end circle from `end_curvature` stays put: from the focus through the
|
||||
/// circle's center to its far side, with the end curvature keeping that circle. A focus on the center keeps `direction`. `None` unless the end is a circle.
|
||||
pub fn refocused_line(focus: DVec2, end_curvature: f64, direction: DVec2) -> Option<RefocusedLine> {
|
||||
let radius = curvature_radius(end_curvature);
|
||||
if !radius.is_finite() || radius == 0. {
|
||||
return None;
|
||||
}
|
||||
let (center, size) = (DVec2::new(1. - radius, 0.), radius.abs());
|
||||
|
||||
let to_center = center - focus;
|
||||
let distance = to_center.length();
|
||||
let direction = if distance > 0. { to_center / distance } else { direction.try_normalize()? };
|
||||
|
||||
Some(RefocusedLine {
|
||||
start: focus,
|
||||
end: center + direction * size,
|
||||
end_curvature: radius_curvature(size / (distance + size)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The transform placing a gradient along `line`, given in the gradient space of the `old` transform. Its frame turns and scales uniformly within
|
||||
/// that space, so a contour that's a circle there keeps its shape, even where `old` stretches it into an ellipse.
|
||||
pub fn transform_along(old: DAffine2, line: RefocusedLine) -> DAffine2 {
|
||||
let x_axis = line.end - line.start;
|
||||
old * DAffine2::from_cols(x_axis, x_axis.perp(), line.start)
|
||||
}
|
||||
|
||||
/// One side of the gradient line, across which its perpendicular axis points one way or the other.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LineSide {
|
||||
Positive,
|
||||
Negative,
|
||||
}
|
||||
|
||||
impl LineSide {
|
||||
/// Which way across the gradient line its perpendicular axis points to reach this side.
|
||||
pub fn sign(self) -> f64 {
|
||||
match self {
|
||||
Self::Positive => 1.,
|
||||
Self::Negative => -1.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The semi-minor axis to this side of this end's circle from its `curvature`, from the circle's center a radius across the gradient line to where
|
||||
/// a handle stretching the gradient across its line sits, in gradient space. `None` for a line or a point.
|
||||
pub fn aspect_axis(end: GradientEnd, curvature: f64, side: LineSide) -> Option<[DVec2; 2]> {
|
||||
let radius = curvature_radius(curvature).abs();
|
||||
let center = contour_center(end, curvature).filter(|_| radius > 0.)?;
|
||||
Some([center, center + DVec2::new(0., side.sign() * radius)])
|
||||
}
|
||||
|
||||
/// The transform stretched across its line so the point `handle` in its gradient space lies as far across the line as `pointer` does
|
||||
/// (in the transform's output space), keeping the line and how far its perpendicular axis leans along it. `None` where it would collapse.
|
||||
pub fn stretched_transform(transform: DAffine2, handle: DVec2, pointer: DVec2) -> Option<DAffine2> {
|
||||
let x_axis = transform.matrix2.x_axis;
|
||||
let along = x_axis.try_normalize()?;
|
||||
let across = along.perp();
|
||||
|
||||
// The handle lies `handle.y` times the perpendicular axis's span across the line
|
||||
let span_across = (pointer - transform.translation).dot(across) / handle.y;
|
||||
if !(span_across.abs() > 1e-9 * x_axis.length()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let y_axis = along * transform.matrix2.y_axis.dot(along) + across * span_across;
|
||||
Some(DAffine2::from_cols(x_axis, y_axis, transform.translation))
|
||||
}
|
||||
|
||||
/// The smallest factor `transform` scales any length by, the least singular value of its linear part.
|
||||
fn least_scale(transform: DAffine2) -> f64 {
|
||||
let [x_axis, y_axis] = [transform.matrix2.x_axis, transform.matrix2.y_axis];
|
||||
let determinant = transform.matrix2.determinant().abs();
|
||||
|
||||
// Of the singular values `√(mean ± √(mean² - determinant²))`, the least is the determinant over the greatest, which avoids cancellation
|
||||
let mean = (x_axis.length_squared() + y_axis.length_squared()) / 2.;
|
||||
let greatest = (mean + (mean * mean - determinant * determinant).max(0.).sqrt()).sqrt();
|
||||
if greatest > 0. { determinant / greatest } else { 0. }
|
||||
}
|
||||
|
||||
/// Points through which this end's contour is drawn in the viewport, from `unit_to_viewport`, as far as `reach` viewport pixels from
|
||||
/// its endpoint along it (or around the whole circle if that's shorter). Empty for a point, or where the transform collapses.
|
||||
pub fn contour_polyline(end: GradientEnd, curvature: f64, unit_to_viewport: DAffine2, reach: f64) -> Vec<DVec2> {
|
||||
let radius = curvature_radius(curvature);
|
||||
let endpoint = end.endpoint();
|
||||
|
||||
let least_scale = least_scale(unit_to_viewport);
|
||||
if radius == 0. || least_scale <= 0. {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// A line runs straight across the gradient line through the endpoint
|
||||
if radius.is_infinite() {
|
||||
let Some(direction) = unit_to_viewport.transform_vector2(DVec2::Y).try_normalize() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let viewport_endpoint = unit_to_viewport.transform_point2(endpoint);
|
||||
return vec![viewport_endpoint - direction * reach, viewport_endpoint + direction * reach];
|
||||
}
|
||||
|
||||
// Sweep from the endpoint both ways around the circle, by the angle reaching `reach` pixels at the least scale
|
||||
let size = radius.abs();
|
||||
let sweep = (reach / (size * least_scale)).min(PI);
|
||||
|
||||
// Uniform steps small enough that each chord stays within the sag tolerance, even at twice the longest axis's scale (which bounds the greatest)
|
||||
let viewport_radius_bound = size * unit_to_viewport.matrix2.x_axis.length().max(unit_to_viewport.matrix2.y_axis.length()) * 2.;
|
||||
let step = (8. * CONTOUR_SAG_TOLERANCE / viewport_radius_bound).sqrt();
|
||||
let chords_each_way = ((sweep / step).ceil() as usize).clamp(4, CONTOUR_MAX_CHORDS / 2);
|
||||
let chords = 2 * chords_each_way;
|
||||
|
||||
// Measured from the endpoint rather than the center, the points stay precise on huge circles
|
||||
(0..=chords)
|
||||
.map(|index| {
|
||||
let angle = sweep * (2. * index as f64 / chords as f64 - 1.);
|
||||
let half_sine = (angle / 2.).sin();
|
||||
let offset = DVec2::new(2. * end.inward() * radius * half_sine * half_sine, size * angle.sin());
|
||||
unit_to_viewport.transform_point2(endpoint + offset)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The distance from `point` to the nearest place on the polyline through `points`, or `None` if it has none.
|
||||
pub fn distance_to_polyline(points: &[DVec2], point: DVec2) -> Option<f64> {
|
||||
if let [only] = points {
|
||||
return Some(only.distance(point));
|
||||
}
|
||||
|
||||
points
|
||||
.windows(2)
|
||||
.map(|pair| {
|
||||
let (start, end) = (pair[0], pair[1]);
|
||||
let along = (point - start).dot(end - start) / (end - start).length_squared();
|
||||
let nearest = if along.is_finite() { start.lerp(end, along.clamp(0., 1.)) } else { start };
|
||||
nearest.distance(point)
|
||||
})
|
||||
.min_by(f64::total_cmp)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Curvatures through circles of each size and bend, both lines, and the points.
|
||||
fn curvatures() -> impl Iterator<Item = f64> {
|
||||
(-20..=20).map(|step| step as f64 * 0.05)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rim_dragged_to_a_point_takes_the_curvature_of_the_circle_through_it() {
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for point in [DVec2::new(0.3, 0.4), DVec2::new(-0.7, 1.2), DVec2::new(2.5, -0.25), DVec2::new(0.5, 3.)] {
|
||||
let curvature = rim_curvature(end, point).unwrap();
|
||||
|
||||
// The contour of that curvature passes through the point, centered on the gradient line
|
||||
let center = contour_center(end, curvature).unwrap();
|
||||
assert!(center.y == 0.);
|
||||
let radius = center.distance(end.endpoint());
|
||||
assert!((center.distance(point) - radius).abs() < 1e-9 * radius.max(1.), "{end:?} through {point}: curvature {curvature}");
|
||||
}
|
||||
|
||||
// Straight across from the endpoint is the line, and either side of it bends toward that side
|
||||
let across = end.endpoint() + DVec2::Y;
|
||||
assert_eq!(rim_curvature(end, across), Some(0.));
|
||||
let inward = DVec2::new(end.inward() * 0.1, 0.);
|
||||
assert!(rim_curvature(end, across + inward).unwrap() > 0.);
|
||||
assert!(rim_curvature(end, across - inward).unwrap() < 0.);
|
||||
|
||||
// The endpoint is on every contour, so it sets none
|
||||
assert_eq!(rim_curvature(end, end.endpoint()), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rim_dragged_along_its_own_contour_keeps_its_curvature() {
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for curvature in curvatures().filter(|curvature| curvature.abs() != 1.) {
|
||||
for point in contour_polyline(end, curvature, DAffine2::IDENTITY, 3.) {
|
||||
// Every point but the endpoint sets the curvature back, as a line's points beside the endpoint do
|
||||
if point.distance(end.endpoint()) < 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let found = rim_curvature(end, point).unwrap();
|
||||
assert!((found - curvature).abs() < 1e-9, "{end:?} curvature {curvature} at {point}: {found}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_center_dragged_along_the_line_takes_the_curvature_centered_there() {
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for curvature in curvatures().filter(|&curvature| curvature != 0.) {
|
||||
let center = contour_center(end, curvature).unwrap();
|
||||
let found = center_curvature(end, center.x);
|
||||
|
||||
// A point is both -1 and 1, which the drag settles at -1
|
||||
let expected = if curvature.abs() == 1. { -1. } else { curvature };
|
||||
assert!((found - expected).abs() < 1e-9, "{end:?} curvature {curvature}: {found}");
|
||||
}
|
||||
|
||||
// Toward the other end bows toward it, and onto the endpoint is a point
|
||||
assert!(center_curvature(end, 0.5) > 0.);
|
||||
assert!(center_curvature(end, end.endpoint().x - end.inward()) < 0.);
|
||||
assert_eq!(center_curvature(end, end.endpoint().x), -1.);
|
||||
}
|
||||
|
||||
// The start contour centered at the end point, and the end contour at the start point, are each the circle of radius 1 between them
|
||||
assert!((center_curvature(GradientEnd::Start, 1.) - 0.5).abs() < 1e-12);
|
||||
assert!((center_curvature(GradientEnd::End, 0.) - 0.5).abs() < 1e-12);
|
||||
}
|
||||
|
||||
/// The center and radius of the end circle of a gradient along `line`, in the gradient space `line` is given in.
|
||||
fn end_circle(line: RefocusedLine) -> (DVec2, f64) {
|
||||
let radius = curvature_radius(line.end_curvature);
|
||||
(line.start.lerp(line.end, 1. - radius), radius.abs() * line.start.distance(line.end))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_moved_focus_keeps_the_end_circle_in_place() {
|
||||
// The end circle of radius 0.75 centered at 0.25, with foci inside it, outside it, and behind its center
|
||||
let end_curvature = radius_curvature(0.75);
|
||||
let (center, radius) = (DVec2::new(0.25, 0.), 0.75);
|
||||
for focus in [DVec2::new(0.1, 0.3), DVec2::new(-0.2, -0.4), DVec2::new(3., 2.), DVec2::new(0.9, 0.), DVec2::new(-5., 0.)] {
|
||||
let line = refocused_line(focus, end_curvature, DVec2::X).unwrap();
|
||||
assert_eq!(line.start, focus);
|
||||
|
||||
let (new_center, new_radius) = end_circle(line);
|
||||
assert!(new_center.distance(center) < 1e-12 && (new_radius - radius).abs() < 1e-12, "focus {focus}: {line:?}");
|
||||
|
||||
// The line runs on through the center to the circle's far side
|
||||
assert!((line.end.distance(focus) - (focus.distance(center) + radius)).abs() < 1e-12, "focus {focus}: {line:?}");
|
||||
}
|
||||
|
||||
// A focus off the circle's line still aims the line through its center
|
||||
let line = refocused_line(DVec2::new(0.25, 2.), end_curvature, DVec2::X).unwrap();
|
||||
assert!(line.end.abs_diff_eq(DVec2::new(0.25, -0.75), 1e-12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_focus_on_the_center_keeps_the_direction_and_makes_the_radial_form() {
|
||||
let end_curvature = radius_curvature(0.75);
|
||||
let line = refocused_line(contour_center(GradientEnd::End, end_curvature).unwrap(), end_curvature, DVec2::new(0., 2.)).unwrap();
|
||||
assert_eq!(line.end_curvature, 0.5);
|
||||
assert!(line.end.abs_diff_eq(DVec2::new(0.25, 0.75), 1e-12));
|
||||
assert_eq!(
|
||||
graphene_std::vector::style::GradientForm::from_curvatures([-1., line.end_curvature]),
|
||||
Some(graphene_std::vector::style::GradientForm::Radial)
|
||||
);
|
||||
|
||||
// Only an end circle has a focus to move around
|
||||
assert!(has_focus([-1., 0.5]) && has_focus([1., -0.3]));
|
||||
assert!(!has_focus([0., 0.5]) && !has_focus([-1., 0.]) && !has_focus([-1., 1.]));
|
||||
assert_eq!(refocused_line(DVec2::ZERO, 0., DVec2::X), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refocused_transform_keeps_an_elliptical_end_contour_in_place() {
|
||||
// A radial gradient squashed to half its height and skewed, whose focus moves off its line
|
||||
let old = DAffine2::from_cols(DVec2::new(100., 20.), DVec2::new(-5., 50.), DVec2::new(30., 40.));
|
||||
let line = refocused_line(DVec2::new(0.3, 0.4), 0.5, DVec2::X).unwrap();
|
||||
let new = transform_along(old, line);
|
||||
|
||||
// The end contour's points land on the same ellipse before and after (within its chords' sag), though spread differently around it
|
||||
let before = contour_polyline(GradientEnd::End, 0.5, old, 1e6);
|
||||
let after = contour_polyline(GradientEnd::End, line.end_curvature, new, 1e6);
|
||||
for point in after {
|
||||
assert!(distance_to_polyline(&before, point).unwrap() <= CONTOUR_SAG_TOLERANCE, "{point} left the ellipse");
|
||||
}
|
||||
assert!(new.transform_point2(DVec2::ZERO).abs_diff_eq(old.transform_point2(DVec2::new(0.3, 0.4)), 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_end_circle_has_an_aspect_handle_a_radius_to_either_side_of_its_center() {
|
||||
use LineSide::{Negative, Positive};
|
||||
|
||||
// The radial form's end circle around the start point, but not its start point
|
||||
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Positive), Some([DVec2::ZERO, DVec2::Y]));
|
||||
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Negative), Some([DVec2::ZERO, -DVec2::Y]));
|
||||
assert_eq!(aspect_axis(GradientEnd::Start, -1., Positive), None);
|
||||
|
||||
// Each of two crossing circles, and a huge nearly flat one
|
||||
let radius = curvature_radius(0.6);
|
||||
assert_eq!(aspect_axis(GradientEnd::Start, 0.6, Positive), Some([DVec2::new(radius, 0.), DVec2::new(radius, radius)]));
|
||||
assert_eq!(aspect_axis(GradientEnd::End, 0.6, Negative), Some([DVec2::new(1. - radius, 0.), DVec2::new(1. - radius, -radius)]));
|
||||
assert!(aspect_axis(GradientEnd::End, 1e-3, Positive).is_some_and(|[_, handle]| handle.y > 100.));
|
||||
|
||||
// Lines and points have none
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
for curvature in [0., 1., -1.] {
|
||||
for side in [Positive, Negative] {
|
||||
assert_eq!(aspect_axis(end, curvature, side), None, "{end:?} curvature {curvature} {side:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stretching_moves_each_aspect_handle_across_the_line_and_keeps_the_line() {
|
||||
// A skewed gradient, its perpendicular axis leaning along the line
|
||||
let transform = DAffine2::from_cols(DVec2::new(80., 60.), DVec2::new(-50., 70.), DVec2::new(10., 20.));
|
||||
let along = transform.matrix2.x_axis.normalize();
|
||||
|
||||
// The radial form's handles and those of two crossing circles of different sizes, each pulled to its own side of the line
|
||||
let axes = [(GradientEnd::End, 0.5), (GradientEnd::Start, 0.6), (GradientEnd::End, 0.3)];
|
||||
let handles = axes
|
||||
.into_iter()
|
||||
.flat_map(|(end, curvature)| [LineSide::Positive, LineSide::Negative].map(|side| (aspect_axis(end, curvature, side).unwrap()[1], side)));
|
||||
for (handle, side) in handles {
|
||||
let pointer = transform.transform_point2(DVec2::new(0.4, side.sign() * 0.7));
|
||||
let stretched = stretched_transform(transform, handle, pointer).unwrap();
|
||||
assert!(stretched.matrix2.determinant() * transform.matrix2.determinant() > 0., "the gradient shouldn't mirror");
|
||||
for point in [DVec2::ZERO, DVec2::X] {
|
||||
assert!(stretched.transform_point2(point).abs_diff_eq(transform.transform_point2(point), 1e-9));
|
||||
}
|
||||
|
||||
// The handle lands as far across the line as the pointer, sliding only across it, and the lean along the line stays
|
||||
let (old_handle, new_handle) = (transform.transform_point2(handle), stretched.transform_point2(handle));
|
||||
assert!(((new_handle - transform.translation).dot(along.perp()) - (pointer - transform.translation).dot(along.perp())).abs() < 1e-9);
|
||||
assert!((new_handle - old_handle).dot(along).abs() < 1e-9);
|
||||
assert!((stretched.matrix2.y_axis.dot(along) - transform.matrix2.y_axis.dot(along)).abs() < 1e-9);
|
||||
|
||||
// Onto the line, it would collapse
|
||||
assert_eq!(stretched_transform(transform, handle, transform.transform_point2(DVec2::new(0.5, 0.))), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contours_are_drawn_through_their_endpoints_out_to_their_reach() {
|
||||
let unit_to_viewport = DAffine2::from_scale_angle_translation(DVec2::new(200., 100.), 0.3, DVec2::new(40., 60.));
|
||||
for end in [GradientEnd::Start, GradientEnd::End] {
|
||||
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
|
||||
|
||||
// A point draws nothing, and a line is one long chord through the endpoint
|
||||
assert!(contour_polyline(end, 1., unit_to_viewport, 500.).is_empty());
|
||||
let line = contour_polyline(end, 0., unit_to_viewport, 500.);
|
||||
assert_eq!(line.len(), 2);
|
||||
assert!(distance_to_polyline(&line, endpoint).unwrap() < 1e-9);
|
||||
|
||||
// A small circle is drawn whole, closing on itself, and a huge one only as far as its reach, nearly straight
|
||||
let small = contour_polyline(end, 0.5, unit_to_viewport, 500.);
|
||||
assert!(small.first().unwrap().distance(*small.last().unwrap()) < 1e-6);
|
||||
let huge = contour_polyline(end, 1e-6, unit_to_viewport, 500.);
|
||||
let farthest = huge.iter().map(|point| point.distance(endpoint)).fold(0., f64::max);
|
||||
assert!((400. ..=1000.).contains(&farthest), "a huge circle should reach about 500 pixels, not {farthest}");
|
||||
|
||||
for polyline in [small, huge] {
|
||||
assert!(distance_to_polyline(&polyline, endpoint).unwrap() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use graphene_std::Color;
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||
use graphene_std::vector::style::{FillChoice, GradientDirection, GradientModel, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
|
||||
use graphene_std::vector::{Gradient, GradientForm, GradientRamp, GradientSettings, PointId, SegmentId, VectorModificationType};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use std::collections::VecDeque;
|
||||
@@ -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_form::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
||||
@@ -428,6 +428,17 @@ 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
|
||||
@@ -830,10 +841,27 @@ 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,
|
||||
/// Its model and direction, each unless the graph feeds it.
|
||||
pub model: Option<GradientModel>,
|
||||
pub direction: Option<GradientDirection>,
|
||||
pub settings: GradientSettings,
|
||||
pub transform: DAffine2,
|
||||
/// Whether the transform input holds a plain value (so it may be written to) rather than a wire.
|
||||
@@ -849,9 +877,15 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
};
|
||||
let settings = GradientSettings::from(ramp);
|
||||
let stops = Gradient::from(ramp);
|
||||
let gradient_form = match fill_node.input(fill::GradientFormInput).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::GradientForm(value)) => value,
|
||||
_ => GradientForm::default(),
|
||||
let curvatures = fill_node_curvatures(fill_node);
|
||||
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default();
|
||||
let model = match fill_node.input(fill::ModelInput).and_then(NodeInput::as_non_exposed_value) {
|
||||
Some(&TaggedValue::GradientModel(model)) => Some(model),
|
||||
_ => None,
|
||||
};
|
||||
let direction = match fill_node.input(fill::DirectionInput).and_then(NodeInput::as_non_exposed_value) {
|
||||
Some(&TaggedValue::GradientDirection(direction)) => Some(direction),
|
||||
_ => None,
|
||||
};
|
||||
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());
|
||||
@@ -863,7 +897,10 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
|
||||
Some(FillNodeGradient {
|
||||
stops,
|
||||
curvatures,
|
||||
gradient_form,
|
||||
model,
|
||||
direction,
|
||||
settings,
|
||||
transform,
|
||||
transform_is_value: transform_input.is_some(),
|
||||
@@ -1005,10 +1042,6 @@ 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,
|
||||
@@ -1019,7 +1052,7 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: Gradient::from(ramp),
|
||||
gradient_form,
|
||||
gradient_form: None,
|
||||
gradient_settings: ramp.into(),
|
||||
transform: Some(transform),
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@ pub mod color_selector;
|
||||
pub mod compass_rose;
|
||||
pub mod edit_target;
|
||||
pub mod gizmos;
|
||||
pub mod gradient_gizmos;
|
||||
pub mod graph_modification_utils;
|
||||
pub mod layer_origin_cross;
|
||||
pub mod measure;
|
||||
|
||||
@@ -92,6 +92,8 @@ pub struct PointOptions {
|
||||
pub box_features: Option<BoxFeatures>,
|
||||
/// Whether the grid is left out, as for a turn, which the grid would otherwise step at odd angles.
|
||||
pub ignores_grid: bool,
|
||||
/// Whether the tool marks where a press would land in its own way, so nothing marks it there unless a snap is named.
|
||||
pub marked_by_tool: bool,
|
||||
}
|
||||
|
||||
/// Which features of a gesture make up a box.
|
||||
@@ -122,6 +124,8 @@ pub struct Shown {
|
||||
pub features: Vec<DVec2>,
|
||||
/// The index of the feature the pointer carries.
|
||||
pub lead: usize,
|
||||
/// Whether the tool marks where a press would land, as [`PointOptions::marked_by_tool`] tells.
|
||||
pub marked_by_tool: bool,
|
||||
}
|
||||
|
||||
/// What a kept set of constructions was found for, which it stays good for.
|
||||
@@ -321,6 +325,7 @@ impl SnapSession {
|
||||
features: features.iter().map(|feature| feature.position(parameters)).collect(),
|
||||
lead,
|
||||
outcome,
|
||||
marked_by_tool: options.marked_by_tool,
|
||||
});
|
||||
|
||||
// A crossing, or the grid, can hold the box anywhere along the track that evens out its gaps, so they are measured again where it landed
|
||||
@@ -399,6 +404,7 @@ impl SnapSession {
|
||||
features: vec![position_of(snapped)],
|
||||
lead: 0,
|
||||
outcome,
|
||||
marked_by_tool: false,
|
||||
});
|
||||
|
||||
snapped
|
||||
|
||||
@@ -19,14 +19,24 @@ impl SnapSession {
|
||||
self.draw_awake(target, to_viewport, overlay_context);
|
||||
}
|
||||
|
||||
let Some(Shown { outcome, features, lead, .. }) = &self.shown else { return };
|
||||
let Some(Shown {
|
||||
outcome,
|
||||
features,
|
||||
lead,
|
||||
marked_by_tool,
|
||||
}) = &self.shown
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Before a press, the point is marked where the press would place it, even with no snap to name
|
||||
if matches!(outcome.snap, Snap::Grid | Snap::Free)
|
||||
&& self.gesture.is_none()
|
||||
&& let Some(&position) = features.get(*lead)
|
||||
{
|
||||
overlay_context.square(to_viewport.transform_point2(position), Some(4.), Some(COLOR_OVERLAY_BLUE), Some(COLOR_OVERLAY_BLUE));
|
||||
if !marked_by_tool {
|
||||
overlay_context.square(to_viewport.transform_point2(position), Some(4.), Some(COLOR_OVERLAY_BLUE), Some(COLOR_OVERLAY_BLUE));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -15,7 +15,6 @@ use crate::messages::tool::common_functionality::color_selector::{
|
||||
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, has_paintable_selection, swap_fill_and_stroke, sync_drawing_state,
|
||||
};
|
||||
use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose};
|
||||
use crate::messages::tool::common_functionality::gizmos::footprint_cage::FootprintCage;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::measure;
|
||||
use crate::messages::tool::common_functionality::pivot::{Pivot, PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget};
|
||||
@@ -506,7 +505,6 @@ enum SelectToolFsmState {
|
||||
},
|
||||
RotatingBounds,
|
||||
DraggingPivot,
|
||||
DraggingFootprintCage,
|
||||
}
|
||||
|
||||
impl Default for SelectToolFsmState {
|
||||
@@ -547,7 +545,6 @@ struct SelectToolData {
|
||||
axis_align: bool,
|
||||
non_duplicated_layers: Option<Vec<LayerNodeIdentifier>>,
|
||||
bounding_box_manager: Option<BoundingBoxManager>,
|
||||
footprint_cage: FootprintCage,
|
||||
cursor: MouseCursorIcon,
|
||||
pivot_gizmo: PivotGizmo,
|
||||
/// The pivot as it was when a drag of it began, restored if the drag is aborted.
|
||||
@@ -957,9 +954,6 @@ impl Fsm for SelectToolFsmState {
|
||||
(_, SelectToolMessage::Overlays { context: mut overlay_context }) => {
|
||||
crate::messages::tool::common_functionality::layer_origin_cross::draw_for_selected_layers(&mut overlay_context, document);
|
||||
|
||||
tool_data.footprint_cage.refresh(document, overlay_context.visibility_settings.transform_cage());
|
||||
tool_data.footprint_cage.overlays(&mut overlay_context);
|
||||
|
||||
let selected_layers_count = document.network_interface.selected_nodes().selected_unlocked_layers(&document.network_interface).count();
|
||||
let paintable_layers_selected = has_paintable_selection(document);
|
||||
tool_data.selected_layers_changed = selected_layers_count != tool_data.selected_layers_count || paintable_layers_selected != tool_data.paintable_layers_selected;
|
||||
@@ -1394,10 +1388,6 @@ impl Fsm for SelectToolFsmState {
|
||||
tool_data.drag_current = input.mouse.position;
|
||||
tool_data.selection_mode = None;
|
||||
|
||||
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_none() && tool_data.footprint_cage.begin_drag(input.mouse.position, responses) {
|
||||
return SelectToolFsmState::DraggingFootprintCage;
|
||||
}
|
||||
|
||||
let mut selected: Vec<_> = document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface).collect();
|
||||
let intersection_list = document.click_list(input, viewport).collect::<Vec<_>>();
|
||||
let intersection = document.find_deepest(&intersection_list);
|
||||
@@ -1630,18 +1620,6 @@ impl Fsm for SelectToolFsmState {
|
||||
remove,
|
||||
}
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerMove { modifier_keys }) => {
|
||||
let (centered, constrain) = (input.keyboard.key(modifier_keys.center), input.keyboard.key(modifier_keys.axis_align));
|
||||
tool_data.footprint_cage.update_drag(input.mouse.position, centered, constrain, responses);
|
||||
|
||||
let messages = [
|
||||
SelectToolMessage::PointerOutsideViewport { modifier_keys: modifier_keys.clone() }.into(),
|
||||
SelectToolMessage::PointerMove { modifier_keys }.into(),
|
||||
];
|
||||
tool_data.auto_panning.setup_by_mouse_position(input, viewport, &messages, responses);
|
||||
|
||||
SelectToolFsmState::DraggingFootprintCage
|
||||
}
|
||||
(SelectToolFsmState::ResizingBounds, SelectToolMessage::PointerMove { modifier_keys }) => {
|
||||
if let Some(bounds) = &mut tool_data.bounding_box_manager {
|
||||
resize_bounds(
|
||||
@@ -1743,10 +1721,6 @@ impl Fsm for SelectToolFsmState {
|
||||
.as_ref()
|
||||
.map_or(MouseCursorIcon::Default, |bounds| bounds.get_cursor(input, true, dragging_bounds, Some(tool_data.skew_edge)));
|
||||
|
||||
if let Some(footprint_cage_cursor) = tool_data.footprint_cage.cursor(input) {
|
||||
cursor = footprint_cage_cursor;
|
||||
}
|
||||
|
||||
// Dragging the pivot overrules the other operations
|
||||
if tool_data.state_from_pivot_gizmo(input.mouse.position).is_some() {
|
||||
cursor = MouseCursorIcon::Move;
|
||||
@@ -1798,14 +1772,6 @@ impl Fsm for SelectToolFsmState {
|
||||
|
||||
self
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// Auto-panning
|
||||
if let Some(shift) = tool_data.auto_panning.shift_viewport(input, viewport, responses) {
|
||||
tool_data.footprint_cage.pan(shift);
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
(SelectToolFsmState::DraggingPivot, SelectToolMessage::PointerOutsideViewport { .. }) => {
|
||||
// Auto-panning
|
||||
let _ = tool_data.auto_panning.shift_viewport(input, viewport, responses);
|
||||
@@ -1951,14 +1917,6 @@ impl Fsm for SelectToolFsmState {
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::DragStop { .. } | SelectToolMessage::Enter) => {
|
||||
let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON;
|
||||
tool_data.footprint_cage.end_drag(drag_too_small, responses);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::Drawing { selection_shape, .. }, SelectToolMessage::DragStop { remove_from_selection }) => {
|
||||
let quad = tool_data.selection_quad();
|
||||
|
||||
@@ -2048,13 +2006,6 @@ impl Fsm for SelectToolFsmState {
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::DraggingFootprintCage, SelectToolMessage::Abort) => {
|
||||
tool_data.footprint_cage.end_drag(true, responses);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
let selection = tool_data.nested_selection_behavior;
|
||||
SelectToolFsmState::Ready { selection }
|
||||
}
|
||||
(SelectToolFsmState::Dragging { .. }, SelectToolMessage::Abort) => {
|
||||
responses.add(DocumentMessage::AbortTransaction);
|
||||
tool_data.axis_align = false;
|
||||
@@ -2224,13 +2175,6 @@ impl Fsm for SelectToolFsmState {
|
||||
]);
|
||||
hint_data.send_layout(responses);
|
||||
}
|
||||
SelectToolFsmState::DraggingFootprintCage => {
|
||||
let hint_data = HintData(vec![
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
|
||||
HintGroup(vec![HintInfo::keys([Key::Alt], "From Center"), HintInfo::keys([Key::Shift], "Preserve Aspect Ratio")]),
|
||||
]);
|
||||
hint_data.send_layout(responses);
|
||||
}
|
||||
SelectToolFsmState::RotatingBounds => {
|
||||
let hint_data = HintData(vec![
|
||||
HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]),
|
||||
|
||||
+176
-217
@@ -1,37 +1,30 @@
|
||||
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, RootNode};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
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 graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::list::{Item, List};
|
||||
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, graphic_types, no_paths, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic};
|
||||
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 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};
|
||||
|
||||
mod observations;
|
||||
#[cfg(test)]
|
||||
mod recompile_tests;
|
||||
mod runtime;
|
||||
pub use observations::ObservationKey;
|
||||
use observations::{path_content_observations, path_contents};
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -59,6 +52,18 @@ struct ViewportCanvasInfo {
|
||||
resolution: DVec2,
|
||||
}
|
||||
|
||||
/// Names an observation so it can be changed or stopped without touching the others.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ObservationKey {
|
||||
/// The node the Data panel inspects.
|
||||
DataPanel,
|
||||
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
|
||||
PathContent(NodeId),
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// The "Fill" node whose geometry a gradient migration measures.
|
||||
FillMeasurement,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ExecutionResult {
|
||||
Pending,
|
||||
@@ -92,8 +97,7 @@ impl std::fmt::Display for EvaluationErrors {
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
pub struct CompilationResponse {
|
||||
result: Result<(), String>,
|
||||
resolved_types: ResolvedDocumentNodeTypesDelta,
|
||||
result: Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)>,
|
||||
node_graph_errors: GraphErrors,
|
||||
node_graph_warnings: GraphErrors,
|
||||
}
|
||||
@@ -108,24 +112,19 @@ pub enum NodeGraphUpdate {
|
||||
},
|
||||
/// The latest result of each observation, sent outside an execution after one of them changed.
|
||||
Observations(HashMap<ObservationKey, InspectResult>),
|
||||
Export {
|
||||
ClipboardSvg {
|
||||
id: u64,
|
||||
result: Box<ExecutionResult>,
|
||||
svg: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[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,
|
||||
/// The document whose network the graph runtime was last sent.
|
||||
node_graph_document: Option<DocumentId>,
|
||||
@@ -147,14 +146,9 @@ 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,
|
||||
@@ -189,8 +183,6 @@ impl NodeGraphExecutor {
|
||||
futures: Default::default(),
|
||||
pending: None,
|
||||
current_execution_id: 0,
|
||||
current_export_id: 0,
|
||||
exports: HashMap::new(),
|
||||
node_graph_hash: 0,
|
||||
node_graph_document: None,
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
@@ -219,21 +211,6 @@ impl NodeGraphExecutor {
|
||||
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}");
|
||||
@@ -252,29 +229,13 @@ impl NodeGraphExecutor {
|
||||
.expect("Failed to send the context overrides");
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
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_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
|
||||
if document_id.is_none() || self.node_graph_document != document_id {
|
||||
return ClipboardMessage::Rendered { id, svg: None }.into();
|
||||
}
|
||||
|
||||
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
|
||||
Message::NoOp
|
||||
}
|
||||
|
||||
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
|
||||
@@ -299,11 +260,9 @@ 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 mut network = document.network_interface.document_network().clone();
|
||||
let 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);
|
||||
|
||||
@@ -313,7 +272,8 @@ impl NodeGraphExecutor {
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
thumbnails,
|
||||
previewed,
|
||||
layers,
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
@@ -377,6 +337,7 @@ impl NodeGraphExecutor {
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: None,
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
@@ -443,6 +404,7 @@ impl NodeGraphExecutor {
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: None,
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
@@ -453,9 +415,10 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
/// Evaluates a node graph for export
|
||||
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());
|
||||
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();
|
||||
|
||||
let export_format = if export_config.file_type == FileType::Svg {
|
||||
graphene_std::application_io::ExportFormat::Svg
|
||||
@@ -489,12 +452,34 @@ impl NodeGraphExecutor {
|
||||
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,
|
||||
};
|
||||
|
||||
self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::File(export_config))
|
||||
// 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: viewport.transform,
|
||||
measure_fill: None,
|
||||
},
|
||||
));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
|
||||
@@ -506,8 +491,8 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
let mut all_dropped_thumbnails = Vec::new();
|
||||
let results = self.receiver.try_iter().collect::<Vec<_>>();
|
||||
for response in results {
|
||||
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter();
|
||||
for response in results.by_ref() {
|
||||
match response {
|
||||
NodeGraphUpdate::ExecutionResponse(execution_response) => {
|
||||
let ExecutionResponse {
|
||||
@@ -531,7 +516,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.measure_fill.is_none() {
|
||||
if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() {
|
||||
self.pending = Some((execution_id, execution_context.clone()));
|
||||
}
|
||||
execution_context
|
||||
@@ -586,7 +571,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
// A pending graph keeps the last frame, and the errors shown with it
|
||||
if !matches!(result, ExecutionResult::Pending) {
|
||||
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
|
||||
let errors = match &result {
|
||||
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
|
||||
let in_document = |path: &&[NodeId]| {
|
||||
@@ -655,13 +640,15 @@ impl NodeGraphExecutor {
|
||||
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_footprint_areas(HashMap::new());
|
||||
if let Some(message) = &message {
|
||||
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 });
|
||||
continue;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -679,8 +666,10 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
document.network_interface.update_vector_modify(path_contents(&observations));
|
||||
|
||||
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);
|
||||
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, _) => {}
|
||||
}
|
||||
responses.add(DeferMessage::TriggerGraphRun {
|
||||
execution_id,
|
||||
@@ -702,43 +691,49 @@ 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;
|
||||
}
|
||||
|
||||
if let Err(e) = &result {
|
||||
// Clear the click targets while the graph is in an un-renderable state
|
||||
let type_delta = match result {
|
||||
Err((incomplete_delta, e)) => {
|
||||
// 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_footprint_areas(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}");
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
Ok(result) => result,
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::UpdateTypes {
|
||||
resolved_types,
|
||||
resolved_types: type_delta,
|
||||
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();
|
||||
@@ -761,7 +756,33 @@ impl NodeGraphExecutor {
|
||||
Self::receive_thumbnails(document, thumbnails, responses);
|
||||
}
|
||||
}
|
||||
NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, 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 }),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -777,6 +798,15 @@ 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
|
||||
@@ -846,10 +876,6 @@ 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,
|
||||
@@ -861,7 +887,8 @@ impl NodeGraphExecutor {
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
thumbnails,
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
|
||||
}))
|
||||
.is_err()
|
||||
@@ -893,6 +920,7 @@ impl NodeGraphExecutor {
|
||||
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)),
|
||||
@@ -1023,7 +1051,6 @@ impl NodeGraphExecutor {
|
||||
outlines,
|
||||
group_layers,
|
||||
text_frames,
|
||||
footprint_areas,
|
||||
clip_targets,
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
@@ -1032,9 +1059,6 @@ impl NodeGraphExecutor {
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
let viewport_to_document = document_to_viewport.inverse();
|
||||
let footprint_areas = footprint_areas.into_iter().map(|(node_id, area)| (node_id, viewport_to_document * area)).collect();
|
||||
|
||||
// Run these update state messages immediately
|
||||
responses.add(DocumentMessage::UpdateUpstreamTransforms {
|
||||
upstream_footprints,
|
||||
@@ -1045,7 +1069,6 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClickTargets { click_targets, group_layers });
|
||||
responses.add(DocumentMessage::UpdateOutlines { outlines });
|
||||
responses.add(DocumentMessage::UpdateTextFrames { text_frames });
|
||||
responses.add(DocumentMessage::UpdateFootprintAreas { footprint_areas });
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
@@ -1057,51 +1080,6 @@ 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,
|
||||
@@ -1201,61 +1179,6 @@ 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)> {
|
||||
@@ -1277,6 +1200,45 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
||||
None
|
||||
}
|
||||
|
||||
/// 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));
|
||||
|
||||
path_nodes.into_iter().filter_map(|node_path| {
|
||||
let key = ObservationKey::PathContent(*node_path.last()?);
|
||||
let observation = Observation {
|
||||
node_path,
|
||||
connector: ObservedConnector::Input(path::ContentInput::INDEX),
|
||||
overrides: ContextOverrides::default(),
|
||||
};
|
||||
Some((key, observation))
|
||||
})
|
||||
}
|
||||
|
||||
/// The incoming geometry of each 'Path' node, read from its observed content.
|
||||
fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
|
||||
observations
|
||||
.iter()
|
||||
.filter_map(|(key, result)| {
|
||||
let ObservationKey::PathContent(path_node) = *key else { return None };
|
||||
let value = result.data.as_ref()?;
|
||||
|
||||
let geometry = match value.downcast_ref::<List<Vector>>() {
|
||||
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
|
||||
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
|
||||
};
|
||||
Some((path_node, geometry))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Re-export for usage by tests in other modules
|
||||
#[cfg(test)]
|
||||
pub use test::Instrumented;
|
||||
@@ -1311,17 +1273,14 @@ 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,
|
||||
thumbnails,
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
use super::{InspectResult, Observation, ObservedConnector};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::vector::{Vector, VectorGeometry, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ContextOverrides, NodeParameter};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Names an observation so it can be changed or stopped without touching the others.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ObservationKey {
|
||||
/// The node the Data panel inspects.
|
||||
DataPanel,
|
||||
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
|
||||
PathContent(NodeId),
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// The "Fill" node whose geometry a gradient migration measures.
|
||||
FillMeasurement,
|
||||
}
|
||||
|
||||
pub(super) 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));
|
||||
|
||||
path_nodes.into_iter().filter_map(|node_path| {
|
||||
let key = ObservationKey::PathContent(*node_path.last()?);
|
||||
let observation = Observation {
|
||||
node_path,
|
||||
connector: ObservedConnector::Input(path::ContentInput::INDEX),
|
||||
overrides: ContextOverrides::default(),
|
||||
};
|
||||
Some((key, observation))
|
||||
})
|
||||
}
|
||||
|
||||
/// The incoming geometry of each 'Path' node, read from its observed content.
|
||||
pub(super) fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
|
||||
observations
|
||||
.iter()
|
||||
.filter_map(|(key, result)| {
|
||||
let ObservationKey::PathContent(path_node) = *key else { return None };
|
||||
let value = result.data.as_ref()?;
|
||||
|
||||
let geometry = match value.downcast_ref::<List<Vector>>() {
|
||||
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
|
||||
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
|
||||
};
|
||||
Some((path_node, geometry))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -18,8 +18,8 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
|
||||
editor.dispatch(Message::Wake);
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
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
@@ -3,7 +3,7 @@ use crate::messages::frontend::FrontendMessage;
|
||||
use atlas::ThumbnailAtlasLayout;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graphene_std::application_io::{ApplicationIo, Texture};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::gradient::Gradient;
|
||||
@@ -12,11 +12,12 @@ use graphene_std::ops::ConvertAsync;
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::renderer::Render;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::transform::{Footprint, RenderQuality};
|
||||
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::sync::Arc;
|
||||
|
||||
@@ -82,9 +83,12 @@ 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, 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();
|
||||
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();
|
||||
|
||||
// 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));
|
||||
@@ -272,11 +276,11 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/// The area the content covers once rendered, counting the effects drawn through maps and images.
|
||||
fn content_bounds(&self) -> RenderBoundingBox {
|
||||
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out.
|
||||
fn content_bounds(&self, maps_resolved: bool) -> 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, true),
|
||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
|
||||
// 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),
|
||||
@@ -285,7 +289,7 @@ impl ThumbnailContent {
|
||||
|
||||
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
||||
fn bounds(&self) -> [DVec2; 2] {
|
||||
let bounds = match self.content_bounds() {
|
||||
let bounds = match self.content_bounds(true) {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
||||
_ => [DVec2::ZERO, DVec2::ONE],
|
||||
};
|
||||
@@ -293,6 +297,45 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
|
||||
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
|
||||
let contents: Vec<ThumbnailContent> = layers
|
||||
.iter()
|
||||
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
|
||||
.collect();
|
||||
|
||||
let bounds = contents
|
||||
.iter()
|
||||
.filter_map(|content| match content.content_bounds(false) {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
|
||||
_ => None,
|
||||
})
|
||||
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
|
||||
|
||||
let render_params = RenderParams {
|
||||
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut render = SvgRender::new();
|
||||
for content in &contents {
|
||||
content.graphic().render_svg(&mut render, &render_params);
|
||||
}
|
||||
if render.svg.is_empty() {
|
||||
return None;
|
||||
}
|
||||
render.format_svg(bounds[0], bounds[1]);
|
||||
|
||||
Some(render.svg.to_svg_string())
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
|
||||
@@ -558,9 +558,10 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||
> .text-label:only-child {
|
||||
// A label with no expose button before it lines up with the parameter names that follow one
|
||||
> .text-label:first-child {
|
||||
margin-left: calc(20px + 8px + 8px);
|
||||
--wire-indent: 20px;
|
||||
}
|
||||
|
||||
> .separator.horizontal.unrelated {
|
||||
|
||||
@@ -570,6 +570,8 @@ tagged_value! {
|
||||
StrokeAlign(vector::style::StrokeAlign),
|
||||
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
||||
GradientForm(vector::style::GradientForm),
|
||||
GradientModel(vector::style::GradientModel),
|
||||
GradientDirection(vector::style::GradientDirection),
|
||||
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
|
||||
GradientSpread(vector::style::GradientSpread),
|
||||
GradientSpace(vector::style::GradientSpace),
|
||||
|
||||
@@ -128,7 +128,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
|
||||
impl CompiledDocument {
|
||||
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(self.proto_network).map_err(|errors| {
|
||||
let (output, _) = executor.update(self.proto_network).map_err(|(_, errors)| {
|
||||
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
||||
messages.join("\n")
|
||||
})?;
|
||||
|
||||
@@ -133,13 +133,13 @@ impl Viewer {
|
||||
Err(error) => return log::error!("Compile failed: {error}"),
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
match executor.insert(proto) {
|
||||
Ok(output) => {
|
||||
match executor.update(proto) {
|
||||
Ok((output, _)) => {
|
||||
self.graph_runtime.update_sources(executor.sources());
|
||||
log::info!("Document compiled");
|
||||
self.executor = Some((executor, output));
|
||||
}
|
||||
Err(errors) => {
|
||||
Err((_, errors)) => {
|
||||
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
||||
log::error!("Executor creation failed: {}", messages.join("\n"));
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(proto_network.clone()).unwrap();
|
||||
let (output, _) = executor.update(proto_network.clone()).unwrap();
|
||||
(executor, output, proto_network)
|
||||
}
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ impl Session {
|
||||
let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
|
||||
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
|
||||
self.output = self.executor.insert(proto_network).expect("Failed to update the executor");
|
||||
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
|
||||
|
||||
let render_config = RenderConfig {
|
||||
viewport: Footprint {
|
||||
|
||||
@@ -16,7 +16,7 @@ fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
c.bench_function(name, |b| {
|
||||
b.iter_batched(
|
||||
|| (executor.clone(), proto_network.clone()),
|
||||
|(mut executor, network)| executor.insert(std::hint::black_box(network)),
|
||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
@@ -36,7 +36,7 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
||||
let proto_network = compile(network);
|
||||
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(proto_network).unwrap();
|
||||
let (output, _) = executor.update(proto_network).unwrap();
|
||||
let footprint = Footprint::default();
|
||||
|
||||
c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint)));
|
||||
|
||||
@@ -13,7 +13,7 @@ fn update_executor(c: &mut Criterion) {
|
||||
let (_, _, proto_network) = setup_network(name);
|
||||
(DynamicExecutor::default(), proto_network)
|
||||
},
|
||||
|(mut executor, network)| executor.insert(std::hint::black_box(network)),
|
||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -15,7 +15,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
|
||||
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
|
||||
let (mut executor, network) = setup;
|
||||
let _ = black_box(executor.insert(black_box(network)));
|
||||
let _ = black_box(executor.update(black_box(network)));
|
||||
|
||||
// Return the executor so its teardown happens outside the measured section
|
||||
executor
|
||||
|
||||
@@ -19,7 +19,8 @@ pub struct DynamicExecutor {
|
||||
typing_context: TypingContext,
|
||||
/// The outputs of the networks, kept alive by the executor as long as there are handles to them.
|
||||
outputs: Vec<Weak<NodeId>>,
|
||||
type_deltas: TypeDeltaCollector,
|
||||
// Kept for one more update, so a node that comes back is reused
|
||||
orphaned_nodes: HashSet<NodeId>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -37,7 +38,7 @@ impl Default for DynamicExecutor {
|
||||
tree: Default::default(),
|
||||
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
||||
outputs: Vec::new(),
|
||||
type_deltas: Default::default(),
|
||||
orphaned_nodes: HashSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,37 +64,19 @@ impl DynamicExecutor {
|
||||
|
||||
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
|
||||
#[cfg_attr(debug_assertions, inline(never))]
|
||||
pub fn insert(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
|
||||
let output = self.insert_nodes(proto_network)?;
|
||||
self.free_orphaned_nodes();
|
||||
Ok(output)
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
let (output, add) = self.insert_nodes(proto_network)?;
|
||||
let remove = self.free_orphaned_nodes();
|
||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
|
||||
}
|
||||
|
||||
pub fn replace(&mut self, output: OutputHandle, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
|
||||
let inserted = self.insert_nodes(proto_network)?;
|
||||
let Some(replaced) = Arc::into_inner(output.0) else { return Ok(inserted) };
|
||||
let live: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
|
||||
let mut pending = vec![replaced];
|
||||
while let Some(node) = pending.pop() {
|
||||
let Some((container, _, inputs)) = self.tree.nodes.get(&node) else { continue };
|
||||
if Arc::strong_count(container) > 1 || live.contains(&node) {
|
||||
continue;
|
||||
}
|
||||
pending.extend(inputs.iter());
|
||||
if let Some(path) = self.tree.free_node(node) {
|
||||
self.type_deltas.remove(path);
|
||||
}
|
||||
self.typing_context.remove_inference(node);
|
||||
}
|
||||
Ok(inserted)
|
||||
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
let (output, add) = self.insert_nodes(proto_network)?;
|
||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }))
|
||||
}
|
||||
|
||||
pub fn take_type_deltas(&mut self) -> Option<ResolvedDocumentNodeTypesDelta> {
|
||||
self.type_deltas.take()
|
||||
}
|
||||
|
||||
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
|
||||
self.typing_context.update(&proto_network).inspect_err(|_| {
|
||||
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
self.typing_context.update(&proto_network).map_err(|e| {
|
||||
// If there is an error then get types that have been resolved before the error
|
||||
let add = proto_network
|
||||
.nodes
|
||||
@@ -111,13 +94,11 @@ impl DynamicExecutor {
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
self.type_deltas.add(add);
|
||||
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
|
||||
})?;
|
||||
|
||||
let output = proto_network.output;
|
||||
|
||||
let add = self.tree.update(proto_network, &self.typing_context)?;
|
||||
|
||||
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||
self.outputs.retain(|output| output.strong_count() > 0);
|
||||
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
|
||||
let output = held.unwrap_or_else(|| {
|
||||
@@ -126,11 +107,11 @@ impl DynamicExecutor {
|
||||
output
|
||||
});
|
||||
|
||||
self.type_deltas.add(self.tree.node_types(add.into_iter()));
|
||||
Ok(OutputHandle(output))
|
||||
let add = self.document_node_types(add.into_iter()).collect();
|
||||
Ok((OutputHandle(output), add))
|
||||
}
|
||||
|
||||
fn free_orphaned_nodes(&mut self) {
|
||||
fn free_orphaned_nodes(&mut self) -> Vec<Path> {
|
||||
let mut kept = HashSet::new();
|
||||
let mut pending: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
|
||||
while let Some(node) = pending.pop() {
|
||||
@@ -140,14 +121,19 @@ impl DynamicExecutor {
|
||||
pending.extend(inputs.iter());
|
||||
}
|
||||
}
|
||||
let orphaned: Vec<NodeId> = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
|
||||
for node_id in orphaned {
|
||||
let path = self.tree.free_node(node_id);
|
||||
self.typing_context.remove_inference(node_id);
|
||||
if let Some(path) = path {
|
||||
self.type_deltas.remove(path);
|
||||
let orphaned = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
|
||||
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
|
||||
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
|
||||
for node_id in old_to_remove {
|
||||
if self.orphaned_nodes.contains(&node_id) {
|
||||
let path = self.tree.free_node(node_id);
|
||||
self.typing_context.remove_inference(node_id);
|
||||
if let Some(path) = path {
|
||||
remove.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
remove
|
||||
}
|
||||
|
||||
pub fn execute<I: 'static + WasmNotSend>(&self, output: &OutputHandle, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> {
|
||||
@@ -167,7 +153,7 @@ impl DynamicExecutor {
|
||||
}
|
||||
|
||||
pub fn document_node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
|
||||
self.tree.node_types(nodes)
|
||||
nodes.flat_map(|id| self.tree.source_map().get(&id).map(|(_, b)| (id, b.clone())))
|
||||
// TODO: https://github.com/GraphiteEditor/Graphite/issues/1767
|
||||
// TODO: Non exposed inputs are not added to the inputs_source_map, so they are not included in the resolved_document_node_types. The type is still available in the typing_context. This only affects the UI-only "Import" node.
|
||||
}
|
||||
@@ -573,39 +559,6 @@ impl BorrowTree {
|
||||
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
|
||||
&self.source_map
|
||||
}
|
||||
|
||||
pub fn node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
|
||||
nodes.flat_map(|id| self.source_map().get(&id).map(|(_, b)| (id, b.clone())))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct TypeDeltaCollector {
|
||||
changes: HashMap<Path, Option<NodeTypes>>,
|
||||
}
|
||||
|
||||
impl TypeDeltaCollector {
|
||||
fn add(&mut self, types: impl IntoIterator<Item = (Path, NodeTypes)>) {
|
||||
self.changes.extend(types.into_iter().map(|(path, types)| (path, Some(types))));
|
||||
}
|
||||
|
||||
fn remove(&mut self, path: Path) {
|
||||
self.changes.insert(path, None);
|
||||
}
|
||||
|
||||
fn take(&mut self) -> Option<ResolvedDocumentNodeTypesDelta> {
|
||||
if self.changes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut delta = ResolvedDocumentNodeTypesDelta::default();
|
||||
for (path, types) in self.changes.drain() {
|
||||
match types {
|
||||
Some(types) => delta.add.push((path, types)),
|
||||
None => delta.remove.push(path),
|
||||
}
|
||||
}
|
||||
Some(delta)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -876,7 +876,7 @@ fn error_traced_through(indices: &[usize]) -> NodeError {
|
||||
#[test]
|
||||
fn a_trace_leads_to_the_node_that_raised_the_error() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||
|
||||
assert!(executor.trace_error(output.node(), &error_traced_through(&[])).is_empty());
|
||||
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0])), [NodeId(0)]);
|
||||
@@ -899,7 +899,7 @@ fn a_trace_steps_over_the_index_of_a_promotion_adapter() {
|
||||
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(network).unwrap();
|
||||
let (output, _) = executor.update(network).unwrap();
|
||||
|
||||
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)]);
|
||||
}
|
||||
@@ -936,7 +936,7 @@ fn chained_fallbacks_both_reach_the_root() {
|
||||
.concat(),
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(network).unwrap();
|
||||
let (output, _) = executor.update(network).unwrap();
|
||||
|
||||
let context: Context = None;
|
||||
let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else {
|
||||
@@ -966,7 +966,7 @@ fn an_error_after_a_fallback_keeps_both() {
|
||||
.concat(),
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(network).unwrap();
|
||||
let (output, _) = executor.update(network).unwrap();
|
||||
|
||||
let context: Context = None;
|
||||
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
|
||||
@@ -995,7 +995,7 @@ fn a_node_error_names_the_node_that_raised_it() {
|
||||
.concat(),
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(network).expect("The Throw Error nodes should resolve");
|
||||
let (output, _) = executor.update(network).expect("The Throw Error nodes should resolve");
|
||||
|
||||
let context: Context = None;
|
||||
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
|
||||
@@ -1050,7 +1050,7 @@ fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], k
|
||||
.concat(),
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(network).expect("The error handling nodes should resolve");
|
||||
let (output, _) = executor.update(network).expect("The error handling nodes should resolve");
|
||||
(executor, output)
|
||||
}
|
||||
|
||||
@@ -1190,6 +1190,16 @@ fn source_network(node: u64) -> ProtoNetwork {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_without_freeing_keeps_the_nodes_the_network_leaves_out() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
executor.update(source_network(0)).unwrap();
|
||||
|
||||
executor.update_without_freeing(source_network(1)).unwrap();
|
||||
executor.update_without_freeing(source_network(1)).unwrap();
|
||||
assert!(executor.tree().get(NodeId(0)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn networks_are_executed_side_by_side_by_their_handles() {
|
||||
let network = |node: u64| ProtoNetwork {
|
||||
@@ -1198,8 +1208,8 @@ fn networks_are_executed_side_by_side_by_their_handles() {
|
||||
nodes: vec![value_node(node, TaggedValue::Number(node as f64))],
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let first = executor.insert(network(0)).unwrap();
|
||||
let second = executor.insert(network(1)).unwrap();
|
||||
let (first, _) = executor.update(network(0)).unwrap();
|
||||
let (second, _) = executor.update(network(1)).unwrap();
|
||||
|
||||
let context: Context = None;
|
||||
assert_eq!(executor.execute(&first, context.clone()).unwrap(), Poll::Final(TaggedValue::Number(0.)));
|
||||
@@ -1209,9 +1219,9 @@ fn networks_are_executed_side_by_side_by_their_handles() {
|
||||
#[test]
|
||||
fn an_output_that_is_already_held_shares_its_handle() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let first = executor.insert(source_network(0)).unwrap();
|
||||
let second = executor.insert(source_network(0)).unwrap();
|
||||
let other = executor.insert(source_network(1)).unwrap();
|
||||
let (first, _) = executor.update(source_network(0)).unwrap();
|
||||
let (second, _) = executor.update(source_network(0)).unwrap();
|
||||
let (other, _) = executor.update(source_network(1)).unwrap();
|
||||
|
||||
assert!(Arc::ptr_eq(&first.0, &second.0));
|
||||
assert!(!Arc::ptr_eq(&first.0, &other.0));
|
||||
@@ -1220,123 +1230,28 @@ fn an_output_that_is_already_held_shares_its_handle() {
|
||||
#[test]
|
||||
fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||
let kept = |executor: &DynamicExecutor| [0, 1].map(|node| executor.tree().get(NodeId(node)).is_some());
|
||||
|
||||
for _ in 0..3 {
|
||||
executor.insert(source_network(2)).unwrap();
|
||||
executor.update(source_network(2)).unwrap();
|
||||
}
|
||||
assert_eq!(kept(&executor), [true; 2]);
|
||||
|
||||
drop(output);
|
||||
executor.insert(source_network(2)).unwrap();
|
||||
executor.update(source_network(2)).unwrap();
|
||||
assert_eq!(kept(&executor), [true; 2], "orphaned for one more update");
|
||||
executor.update(source_network(2)).unwrap();
|
||||
assert_eq!(kept(&executor), [false; 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_is_listed_for_as_long_as_its_node_lives() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let output = executor.insert(source_network(0)).unwrap();
|
||||
let listed = |executor: &DynamicExecutor| executor.sources().any(|source| *source == SourceId(0));
|
||||
executor.update(source_network(0)).unwrap();
|
||||
|
||||
executor.insert(source_network(1)).unwrap();
|
||||
assert!(listed(&executor));
|
||||
|
||||
drop(output);
|
||||
executor.insert(source_network(1)).unwrap();
|
||||
assert!(!listed(&executor));
|
||||
}
|
||||
|
||||
fn changed_paths(executor: &mut DynamicExecutor) -> Option<[Vec<u64>; 2]> {
|
||||
let changes = executor.take_type_deltas()?;
|
||||
let added = changes.add.iter().map(|(path, _)| path[0].0);
|
||||
let removed = changes.remove.iter().map(|path| path[0].0);
|
||||
let mut paths = [added.collect::<Vec<_>>(), removed.collect()];
|
||||
paths.iter_mut().for_each(|paths| paths.sort_unstable());
|
||||
Some(paths)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn take_type_deltas_gives_the_paths_inserted_and_freed_since_the_last_take() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let held = [executor.insert(source_network(0)).unwrap(), executor.insert(source_network(1)).unwrap()];
|
||||
assert_eq!(changed_paths(&mut executor), Some([vec![0, 1], vec![]]));
|
||||
assert_eq!(changed_paths(&mut executor), None);
|
||||
|
||||
drop(held);
|
||||
executor.insert(source_network(2)).unwrap();
|
||||
assert_eq!(changed_paths(&mut executor), Some([vec![2], vec![0, 1]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_freed_and_inserted_again_between_two_takes_is_given_with_its_types() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
executor.insert(source_network(0)).unwrap();
|
||||
executor.take_type_deltas();
|
||||
|
||||
executor.insert(source_network(1)).unwrap();
|
||||
executor.insert(source_network(0)).unwrap();
|
||||
let path: Path = [NodeId(0)].into();
|
||||
let types = executor.tree().source_map()[&path].1.clone();
|
||||
assert_eq!(executor.take_type_deltas().unwrap().add, [(path, types)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_typed_before_a_type_error_is_given() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
executor.insert(bounding_box_network(TaggedValue::Number(1.))).unwrap_err();
|
||||
assert_eq!(changed_paths(&mut executor), Some([vec![0], vec![]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_frees_what_only_the_replaced_output_reached() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let replaced = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||
|
||||
executor.replace(replaced, source_network(2)).unwrap();
|
||||
for node in [NodeId(0), NodeId(1)] {
|
||||
assert!(executor.tree().get(node).is_none());
|
||||
assert!(executor.typing_context.type_of(node).is_none());
|
||||
}
|
||||
let delta = executor.take_type_deltas().unwrap();
|
||||
let mut removed: Vec<_> = delta.remove.iter().map(|path| path.to_vec()).collect();
|
||||
removed.sort();
|
||||
assert_eq!(removed, [vec![NodeId(0)], vec![NodeId(1)]]);
|
||||
assert_eq!(executor.tree().source_map().keys().map(|path| path.to_vec()).collect::<Vec<_>>(), [vec![NodeId(2)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_keeps_what_the_new_network_or_another_output_still_reaches() {
|
||||
let content = TaggedValue::TypeDefault(item!(Vector));
|
||||
let value_network = |(output, node)| ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output,
|
||||
nodes: vec![(output, node)],
|
||||
};
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let _document = executor.insert(value_network(value_node(0, content.clone()))).unwrap();
|
||||
let replaced = executor.insert(offset_points_network(content)).unwrap();
|
||||
|
||||
executor.replace(replaced, value_network(value_node(1, TaggedValue::Number(10.)))).unwrap();
|
||||
assert_eq!([0, 1, 2, 3].map(|node| executor.tree().get(NodeId(node)).is_some()), [true, true, false, false]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_frees_nothing_while_the_replaced_handle_is_held_elsewhere() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let held = executor.insert(source_network(0)).unwrap();
|
||||
|
||||
executor.replace(held.clone(), source_network(1)).unwrap();
|
||||
assert!(executor.tree().get(NodeId(0)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_replacing_keeps_the_node_count_and_the_source_map_size_constant() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let mut output = executor.insert(source_network(0)).unwrap();
|
||||
|
||||
for node in 1..=4 {
|
||||
output = executor.replace(output, source_network(node)).unwrap();
|
||||
assert_eq!([executor.tree().nodes.len(), executor.tree().source_map().len()], [1, 1]);
|
||||
for _ in 0..3 {
|
||||
executor.update(source_network(1)).unwrap();
|
||||
assert_eq!(executor.sources().any(|source| *source == SourceId(0)), executor.tree().get(NodeId(0)).is_some());
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,6 @@ mod tests {
|
||||
let compiler = Compiler {};
|
||||
let protograph = compiler.compile_single(network).expect("Graph should be generated").network;
|
||||
|
||||
let _exec = DynamicExecutor::default().insert(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
let _exec = DynamicExecutor::default().update(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,9 @@ use graphene_std::vector::misc::{
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||
WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::style::{
|
||||
DashPattern, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
@@ -68,7 +70,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientForm>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpread>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpace>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientHueDirection>]),
|
||||
@@ -155,24 +156,14 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
)
|
||||
};
|
||||
}
|
||||
// Keeps an adapter row under the identifier the preprocessor names it by and repeats it under the adapter node's own identifier,
|
||||
// which the new compiler selects by signature
|
||||
macro_rules! also_under_own_identifier {
|
||||
($module:ident, $row:expr) => {{
|
||||
let row: (ProtoNodeIdentifier, NodeConstructor, NodeIOTypes) = $row;
|
||||
let own = (graphene_core::ops::$module::IDENTIFIER, row.1, row.2.clone());
|
||||
[row, own]
|
||||
}};
|
||||
}
|
||||
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
|
||||
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
|
||||
macro_rules! input_adapter_row {
|
||||
(from_element: $from:ty, element: $element:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||
also_under_own_identifier!(into_item, input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||
also_under_own_identifier!(into_list, input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||
]
|
||||
.concat();
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
||||
input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element),
|
||||
];
|
||||
entries
|
||||
}};
|
||||
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
|
||||
@@ -264,7 +255,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
$(
|
||||
entries.extend(input_adapter_node!(element: $element));
|
||||
entries.extend(also_under_own_identifier!(item_to_list, item_to_list_node!(element: $element)));
|
||||
entries.push(item_to_list_node!(element: $element));
|
||||
)*
|
||||
entries
|
||||
}};
|
||||
@@ -281,6 +272,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientDirection,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -369,10 +362,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
||||
macro_rules! list_dyn_rows {
|
||||
($($element:ty),* $(,)?) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||
$(also_under_own_identifier!(into, input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn)),)*
|
||||
]
|
||||
.concat();
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
$(input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn),)*
|
||||
];
|
||||
entries
|
||||
}};
|
||||
}
|
||||
@@ -392,7 +384,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
DVec2,
|
||||
DAffine2,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -405,8 +396,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
($($element:ty),* $(,)?) => {{
|
||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||
$(
|
||||
entries.extend(also_under_own_identifier!(bundle, bundle_node!(element: $element)));
|
||||
entries.extend(also_under_own_identifier!(unbundle, unbundle_node!(element: $element)));
|
||||
entries.push(bundle_node!(element: $element));
|
||||
entries.push(unbundle_node!(element: $element));
|
||||
)*
|
||||
entries
|
||||
}};
|
||||
@@ -466,11 +457,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
|
||||
macro_rules! embed_adapter_row {
|
||||
(from_element: $from:ty, element: $element:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||
also_under_own_identifier!(embed_item, input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||
also_under_own_identifier!(embed_list, input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||
]
|
||||
.concat();
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
||||
input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element),
|
||||
];
|
||||
entries
|
||||
}};
|
||||
}
|
||||
@@ -487,11 +477,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
|
||||
macro_rules! convert_adapter_node {
|
||||
(from_element: $from:ty, element: $element:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||
also_under_own_identifier!(convert_item, input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||
also_under_own_identifier!(convert_list, input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||
]
|
||||
.concat();
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
||||
input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element),
|
||||
];
|
||||
entries
|
||||
}};
|
||||
}
|
||||
@@ -513,19 +502,13 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
||||
macro_rules! attribute_value_node {
|
||||
(Item<$element:ty>) => {
|
||||
also_under_own_identifier!(
|
||||
item_to_attribute_value,
|
||||
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||
)
|
||||
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||
};
|
||||
(List<$element:ty>) => {
|
||||
also_under_own_identifier!(
|
||||
list_to_attribute_value,
|
||||
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||
)
|
||||
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||
};
|
||||
}
|
||||
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
attribute_value_node!(Item<f64>),
|
||||
attribute_value_node!(Item<i64>),
|
||||
attribute_value_node!(Item<bool>),
|
||||
@@ -535,6 +518,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(Item<Color>),
|
||||
attribute_value_node!(Item<BlendMode>),
|
||||
attribute_value_node!(Item<GradientForm>),
|
||||
attribute_value_node!(Item<GradientModel>),
|
||||
attribute_value_node!(Item<GradientDirection>),
|
||||
attribute_value_node!(Item<GradientSpread>),
|
||||
attribute_value_node!(Item<GradientSpace>),
|
||||
attribute_value_node!(Item<GradientHueDirection>),
|
||||
@@ -550,8 +535,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(List<Raster<GPU>>),
|
||||
attribute_value_node!(List<Graphic>),
|
||||
attribute_value_node!(List<Artboard>),
|
||||
]
|
||||
.concat();
|
||||
];
|
||||
node_types.extend(attribute_value_rows);
|
||||
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
|
||||
macro_rules! transform_list_node {
|
||||
|
||||
@@ -32,10 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_FOOTPRINT_AREAS, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS,
|
||||
ATTR_EDITOR_TEXT_FRAME, ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE,
|
||||
ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START,
|
||||
ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
|
||||
ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT,
|
||||
ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use num_traits;
|
||||
|
||||
@@ -40,9 +40,6 @@ pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
|
||||
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
|
||||
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
|
||||
/// `List<NodeIdPath>` of the nodes with a footprint input this item passed through.
|
||||
/// Each row's transform maps the unit square onto that node's area in this item's local space.
|
||||
pub const ATTR_EDITOR_FOOTPRINT_AREAS: &str = "editor:footprint_areas";
|
||||
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
|
||||
pub const ATTR_START: &str = "start";
|
||||
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
|
||||
@@ -62,8 +59,16 @@ pub const ATTR_CLIP: &str = "clip";
|
||||
// TODO: Consider adding "gradient_spread_left" and "gradient_spread_right" override attributes to allow setting different gradient spreads on each side of a gradient
|
||||
/// Gradient's `GradientSpread` (`Pad`, `Reflect`, `Repeat`, or `Clear`).
|
||||
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
||||
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||
/// Gradient's `f64` curvature for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
|
||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, it's 0.
|
||||
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
|
||||
/// Gradient's `f64` curvature for the contour through its end, like `gradient_start_curvature` with the ends swapped.
|
||||
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
|
||||
/// Gradient's `GradientModel` (`Standard` or `Apollonian`), how the contours between its curved ends are laid out: as SVG 2's cone
|
||||
/// between the end circles, or as the family of circles the ends span. Absent, it's `Standard`.
|
||||
pub const ATTR_GRADIENT_MODEL: &str = "gradient_model";
|
||||
/// Gradient's `GradientDirection` (`Along` or `Across`), whether its colors run from one end contour to the other or around each contour. Absent, it's `Along`.
|
||||
pub const ATTR_GRADIENT_DIRECTION: &str = "gradient_direction";
|
||||
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||
@@ -1717,7 +1722,7 @@ impl<T: CacheHash> CacheHash for List<T> {
|
||||
self.element.as_slice().cache_hash(state);
|
||||
|
||||
// Hash every attribute (key + values) rather than just the well-known ones, so changes to user-defined keys
|
||||
// (e.g., gradient_form, gradient_spread) invalidate downstream graph caches as expected
|
||||
// (e.g., gradient_spread) invalidate downstream graph caches as expected
|
||||
self.attributes.cache_hash_entries(state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,18 +29,6 @@ pub struct NodeFlags {
|
||||
pub forwards_input: bool,
|
||||
pub inject_scope: bool,
|
||||
pub asynchronous: bool,
|
||||
/// Whether type resolution may insert this node on an edge, from `#[node_macro::node(adapter(...))]`.
|
||||
pub adapter: Option<AdapterKind>,
|
||||
pub transient: bool,
|
||||
}
|
||||
|
||||
/// How an adapter node changes the wire it is inserted on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AdapterKind {
|
||||
/// Converts the wire's element into another element type.
|
||||
Conversion,
|
||||
/// Changes the wire's rank, like raising an `Item` onto a `List`.
|
||||
Rank,
|
||||
}
|
||||
|
||||
// Translation struct between macro and definition
|
||||
|
||||
@@ -113,36 +113,7 @@ impl RuntimeInner {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Slots<T>(Arc<Mutex<SlotTable<T>>>);
|
||||
|
||||
struct SlotTable<T> {
|
||||
slots: HashMap<u64, Slot<T>>,
|
||||
/// The number of started evaluations, which orders them.
|
||||
started: u64,
|
||||
/// The value of the latest started evaluation that has landed, with its order.
|
||||
latest: Option<(u64, T)>,
|
||||
}
|
||||
|
||||
impl<T: Clone> SlotTable<T> {
|
||||
fn start(&mut self) -> u64 {
|
||||
self.started += 1;
|
||||
self.started
|
||||
}
|
||||
|
||||
fn land(&mut self, key: u64, order: u64, state: Poll<T>) {
|
||||
let superseded = self.latest.as_ref().is_some_and(|(latest_order, _)| *latest_order > order);
|
||||
if !superseded && let Some(value) = state.clone().value() {
|
||||
self.latest = Some((order, value));
|
||||
}
|
||||
self.slots.insert(key, Slot::Ready(state));
|
||||
}
|
||||
|
||||
/// The value a pending evaluation returns, preferring the latest landed value if `keep_previous` is set.
|
||||
fn stand_in(&self, placeholder: Option<T>, keep_previous: bool) -> Poll<T> {
|
||||
let previous = if keep_previous { self.latest.as_ref().map(|(_, value)| value.clone()) } else { None };
|
||||
previous.or(placeholder).map_or(Poll::Pending, Poll::Partial)
|
||||
}
|
||||
}
|
||||
pub struct Slots<T>(Arc<Mutex<HashMap<u64, Slot<T>>>>);
|
||||
|
||||
enum Slot<T> {
|
||||
Ready(Poll<T>),
|
||||
@@ -159,11 +130,7 @@ impl<T> Drop for Slot<T> {
|
||||
|
||||
impl<T> Default for Slots<T> {
|
||||
fn default() -> Self {
|
||||
Self(Arc::new(Mutex::new(SlotTable {
|
||||
slots: HashMap::new(),
|
||||
started: 0,
|
||||
latest: None,
|
||||
})))
|
||||
Self(Arc::default())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,46 +147,42 @@ impl<T> std::fmt::Debug for Slots<T> {
|
||||
}
|
||||
|
||||
impl<T: Clone + WasmNotSend + 'static> Slots<T> {
|
||||
/// The landed state for `key`, or else starts its evaluation and returns its stand-in.
|
||||
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, keep_previous: bool, future: impl FnOnce() -> F) -> Poll<T>
|
||||
pub fn resolve<F>(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option<T>, future: impl FnOnce() -> F) -> Poll<T>
|
||||
where
|
||||
F: Future<Output = Poll<T>> + WasmNotSend + 'static,
|
||||
{
|
||||
let order = {
|
||||
let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match table.slots.get(&key) {
|
||||
Some(Slot::Ready(landed)) => return landed.clone(),
|
||||
Some(Slot::Pending(_)) => return table.stand_in(placeholder, keep_previous),
|
||||
None => table.start(),
|
||||
}
|
||||
};
|
||||
match self.0.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
|
||||
Some(Slot::Ready(landed)) => return landed.clone(),
|
||||
Some(Slot::Pending(_)) => return placeholder.map_or(Poll::Pending, Poll::Partial),
|
||||
None => {}
|
||||
}
|
||||
|
||||
// Fast path for futures that are ready immediately
|
||||
// TODO(Timon): check if this would ever cause a problem; running a future on the graph executor thread might also be a bit wierd
|
||||
let mut future = Box::pin(future());
|
||||
if let std::task::Poll::Ready(state) = future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state.clone());
|
||||
self.0.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state.clone()));
|
||||
return state;
|
||||
}
|
||||
|
||||
let (handle, registration) = AbortHandle::new_pair();
|
||||
let table = Arc::downgrade(&self.0);
|
||||
let slots = Arc::downgrade(&self.0);
|
||||
runtime.spawn(
|
||||
source,
|
||||
Box::pin(async move {
|
||||
if let Ok(state) = Abortable::new(future, registration).await
|
||||
&& let Some(table) = table.upgrade()
|
||||
&& let Some(slots) = slots.upgrade()
|
||||
{
|
||||
table.lock().unwrap_or_else(PoisonError::into_inner).land(key, order, state);
|
||||
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state));
|
||||
}
|
||||
}),
|
||||
);
|
||||
let mut table = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match table.slots.get(&key) {
|
||||
let mut slots = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match slots.get(&key) {
|
||||
Some(Slot::Ready(landed)) => landed.clone(),
|
||||
_ => {
|
||||
table.slots.insert(key, Slot::Pending(handle));
|
||||
table.stand_in(placeholder, keep_previous)
|
||||
slots.insert(key, Slot::Pending(handle));
|
||||
placeholder.map_or(Poll::Pending, Poll::Partial)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -252,13 +215,6 @@ mod tests {
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
fn drain_newest_first(&self) {
|
||||
let tasks = std::mem::take(&mut *self.0.lock().unwrap());
|
||||
for mut task in tasks.into_iter().rev() {
|
||||
while !poll_once(&mut task) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BlockingSpawner;
|
||||
@@ -320,7 +276,7 @@ mod tests {
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
|
||||
let slots = Slots::default();
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
assert_eq!(spawner.drain(), 0);
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
|
||||
|
||||
@@ -341,77 +297,11 @@ mod tests {
|
||||
Poll::Final(42u32)
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Partial(0));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Partial(0));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
|
||||
assert_eq!(spawner.drain(), 1, "an in-flight slot is not spawned twice");
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, false, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slot_keeping_the_previous_value_serves_it_until_the_next_response_lands() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
let fetch = |value: u32| {
|
||||
move || async move {
|
||||
YieldOnce(false).await;
|
||||
Poll::Final(value)
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)),
|
||||
Poll::Partial(0),
|
||||
"nothing landed yet, so the placeholder stands in"
|
||||
);
|
||||
spawner.drain();
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1)), Poll::Final(1));
|
||||
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Partial(1), "the previous value stands in");
|
||||
spawner.drain();
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2)), Poll::Final(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_response_landing_late_does_not_replace_the_previous_value() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
let fetch = |value: u32| {
|
||||
move || async move {
|
||||
YieldOnce(false).await;
|
||||
Poll::Final(value)
|
||||
}
|
||||
};
|
||||
|
||||
slots.resolve(1, &runtime, SOURCE, Some(0), true, fetch(1));
|
||||
slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch(2));
|
||||
spawner.drain_newest_first();
|
||||
|
||||
assert_eq!(slots.resolve(3, &runtime, SOURCE, Some(0), true, fetch(3)), Poll::Partial(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fallback_response_stands_in_as_the_previous_value() {
|
||||
let spawner = Arc::new(CollectSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
runtime.update_sources(&[SOURCE]);
|
||||
let slots = Slots::default();
|
||||
|
||||
slots.resolve(1, &runtime, SOURCE, Some(0), true, || async {
|
||||
YieldOnce(false).await;
|
||||
Poll::fallback(1, "failed")
|
||||
});
|
||||
spawner.drain();
|
||||
|
||||
let fetch = || async {
|
||||
YieldOnce(false).await;
|
||||
Poll::Final(2)
|
||||
};
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, Some(0), true, fetch), Poll::Partial(1));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42));
|
||||
assert_eq!(slots.resolve(2, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -424,7 +314,7 @@ mod tests {
|
||||
Poll::Final(42u32)
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), false, fetch), Poll::Final(42));
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42));
|
||||
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)]);
|
||||
}
|
||||
|
||||
@@ -438,11 +328,11 @@ mod tests {
|
||||
Poll::Final(42u32)
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
|
||||
let clone = slots.clone();
|
||||
drop(slots);
|
||||
assert_eq!(spawner.drain(), 1);
|
||||
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Final(42));
|
||||
assert_eq!(clone.resolve(1, &runtime, SOURCE, None, fetch), Poll::Final(42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -460,7 +350,7 @@ mod tests {
|
||||
}
|
||||
};
|
||||
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, false, fetch), Poll::Pending);
|
||||
assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending);
|
||||
drop(slots);
|
||||
assert_eq!(spawner.drain(), 1);
|
||||
assert!(!finished.load(Ordering::Relaxed));
|
||||
|
||||
@@ -9,13 +9,17 @@ use core_types::math::quad::Quad;
|
||||
use core_types::none;
|
||||
use core_types::ops::FromAnchorPosition;
|
||||
use core_types::transform::Transform;
|
||||
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use core_types::{
|
||||
ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY,
|
||||
ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color,
|
||||
};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
pub use vector_types::Vector;
|
||||
use vector_types::gradient_standard::GradientShape;
|
||||
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
|
||||
use vector_types::{Gradient, GradientSpread};
|
||||
use vector_types::{Gradient, GradientDirection, GradientModel, GradientSpread};
|
||||
|
||||
/// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node.
|
||||
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
|
||||
@@ -667,10 +671,11 @@ impl Graphic {
|
||||
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
||||
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
|
||||
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
||||
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
|
||||
// A `Clear` spread cuts off to transparency past the ends, and curved contours may leave gaps, leaving the rest of the region unpainted
|
||||
Graphic::Gradient(item) => {
|
||||
item_opacity_is_full(item)
|
||||
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
|
||||
&& gradient_paints_everywhere(&|key| item.attributes().get_any(key))
|
||||
&& item.element().iter().all(|stop| stop.color.is_opaque())
|
||||
}
|
||||
Graphic::GradientList(list) => {
|
||||
@@ -678,6 +683,7 @@ impl Graphic {
|
||||
&& every_item_has_full_opacity(list)
|
||||
&& (0..list.len()).all(|index| {
|
||||
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
|
||||
&& gradient_paints_everywhere(&|key| list.attribute_any(key, index))
|
||||
&& list.element(index).is_some_and(|stops| stops.iter().all(|stop| stop.color.is_opaque()))
|
||||
})
|
||||
}
|
||||
@@ -843,6 +849,22 @@ fn every_item_has_full_opacity<T>(list: &List<T>) -> bool {
|
||||
(0..list.len()).all(|index| list.attribute_cloned_or::<f64>(ATTR_OPACITY, index, 1.) >= 1. - f64::EPSILON && list.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, index, 1.) >= 1. - f64::EPSILON)
|
||||
}
|
||||
|
||||
/// Whether a gradient with the attributes the `attribute` lookup gives paints every point, which curved contours leaving gaps unfilled don't.
|
||||
fn gradient_paints_everywhere<'a>(attribute: &dyn Fn(&str) -> Option<&'a dyn std::any::Any>) -> bool {
|
||||
fn read<'a, T: 'static>(attribute: &dyn Fn(&str) -> Option<&'a dyn std::any::Any>, key: &str) -> Option<&'a T> {
|
||||
attribute(key).and_then(|value| value.downcast_ref::<T>())
|
||||
}
|
||||
|
||||
GradientShape::new(
|
||||
read::<f64>(attribute, ATTR_GRADIENT_START_CURVATURE).copied().unwrap_or_default(),
|
||||
read::<f64>(attribute, ATTR_GRADIENT_END_CURVATURE).copied().unwrap_or_default(),
|
||||
read::<GradientModel>(attribute, ATTR_GRADIENT_MODEL).copied().unwrap_or_default(),
|
||||
read::<GradientDirection>(attribute, ATTR_GRADIENT_DIRECTION).copied().unwrap_or_default(),
|
||||
read::<DAffine2>(attribute, ATTR_TRANSFORM).copied().unwrap_or_default(),
|
||||
)
|
||||
.paints_everywhere()
|
||||
}
|
||||
|
||||
/// Bounding box of one vector, inflated by its appearance's stroke when `include_stroke` is true.
|
||||
/// Paths and stroke parameters live on the holder's attributes, out of reach of the element-level impl.
|
||||
fn vector_bounding_box(vector: &Vector, paths: Option<&List<Path>>, composed_transform: DAffine2, appearance: Option<&Appearance>, include_stroke: bool) -> Option<[DVec2; 2]> {
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::warp_kernels::WarpRasterizer;
|
||||
use core_types::FallibleVec2Operations;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_FORM, Item, List};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE, Item, List};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
@@ -33,7 +33,8 @@ use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{CPU, Image, Raster};
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
use vector_types::gradient::{Gradient, GradientForm, GradientSettings, GradientSpread};
|
||||
use vector_types::gradient::{Gradient, GradientSettings, GradientSpread};
|
||||
use vector_types::gradient_standard::GradientShape;
|
||||
|
||||
mod styles;
|
||||
|
||||
@@ -1229,7 +1230,7 @@ fn drawn_paint_colors(operation: &EffectOperation, transform: DAffine2, size: DV
|
||||
Some(colors)
|
||||
}
|
||||
|
||||
/// Samples the paint's color at points in the space its placement maps into, faded by its opacity, for the paints the CPU can draw: colors, images, generators, linear or radial gradients, and those nested in a placement of their own.
|
||||
/// Samples the paint's color at points in the space its placement maps into, faded by its opacity, for the paints the CPU can draw: colors, images, generators, gradients, and those nested in a placement of their own.
|
||||
/// The paint's own adjustments are carried out first, and an image's own effects too.
|
||||
fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync + '_>> {
|
||||
let inverse = |placement: DAffine2| (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
|
||||
@@ -1260,7 +1261,11 @@ fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync +
|
||||
let item = evaluate_gradient_effects(item.clone());
|
||||
let position = gradient_position(&item)?;
|
||||
let evaluator = item.element().evaluator(GradientSettings::from_item_attributes(&item));
|
||||
Some(Box::new(move |point| faded(evaluator.evaluate(position(point)), opacity)))
|
||||
let spread = evaluator.settings().spread;
|
||||
Some(Box::new(move |point| {
|
||||
let color = position(point).map_or(Color::TRANSPARENT, |position| evaluator.evaluate(spread_position(position, spread)));
|
||||
faded(color, opacity)
|
||||
}))
|
||||
}
|
||||
Graphic::Graphic(item) => nested_sampler(item.element(), &|key| item.attributes().get_any(key)),
|
||||
Graphic::GraphicList(list) => {
|
||||
@@ -1408,7 +1413,9 @@ fn displacement_map_sampler(map: &Graphic) -> Option<Box<dyn Fn(DVec2) -> [f32;
|
||||
let samples = gradient.interpolated_samples(settings);
|
||||
|
||||
Some(Box::new(move |point| {
|
||||
let color = drawn_gradient_color(&samples, settings.spread, position(point));
|
||||
let color = position(point).map_or(Color::TRANSPARENT, |position| {
|
||||
drawn_gradient_color(&samples, settings.spread, spread_position(position, settings.spread))
|
||||
});
|
||||
premultiplied_gamma_channels(color).map(|channel| channel * opacity)
|
||||
}))
|
||||
}
|
||||
@@ -1495,22 +1502,54 @@ fn drawn_gradient_color(samples: &[(f64, Color, Option<f64>)], spread: GradientS
|
||||
}
|
||||
}
|
||||
|
||||
/// How far along the gradient each point lies, or `None` where its placement collapses it.
|
||||
fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> f64 + Sync>> {
|
||||
/// How far along the gradient each point lies, or `None` where it's unpainted, or no function where its placement collapses a form.
|
||||
/// A solid end stop's color is that end's infinite position, which [`spread_position`] keeps on that end under every spread.
|
||||
fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> Option<f64> + Sync>> {
|
||||
let placement: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let shape = GradientShape::new(
|
||||
item.attribute_cloned_or_default(ATTR_GRADIENT_START_CURVATURE),
|
||||
item.attribute_cloned_or_default(ATTR_GRADIENT_END_CURVATURE),
|
||||
item.attribute_cloned_or_default(ATTR_GRADIENT_MODEL),
|
||||
item.attribute_cloned_or_default(ATTR_GRADIENT_DIRECTION),
|
||||
placement,
|
||||
);
|
||||
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
|
||||
|
||||
match item.attribute_cloned_or_default::<GradientForm>(ATTR_GRADIENT_FORM) {
|
||||
match shape {
|
||||
// Measured along the line across the bands, which stay parallel to the placement's sheared y axis as the renderers draw them
|
||||
GradientForm::Linear => {
|
||||
GradientShape::Linear => {
|
||||
let axis = placement.matrix2.x_axis;
|
||||
let line = axis.try_project_onto(placement.matrix2.y_axis.perp()).unwrap_or(axis);
|
||||
let origin = placement.translation;
|
||||
(line.length_squared() > 0.).then(|| Box::new(move |point: DVec2| (point - origin).dot(line) / line.length_squared()) as Box<dyn Fn(DVec2) -> f64 + Sync>)
|
||||
(line.length_squared() > 0.).then(|| Box::new(move |point: DVec2| Some((point - origin).dot(line) / line.length_squared())) as Box<dyn Fn(DVec2) -> Option<f64> + Sync>)
|
||||
}
|
||||
GradientForm::Radial => {
|
||||
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse())?;
|
||||
Some(Box::new(move |point| to_unit.transform_point2(point).length()))
|
||||
GradientShape::Radial => {
|
||||
let to_unit = to_unit?;
|
||||
Some(Box::new(move |point| Some(to_unit.transform_point2(point).length())))
|
||||
}
|
||||
// Any other curvatures draw in the gradient space the full placement maps from, which a collapsed placement leaves a solid color needing none
|
||||
GradientShape::Standard(gradient) => {
|
||||
let to_unit = to_unit.unwrap_or_default();
|
||||
Some(Box::new(move |point| gradient.t(to_unit.transform_point2(point))))
|
||||
}
|
||||
// Apollonian circles paint every point, and a collapsed placement takes the Standard model's solid color instead
|
||||
GradientShape::Apollonian(parameters) => {
|
||||
let to_unit = to_unit?;
|
||||
Some(Box::new(move |point| Some(parameters.t(to_unit.transform_point2(point)))))
|
||||
}
|
||||
GradientShape::Across(across) => {
|
||||
let to_unit = to_unit?;
|
||||
Some(Box::new(move |point| across.chart.v(to_unit.transform_point2(point))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The position a `spread` reads along the ramp for one of a gradient's positions, which keeps an infinite one (a solid end stop) on that end's color under every spread but Clear.
|
||||
fn spread_position(position: f64, spread: GradientSpread) -> f64 {
|
||||
match (position.is_infinite(), spread) {
|
||||
(true, GradientSpread::Repeat | GradientSpread::Reflect) if position > 0. => 1. - f64::EPSILON,
|
||||
(true, GradientSpread::Repeat | GradientSpread::Reflect) => 0.,
|
||||
_ => position,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1588,6 +1627,33 @@ mod tests {
|
||||
assert!(alpha_at(5, 5) > 0.9, "{}", alpha_at(5, 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradients_read_across_their_contours_take_positions_around_them() {
|
||||
use std::f64::consts::TAU;
|
||||
use vector_types::gradient::GradientDirection;
|
||||
|
||||
// A sheared placement, which the linear form read across its line follows in full
|
||||
let placement = DAffine2::from_cols(DVec2::new(40., 10.), DVec2::new(-5., 25.), DVec2::new(7., 3.));
|
||||
let across = |[start, end]: [f64; 2]| {
|
||||
Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
|
||||
.with_attribute(ATTR_TRANSFORM, placement)
|
||||
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start)
|
||||
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end)
|
||||
.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across)
|
||||
};
|
||||
let (Some(linear), Some(radial)) = (gradient_position(&across([0., 0.])), gradient_position(&across([-1., 0.5]))) else {
|
||||
panic!("both forms should be read across their contours");
|
||||
};
|
||||
|
||||
for unit in [DVec2::new(0.3, 0.2), DVec2::new(-0.5, 0.7), DVec2::new(0.9, -0.4)] {
|
||||
let point = placement.transform_point2(unit);
|
||||
assert!(linear(point).is_some_and(|v| (v - unit.y).abs() < 1e-9), "linear at {unit}");
|
||||
|
||||
let angle = unit.y.atan2(unit.x).rem_euclid(TAU) / TAU;
|
||||
assert!(radial(point).is_some_and(|v| (v - angle).abs() < 1e-9), "radial at {unit}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_paints_fade_by_their_fill_once_with_effects_of_their_own() {
|
||||
use graphic_types::EffectKind;
|
||||
@@ -1877,9 +1943,7 @@ mod tests {
|
||||
|
||||
// A ramp from black to white across far more than the content, which lights flat ground wherever it reaches
|
||||
let stops = [(0., Color::BLACK), (1., Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||||
let ramp = Item::new_from_element(Gradient::new(stops))
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(-100.)) * DAffine2::from_scale(DVec2::splat(300.)))
|
||||
.with_attribute(ATTR_GRADIENT_FORM, GradientForm::Linear);
|
||||
let ramp = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(-100.)) * DAffine2::from_scale(DVec2::splat(300.)));
|
||||
|
||||
let mut emboss = EffectOperation::default_for(graphic_types::EffectKind::BevelAndEmboss);
|
||||
if let EffectOperation::BevelAndEmboss { style, size, texture, .. } = &mut emboss {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! What SVG can't express, which the GPU renders as images for an SVG to take, once the SVG is drawn.
|
||||
//! An effect whose coverage SVG filters can't work out, like the shadows and glows shaped for PSD interop, goes in its filter as a map of that coverage, while the content keeps its own markup.
|
||||
//! Content with an effect no filter can carry out, and a backdrop whose copy in markup would nest, are drawn as images in place of markup.
|
||||
//! Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
|
||||
//! Content with an effect no filter can carry out or a paint SVG only approximates (like a gradient of Apollonian circles), and a backdrop whose copy in markup would nest,
|
||||
//! are drawn as images in place of markup. Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
|
||||
|
||||
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix, render_raster_cpu_image_svg};
|
||||
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
|
||||
@@ -209,7 +209,7 @@ pub struct DeferredImage {
|
||||
/// What the GPU renders an image of for an SVG.
|
||||
#[derive(Clone)]
|
||||
pub enum DeferredContent {
|
||||
/// An item with effects SVG filters can't carry out, but without its opacity and blend mode, which the image takes instead.
|
||||
/// An item with effects SVG filters can't carry out or a paint SVG only approximates, but without its opacity and blend mode, which the image takes instead.
|
||||
Item(Graphic),
|
||||
/// What lies beneath content reading its backdrop, drawn in order, for which the markers stand around no markup.
|
||||
/// The outline of the backdrop root's `clip`, a path in the document filled by the nonzero rule, cuts it as it's drawn, as it cuts what a copy of it would hold.
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use crate::renderer::{
|
||||
ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, painted_gradient, spread_adjusted_samples, transform_is_invertible,
|
||||
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, painted_gradient, spread_adjusted_samples,
|
||||
svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
|
||||
};
|
||||
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::uuid::generate_uuid;
|
||||
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
|
||||
use core_types::{ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::vector_types::gradient::GradientForm;
|
||||
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use std::fmt::Write;
|
||||
use vector_types::Gradient;
|
||||
@@ -86,17 +86,27 @@ impl RenderExt for List<Color> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds one gradient item's def into `svg_defs` and returns the gradient ID, or `None` when the item is absent.
|
||||
/// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing.
|
||||
/// One painted through a mask fills a pattern spanning `bounds`, which `stroke_transform` places in the painted element's space.
|
||||
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
|
||||
fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut String, item_transform: DAffine2, element_transform: DAffine2, for_mask: bool) -> Option<u64> {
|
||||
fn render_gradient_paint(
|
||||
item: Option<ItemRef<'_, Gradient>>,
|
||||
svg_defs: &mut String,
|
||||
item_transform: DAffine2,
|
||||
element_transform: DAffine2,
|
||||
stroke_transform: DAffine2,
|
||||
bounds: DAffine2,
|
||||
for_mask: bool,
|
||||
) -> Option<u64> {
|
||||
let mut stop = String::new();
|
||||
|
||||
let item = item?;
|
||||
let (stops, settings) = painted_gradient(item)?;
|
||||
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
|
||||
let shape = gradient_shape(item);
|
||||
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
|
||||
let mut samples = spread_adjusted_samples(&stops, settings, gradient_form);
|
||||
let mut samples = spread_adjusted_samples(&stops, settings, shape);
|
||||
with_two_stops_at_least(shape, &mut samples);
|
||||
|
||||
let paint_opacity = item.paint_opacity(for_mask);
|
||||
if paint_opacity < 1. {
|
||||
@@ -105,7 +115,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
}
|
||||
}
|
||||
|
||||
for (position, color, original_midpoint) in samples {
|
||||
for &(position, color, original_midpoint) in &samples {
|
||||
stop.push_str("<stop");
|
||||
if position != 0. {
|
||||
let _ = write!(stop, r#" offset="{}""#, (position * 1_000_000.).round() / 1_000_000.);
|
||||
@@ -138,13 +148,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
|
||||
let document_transform = item_transform * local_gradient_transform;
|
||||
|
||||
let placement = gradient_placement(document_transform, gradient_form);
|
||||
let gradient_transform = format_transform_matrix(element_transform_inverse * placement);
|
||||
let gradient_transform = if gradient_transform.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(r#" gradientTransform="{gradient_transform}""#)
|
||||
};
|
||||
let gradient_transform = element_transform_inverse * gradient_placement(document_transform, shape);
|
||||
|
||||
let gradient_spread = if matches!(settings.spread, GradientSpread::Pad | GradientSpread::Clear) {
|
||||
String::new()
|
||||
@@ -152,26 +156,45 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
format!(r#" spreadMethod="{}""#, settings.spread.svg_name())
|
||||
};
|
||||
|
||||
let gradient_id = generate_uuid();
|
||||
// A paint drawn through a mask fills a pattern of the box around the painted area, which the masks are drawn over
|
||||
let masked = svg_gradient_standard(shape).is_some_and(|gradient| gradient.is_masked());
|
||||
let pattern_area = if masked {
|
||||
let inverse = |length: f64| if length > 0. { 1. / length } else { 0. };
|
||||
let inflate = DVec2::new(inverse(item_transform.matrix2.x_axis.length()), inverse(item_transform.matrix2.y_axis.length()));
|
||||
let (local_min, local_max) = (bounds.transform_point2(DVec2::ZERO) - inflate, bounds.transform_point2(DVec2::ONE) + inflate);
|
||||
|
||||
match gradient_form {
|
||||
GradientForm::Linear => {
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<linearGradient id="{}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{gradient_spread}{gradient_transform}>{}</linearGradient>"#,
|
||||
gradient_id, stop
|
||||
);
|
||||
}
|
||||
GradientForm::Radial => {
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<radialGradient id="{}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"{gradient_spread}{gradient_transform}>{}</radialGradient>"#,
|
||||
gradient_id, stop
|
||||
);
|
||||
let corners = [local_min, DVec2::new(local_max.x, local_min.y), DVec2::new(local_min.x, local_max.y), local_max].map(|corner| stroke_transform.transform_point2(corner));
|
||||
let min = corners.into_iter().reduce(DVec2::min)?;
|
||||
let size = corners.into_iter().reduce(DVec2::max)? - min;
|
||||
if !(size.x > 0. && size.y > 0. && size.is_finite() && min.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some((min, size))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let area = pattern_area.map_or(String::new(), |(min, size)| format!(r#"rect x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, size.x, size.y));
|
||||
|
||||
let layers = write_svg_gradient_paint(svg_defs, shape, &samples, &stop, &gradient_spread, gradient_transform, &area);
|
||||
if let [SvgGradientLayer { paint, mask: None }] = layers.as_slice() {
|
||||
return Some(*paint);
|
||||
}
|
||||
|
||||
Some(gradient_id)
|
||||
let (min, size) = pattern_area?;
|
||||
let pattern_id = generate_uuid();
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<pattern id="{pattern_id}" patternUnits="userSpaceOnUse" x="{}" y="{}" width="{}" height="{}" viewBox="{} {} {} {}">"#,
|
||||
min.x, min.y, size.x, size.y, min.x, min.y, size.x, size.y
|
||||
);
|
||||
for SvgGradientLayer { paint, mask } in layers {
|
||||
let mask = mask.map(|mask| format!(r#" mask="url(#{mask})""#)).unwrap_or_default();
|
||||
let _ = write!(svg_defs, r#"<{area} fill="url(#{paint})"{mask} />"#);
|
||||
}
|
||||
svg_defs.push_str("</pattern>");
|
||||
|
||||
Some(pattern_id)
|
||||
}
|
||||
|
||||
impl RenderExt for List<Gradient> {
|
||||
@@ -185,8 +208,8 @@ impl RenderExt for List<Gradient> {
|
||||
_paint_reach: f64,
|
||||
item_transform: DAffine2,
|
||||
element_transform: DAffine2,
|
||||
_stroke_transform: DAffine2,
|
||||
_bounds: DAffine2,
|
||||
stroke_transform: DAffine2,
|
||||
bounds: DAffine2,
|
||||
render_params: &RenderParams,
|
||||
_target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
@@ -195,6 +218,8 @@ impl RenderExt for List<Gradient> {
|
||||
svg_defs,
|
||||
item_transform,
|
||||
element_transform,
|
||||
stroke_transform,
|
||||
bounds,
|
||||
render_params.for_mask,
|
||||
)
|
||||
}
|
||||
@@ -292,7 +317,7 @@ impl RenderExt for Graphic {
|
||||
render_params,
|
||||
target,
|
||||
),
|
||||
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, render_params.for_mask)
|
||||
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
|
||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,7 +11,7 @@ use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use vello_gpu::peniko::{self, BlendMode, BrushRef, Fill};
|
||||
use vello_gpu::{Image, ImageSource, PaintType, TextureId, TextureRegion};
|
||||
use vello_gpu::{ApollonianGradient, Image, ImageSource, PaintType, PolarGradient, TextureId, TextureRegion};
|
||||
|
||||
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
|
||||
const SHAPE_TOLERANCE: f64 = 0.1;
|
||||
@@ -94,6 +94,59 @@ pub trait EffectsRenderer: Send {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a fill or stroke paints with.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum SceneBrush<'b> {
|
||||
/// A solid color, gradient, or image.
|
||||
Peniko(BrushRef<'b>),
|
||||
/// A gradient whose contours are Apollonian circles, which only Vello GPU's fork draws.
|
||||
Apollonian(&'b ApollonianGradient),
|
||||
/// A gradient whose position runs around its contours, which only Vello GPU's fork draws.
|
||||
Polar(&'b PolarGradient),
|
||||
}
|
||||
|
||||
impl<'b> From<BrushRef<'b>> for SceneBrush<'b> {
|
||||
fn from(brush: BrushRef<'b>) -> Self {
|
||||
Self::Peniko(brush)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'b> From<&'b peniko::Brush> for SceneBrush<'b> {
|
||||
fn from(brush: &'b peniko::Brush) -> Self {
|
||||
Self::Peniko(brush.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'b> From<&'b peniko::Gradient> for SceneBrush<'b> {
|
||||
fn from(gradient: &'b peniko::Gradient) -> Self {
|
||||
Self::Peniko(gradient.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<peniko::Color> for SceneBrush<'_> {
|
||||
fn from(color: peniko::Color) -> Self {
|
||||
Self::Peniko(color.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&peniko::Color> for SceneBrush<'_> {
|
||||
fn from(color: &peniko::Color) -> Self {
|
||||
Self::Peniko((*color).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'b> From<&'b ApollonianGradient> for SceneBrush<'b> {
|
||||
fn from(gradient: &'b ApollonianGradient) -> Self {
|
||||
Self::Apollonian(gradient)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'b> From<&'b PolarGradient> for SceneBrush<'b> {
|
||||
fn from(gradient: &'b PolarGradient) -> Self {
|
||||
Self::Polar(gradient)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels behind an image the scene draws.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SceneImage {
|
||||
@@ -270,44 +323,41 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
}
|
||||
|
||||
/// Fills a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
||||
pub fn fill<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
pub fn fill<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
self.fill_path(fill_rule, transform, brush, brush_transform, &shape.to_path(SHAPE_TOLERANCE));
|
||||
}
|
||||
|
||||
/// Like [`Self::fill`] for a path, which it draws without copying.
|
||||
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
|
||||
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
self.scene.fill_path(&finite_path(path));
|
||||
}
|
||||
|
||||
/// Strokes a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
||||
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_stroke(stroke.clone());
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
self.scene.stroke_path(&finite_path(&shape.to_path(SHAPE_TOLERANCE)));
|
||||
}
|
||||
|
||||
/// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content.
|
||||
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
|
||||
pub fn fill_viewport<'b>(&mut self, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
||||
self.scene.set_transform(Affine::IDENTITY);
|
||||
self.scene.set_paint(paint);
|
||||
self.scene.set_paint_transform(self.view * brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||
self.scene.fill_rect(&Rect::new(0., 0., self.width() as f64, self.height() as f64));
|
||||
}
|
||||
@@ -698,22 +748,31 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self.scene.fill_rect(&Rect::new(0., 0., width as f64, height as f64));
|
||||
}
|
||||
|
||||
/// The Vello GPU paint for a brush, plus the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
|
||||
fn paint(&mut self, brush: BrushRef<'_>) -> Option<(PaintType, Affine)> {
|
||||
match brush {
|
||||
BrushRef::Solid(color) => Some((PaintType::Solid(color), Affine::IDENTITY)),
|
||||
BrushRef::Gradient(gradient) => Some((PaintType::Gradient(gradient.clone()), Affine::IDENTITY)),
|
||||
BrushRef::Image(image) => {
|
||||
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image.clone()))?;
|
||||
Some((
|
||||
PaintType::Image(Image {
|
||||
image: source,
|
||||
sampler: image.sampler,
|
||||
}),
|
||||
texture_to_image,
|
||||
))
|
||||
/// Paints with `brush`, returning the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
|
||||
fn set_paint(&mut self, brush: SceneBrush<'_>) -> Option<Affine> {
|
||||
let (paint, paint_to_brush) = match brush {
|
||||
SceneBrush::Apollonian(gradient) => {
|
||||
self.scene.set_apollonian_gradient_paint(gradient.clone());
|
||||
return Some(Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
SceneBrush::Polar(gradient) => {
|
||||
self.scene.set_polar_gradient_paint(gradient.clone());
|
||||
return Some(Affine::IDENTITY);
|
||||
}
|
||||
SceneBrush::Peniko(BrushRef::Solid(color)) => (PaintType::Solid(color), Affine::IDENTITY),
|
||||
SceneBrush::Peniko(BrushRef::Gradient(gradient)) => (PaintType::Gradient(gradient.clone()), Affine::IDENTITY),
|
||||
SceneBrush::Peniko(BrushRef::Image(image)) => {
|
||||
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image.clone()))?;
|
||||
let paint = PaintType::Image(Image {
|
||||
image: source,
|
||||
sampler: image.sampler,
|
||||
});
|
||||
(paint, texture_to_image)
|
||||
}
|
||||
};
|
||||
self.scene.set_paint(paint);
|
||||
|
||||
Some(paint_to_brush)
|
||||
}
|
||||
|
||||
/// The external texture standing for an image, with the transform from its texture's pixels onto the image's own pixels and its texture's size.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{affine, color};
|
||||
use core_types::list::{ATTR_POSITION, Item};
|
||||
use core_types::{ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_TRANSFORM};
|
||||
use core_types::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_TRANSFORM};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::vector_types::{Gradient, GradientForm, GradientSpace, GradientSpread};
|
||||
@@ -31,7 +31,9 @@ fn paint(gradient: &usvg::BaseGradient, form: GradientForm, unit_placement: DAff
|
||||
let mut item = Item::new_from_element(Gradient(stops)).with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma);
|
||||
|
||||
if form != GradientForm::default() {
|
||||
item.set_attribute(ATTR_GRADIENT_FORM, form);
|
||||
let [start_curvature, end_curvature] = form.curvatures();
|
||||
item.set_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature);
|
||||
item.set_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature);
|
||||
}
|
||||
let spread = match gradient.spread_method() {
|
||||
usvg::SpreadMethod::Pad => GradientSpread::Pad,
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use core_types::list::{ATTR_APPEARANCE, Item, List};
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_EFFECTS, ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, BlendMode, Color};
|
||||
use core_types::{
|
||||
ATTR_BLEND_MODE, ATTR_EFFECTS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, BlendMode,
|
||||
Color,
|
||||
};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effects::shadow_offset;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
@@ -177,7 +180,11 @@ fn a_bounding_box_radial_gradient_on_a_wide_shape_is_placed_as_an_ellipse() -> R
|
||||
let content = converted(r#"<radialGradient id="g"><stop stop-color="red"/><stop offset="1" stop-color="blue"/></radialGradient><rect width="8" height="4" fill="url(#g)"/>"#)?;
|
||||
|
||||
let gradient = gradient_of(&content, Cover::Fill);
|
||||
assert_eq!(gradient.and_then(|gradient| gradient.attribute::<GradientForm>(ATTR_GRADIENT_FORM)), Some(&GradientForm::Radial));
|
||||
let curvature = |key| gradient.and_then(|gradient| gradient.attribute::<f64>(key)).copied();
|
||||
assert_eq!(
|
||||
[curvature(ATTR_GRADIENT_START_CURVATURE), curvature(ATTR_GRADIENT_END_CURVATURE)],
|
||||
GradientForm::Radial.curvatures().map(Some)
|
||||
);
|
||||
assert_eq!(
|
||||
gradient.and_then(|gradient| gradient.attribute::<DAffine2>(ATTR_TRANSFORM)),
|
||||
Some(&DAffine2::from_cols(DVec2::new(4., 0.), DVec2::new(0., 2.), DVec2::new(4., 2.)))
|
||||
|
||||
@@ -17,6 +17,40 @@ pub enum GradientForm {
|
||||
Radial,
|
||||
}
|
||||
|
||||
/// The curvatures of the linear form: both ends are lines.
|
||||
pub const LINEAR_CURVATURES: [f64; 2] = [0., 0.];
|
||||
/// The curvatures of the radial form: the start is a point at the center, and the end is the circle around it through the end point.
|
||||
/// The point is -1 rather than 1 since animating from the linear form toward -1 keeps each circle nested in the next.
|
||||
pub const RADIAL_CURVATURES: [f64; 2] = [-1., 0.5];
|
||||
|
||||
impl GradientForm {
|
||||
/// The curvatures of the start and end contours that make this form.
|
||||
pub fn curvatures(self) -> [f64; 2] {
|
||||
match self {
|
||||
Self::Linear => LINEAR_CURVATURES,
|
||||
Self::Radial => RADIAL_CURVATURES,
|
||||
}
|
||||
}
|
||||
|
||||
/// The form these curvatures make, if either, once wrapped like [`wrapped_curvature`].
|
||||
pub fn from_curvatures(curvatures: [f64; 2]) -> Option<Self> {
|
||||
match curvatures.map(|curvature| wrapped_curvature(curvature, f64::NAN)) {
|
||||
LINEAR_CURVATURES => Some(Self::Linear),
|
||||
RADIAL_CURVATURES => Some(Self::Radial),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A curvature wrapped into the range starting at -1, since -1 and 1 are both the end's own point, or `preset` if it isn't finite.
|
||||
pub fn wrapped_curvature(curvature: f64, preset: f64) -> f64 {
|
||||
match curvature {
|
||||
_ if (-1. ..1.).contains(&curvature) => curvature,
|
||||
_ if curvature.is_finite() => (curvature + 1.).rem_euclid(2.) - 1.,
|
||||
_ => preset,
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient's stops: a list of colors (linear, unassociated alpha) whose optional `position` and `midpoint`
|
||||
/// attributes place each stop along the 0 to 1 range. Stops lacking the `position` attribute distribute evenly,
|
||||
/// and stops lacking the `midpoint` attribute interpolate linearly (`0.5`).
|
||||
@@ -1809,6 +1843,32 @@ impl GradientEvaluator {
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[widget(Radio)]
|
||||
pub enum GradientModel {
|
||||
/// Draws the contours between the two ends the way SVG and other apps do, each a circle interpolated between the two end circles. Where the end circles don't nest, it leaves gaps unpainted.
|
||||
#[default]
|
||||
Standard,
|
||||
/// Draws the contours between the two ends as a single family of circles that never cross one another, except at points they all share, and together fill the whole plane. SVG exports include it as an image, and PDF exports show an approximation.
|
||||
Apollonian,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[widget(Radio)]
|
||||
pub enum GradientDirection {
|
||||
/// Reads the colors from start to end, each contour taking one color.
|
||||
#[default]
|
||||
Along,
|
||||
/// Reads the colors around each contour instead, once clockwise around curved ones, or beside the gradient line in the linear form. Except for the linear form, SVG exports include it as an image, and PDF exports show an approximation.
|
||||
Across,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
@@ -2063,6 +2123,19 @@ impl core_types::bounds::BoundingBox for Gradient {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn curvatures_make_a_form_only_at_its_presets_once_wrapped() {
|
||||
assert_eq!(GradientForm::from_curvatures([0., 0.]), Some(GradientForm::Linear));
|
||||
assert_eq!(GradientForm::from_curvatures([1., 0.5]), Some(GradientForm::Radial));
|
||||
assert_eq!(GradientForm::from_curvatures([-1., 0.5]), Some(GradientForm::Radial));
|
||||
assert_eq!(GradientForm::from_curvatures([3., 0.5]), Some(GradientForm::Radial));
|
||||
assert_eq!(GradientForm::from_curvatures([2., -2.]), Some(GradientForm::Linear));
|
||||
|
||||
assert_eq!(GradientForm::from_curvatures([0.5, 0.25]), None);
|
||||
assert_eq!(GradientForm::from_curvatures([f64::NAN, 0.]), None);
|
||||
assert_eq!(GradientForm::from_curvatures([f64::INFINITY, 0.5]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_is_empty_and_black_to_white_is_the_artist_starting_gradient() {
|
||||
assert!(Gradient::default().is_empty());
|
||||
|
||||
@@ -0,0 +1,479 @@
|
||||
//! Gradients read across their contours rather than along them, where each point's position `v` runs around or beside the contour through it.
|
||||
//!
|
||||
//! Everything here is in gradient space, laid out as in [`crate::gradient_standard`], and `v` increases toward +y (clockwise on screen for an
|
||||
//! unreflected placement). A winding chart measures an angle in turns within `[0, 1)`, wrapping at a seam on the +x side where the spread has no
|
||||
//! effect. The others measure from the gradient line, 0 on it and one unit per gradient length across its midpoint, which the spread then repeats.
|
||||
|
||||
use crate::gradient::{GradientForm, GradientModel};
|
||||
use crate::gradient_apollonian::{AxisCircle, CircleFamily, Homogeneous};
|
||||
use crate::gradient_standard::{Cone, GradientStandard, HalfPlane, NEAR_LINE_RADIUS, curvature_radius};
|
||||
use glam::DVec2;
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
/// How far apart a cone's two centers may be, relative to its size, for it to be drawn as concentric circles.
|
||||
const CONCENTRIC_TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// A gradient read across its contours.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct GradientAcross {
|
||||
pub chart: AcrossChart,
|
||||
/// The form its curvatures make, if either.
|
||||
pub form: Option<GradientForm>,
|
||||
}
|
||||
|
||||
/// How each point of a gradient read across its contours finds its position `v`, in gradient space.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum AcrossChart {
|
||||
/// The linear form's: `v = y`.
|
||||
Linear,
|
||||
/// Concentric circles': the angle around their shared center at `(center, 0)`, from the +x ray.
|
||||
Concentric { center: f64 },
|
||||
/// SVG 2's cone's: the angle of the point around the center of the cone's circle through it, unpainted where the cone is and past `keep`'s line.
|
||||
Cone { cone: Cone, keep: Option<HalfPlane> },
|
||||
/// Apollonian circles nesting around two limit points: the angle of `M(z) = (n₀ z + n₁) / (d₀ z + d₁)`, which sends the limit point the
|
||||
/// end contour encloses to 0 and the other to infinity, so each contour of constant `v` is an arc from one limit point to the other.
|
||||
Mobius { numerator: [f64; 2], denominator: [f64; 2] },
|
||||
/// Apollonian circles crossing at `(center_x, ±half_height)`: `scale · ln(|z - (center_x, -half_height)| / |z - (center_x, half_height)|)`,
|
||||
/// the bipolar coordinate whose contours are the circles around the two crossings.
|
||||
Bipolar { center_x: f64, half_height: f64, scale: f64 },
|
||||
/// Unpainted everywhere, as SVG 2 leaves identical end circles.
|
||||
Nothing,
|
||||
}
|
||||
|
||||
impl AcrossChart {
|
||||
/// The chart of a gradient with these curvatures, which must be finite and within -1 to 1, and model.
|
||||
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel) -> Self {
|
||||
match (GradientForm::from_curvatures([start_curvature, end_curvature]), model) {
|
||||
(Some(GradientForm::Linear), _) => Self::Linear,
|
||||
(Some(GradientForm::Radial), _) => Self::Concentric { center: 0. },
|
||||
(None, GradientModel::Standard) => Self::standard(start_curvature, end_curvature),
|
||||
(None, GradientModel::Apollonian) => Self::apollonian(start_curvature, end_curvature),
|
||||
}
|
||||
}
|
||||
|
||||
/// The angle around SVG 2's circles, painting where the Standard model's gradient read along them paints.
|
||||
fn standard(start_curvature: f64, end_curvature: f64) -> Self {
|
||||
match GradientStandard::new(start_curvature, end_curvature) {
|
||||
GradientStandard::Cone(cone) => Self::cone(cone, None),
|
||||
// A line end and a nearly flat cone, drawn as a profile along the gradient line, measure around the cone that's drawn at the flattest radius
|
||||
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => Self::cone(near_line_cone(start_curvature, end_curvature), keep),
|
||||
GradientStandard::Profile { .. } => Self::cone(near_line_cone(start_curvature, end_curvature), None),
|
||||
GradientStandard::Nothing => Self::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
fn cone(cone: Cone, keep: Option<HalfPlane>) -> Self {
|
||||
let size = cone.start_center.abs().max(cone.end_center.abs()).max(cone.start_radius).max(cone.end_radius);
|
||||
let concentric = (cone.end_center - cone.start_center).abs() <= CONCENTRIC_TOLERANCE * size;
|
||||
|
||||
match keep {
|
||||
None if concentric => Self::Concentric { center: cone.start_center },
|
||||
_ => Self::Cone { cone, keep },
|
||||
}
|
||||
}
|
||||
|
||||
/// The angle around the limit points of the Apollonian circles, or the bipolar coordinate beside their crossings.
|
||||
fn apollonian(start_curvature: f64, end_curvature: f64) -> Self {
|
||||
// Identical end circles span no family of circles, and draw the linear form's plain ramp
|
||||
let (start_radius, end_radius) = (curvature_radius(start_curvature), curvature_radius(end_curvature));
|
||||
if start_radius.is_finite() && end_radius.is_finite() && Cone::between(start_radius, end_radius).is_identical() {
|
||||
return Self::Linear;
|
||||
}
|
||||
|
||||
let (start, end) = (AxisCircle::start(start_curvature), AxisCircle::end(end_curvature));
|
||||
match CircleFamily::of(start, end) {
|
||||
CircleFamily::Crossing { radical_x } => Self::bipolar(start, end, radical_x),
|
||||
CircleFamily::Nesting { limit_points } => Self::mobius(start, end, limit_points),
|
||||
}
|
||||
}
|
||||
|
||||
fn bipolar(start: AxisCircle, end: AxisCircle, radical_x: f64) -> Self {
|
||||
// The crossings lie on whichever end contour is rounder, which places them most precisely
|
||||
let circle = if start.a.abs() >= end.a.abs() { start } else { end };
|
||||
let half_height = (-(circle.b * radical_x + circle.c) / circle.a - radical_x * radical_x).max(0.).sqrt().max(f64::MIN_POSITIVE);
|
||||
|
||||
// The coordinate's rate across the gradient line at its midpoint is `half_height / (half_height² + (1/2 - radical_x)²)` before this scale
|
||||
let midpoint_offset = 0.5 - radical_x;
|
||||
let scale = (half_height * half_height + midpoint_offset * midpoint_offset) / (2. * half_height);
|
||||
|
||||
Self::Bipolar {
|
||||
center_x: radical_x,
|
||||
half_height,
|
||||
scale,
|
||||
}
|
||||
}
|
||||
|
||||
fn mobius(start: AxisCircle, end: AxisCircle, limit_points: [Homogeneous; 2]) -> Self {
|
||||
// With nonnegative denominators, a point's sign on a contour doesn't depend on how it's scaled
|
||||
let oriented = |point: Homogeneous| {
|
||||
let sign = if point.denominator < 0. { -1. } else { 1. };
|
||||
Homogeneous {
|
||||
numerator: point.numerator * sign,
|
||||
denominator: point.denominator * sign,
|
||||
}
|
||||
};
|
||||
let [first, second] = limit_points.map(oriented);
|
||||
|
||||
// The limit point inside the end contour, or the start contour where the end is a line, is negative on it (or zero, for a point contour on it)
|
||||
let inside = |circle: AxisCircle, point: Homogeneous| {
|
||||
let Homogeneous { numerator, denominator } = point;
|
||||
circle.a * (circle.a * numerator * numerator + circle.b * numerator * denominator + circle.c * denominator * denominator)
|
||||
};
|
||||
let enclosing = if end.a != 0. { end } else { start };
|
||||
let (enclosed, other) = if inside(enclosing, first) <= inside(enclosing, second) {
|
||||
(first, second)
|
||||
} else {
|
||||
(second, first)
|
||||
};
|
||||
|
||||
// Concentric circles have their other limit point at infinity, about which the angle is around their shared center
|
||||
let Some(center) = enclosed.value() else { return Self::Linear };
|
||||
if other.denominator == 0. {
|
||||
return Self::Concentric { center };
|
||||
}
|
||||
|
||||
// `M(z) = ±(z - enclosed) / (other - z)`, signed so `M` is positive on the +x ray from the enclosed limit point as `other` passes through infinity
|
||||
let product = other.numerator * enclosed.denominator - enclosed.numerator * other.denominator;
|
||||
let sign = if product < 0. { -1. } else { 1. };
|
||||
Self::Mobius {
|
||||
numerator: [sign * enclosed.denominator, -sign * enclosed.numerator],
|
||||
denominator: [-other.denominator, other.numerator],
|
||||
}
|
||||
}
|
||||
|
||||
/// The position at `point`, or `None` where it's unpainted.
|
||||
pub fn v(&self, point: DVec2) -> Option<f64> {
|
||||
match *self {
|
||||
Self::Linear => Some(point.y),
|
||||
Self::Concentric { center } => Some(turns(point.y, point.x - center)),
|
||||
Self::Cone { cone, keep } => {
|
||||
if keep.is_some_and(|keep| !keep.keeps(point.x)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let t = cone.t(point)?;
|
||||
let center = cone.start_center + t * (cone.end_center - cone.start_center);
|
||||
Some(turns(point.y, point.x - center))
|
||||
}
|
||||
Self::Mobius { numerator, denominator } => {
|
||||
// The angle of `numerator / denominator` is that of `numerator · conj(denominator)`
|
||||
let affine = |[slope, intercept]: [f64; 2]| DVec2::new(slope * point.x + intercept, slope * point.y);
|
||||
let (numerator, denominator) = (affine(numerator), affine(denominator));
|
||||
Some(turns(numerator.y * denominator.x - numerator.x * denominator.y, numerator.dot(denominator)))
|
||||
}
|
||||
Self::Bipolar { center_x, half_height, scale } => {
|
||||
// The squared distances to the crossings differ by `4 half_height y`, whose ratio's logarithm keeps its precision near the gradient line
|
||||
let to_upper = DVec2::new(point.x - center_x, point.y - half_height).length_squared();
|
||||
Some(scale * 0.5 * (4. * half_height * point.y / to_upper).ln_1p())
|
||||
}
|
||||
Self::Nothing => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether it measures an angle, wrapping from 1 back to 0 at a seam, rather than a distance from the gradient line.
|
||||
pub fn winds(&self) -> bool {
|
||||
matches!(self, Self::Concentric { .. } | Self::Cone { .. } | Self::Mobius { .. })
|
||||
}
|
||||
|
||||
/// Whether it paints every point, rather than leaving some unpainted.
|
||||
pub fn paints_everywhere(&self) -> bool {
|
||||
match self {
|
||||
Self::Linear | Self::Concentric { .. } | Self::Mobius { .. } | Self::Bipolar { .. } => true,
|
||||
Self::Cone { cone, keep } => keep.is_none() && cone.is_nested(),
|
||||
Self::Nothing => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether SVG draws it exactly, which only the linear form's ramp across the gradient line is (and nothing at all).
|
||||
pub fn svg_draws_exactly(&self) -> bool {
|
||||
matches!(self, Self::Linear | Self::Nothing)
|
||||
}
|
||||
}
|
||||
|
||||
/// The cone between the end contours with these curvatures, each a nearly flat circle or a line drawn at the flattest radius a cone is (a line bowing toward the other end).
|
||||
fn near_line_cone(start_curvature: f64, end_curvature: f64) -> Cone {
|
||||
let near_line_radius = |curvature: f64| {
|
||||
let radius = curvature_radius(curvature);
|
||||
if radius.is_infinite() {
|
||||
NEAR_LINE_RADIUS
|
||||
} else {
|
||||
radius.clamp(-NEAR_LINE_RADIUS, NEAR_LINE_RADIUS)
|
||||
}
|
||||
};
|
||||
Cone::between(near_line_radius(start_curvature), near_line_radius(end_curvature))
|
||||
}
|
||||
|
||||
/// The angle of `(x, y)` from the +x axis toward the +y axis, in turns within `[0, 1)`.
|
||||
fn turns(y: f64, x: f64) -> f64 {
|
||||
let turns = y.atan2(x).rem_euclid(TAU) / TAU;
|
||||
if turns >= 1. { 0. } else { turns }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::gradient::{LINEAR_CURVATURES, RADIAL_CURVATURES};
|
||||
use crate::gradient_apollonian::GradientApollonian;
|
||||
use crate::gradient_standard::radius_curvature;
|
||||
|
||||
/// Points spread over a view around the gradient line, kept off its exact rational coordinates.
|
||||
fn sample_points() -> impl Iterator<Item = DVec2> {
|
||||
(-30..=40).flat_map(|x| (-25..=25).map(move |y| DVec2::new(x as f64 * 0.1 + 0.0013, y as f64 * 0.1 + 0.0007)))
|
||||
}
|
||||
|
||||
/// The distance between two angles in turns, the short way around.
|
||||
fn turn_distance(first: f64, second: f64) -> f64 {
|
||||
let distance = (first - second).rem_euclid(1.);
|
||||
distance.min(1. - distance)
|
||||
}
|
||||
|
||||
/// Curvature pairs of every kind: circles crossing, nested, apart, and concentric, lines and points beside them, and nearly flat circles.
|
||||
fn curvature_pairs() -> Vec<[f64; 2]> {
|
||||
let mut pairs: Vec<[f64; 2]> = [
|
||||
(0., 0.75),
|
||||
(0.2, 1.5),
|
||||
(2., -0.5),
|
||||
(0.6, 0.6),
|
||||
(-0.3, -0.3),
|
||||
(0., -0.4),
|
||||
(2., -1.),
|
||||
(-0.5, 1.5),
|
||||
(0.8, 1e9),
|
||||
(-0.3, 1e9),
|
||||
(1e9, 0.25),
|
||||
(1e9, 2.),
|
||||
(3000., -2500.),
|
||||
(0.3, 2500.),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(start, end)| [radius_curvature(start), radius_curvature(end)])
|
||||
.collect();
|
||||
pairs.extend([[1., 0.3], [1., 1.], [0.8, -1.], [0.4, 0.], [0., -0.4], [-0.3, 0.]]);
|
||||
pairs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_linear_form_reads_across_the_gradient_line() {
|
||||
for model in [GradientModel::Standard, GradientModel::Apollonian] {
|
||||
let chart = AcrossChart::new(LINEAR_CURVATURES[0], LINEAR_CURVATURES[1], model);
|
||||
assert_eq!(chart, AcrossChart::Linear);
|
||||
for point in sample_points() {
|
||||
assert_eq!(chart.v(point), Some(point.y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_radial_form_reads_the_angle_around_its_center() {
|
||||
for model in [GradientModel::Standard, GradientModel::Apollonian] {
|
||||
let chart = AcrossChart::new(RADIAL_CURVATURES[0], RADIAL_CURVATURES[1], model);
|
||||
for point in sample_points() {
|
||||
let expected = point.y.atan2(point.x).rem_euclid(TAU) / TAU;
|
||||
assert!(turn_distance(chart.v(point).unwrap(), expected) < 1e-12, "{model:?} at {point}");
|
||||
}
|
||||
|
||||
// Clockwise on screen, from the seam along the gradient line
|
||||
assert!((chart.v(DVec2::new(0., 1.)).unwrap() - 0.25).abs() < 1e-12);
|
||||
assert!(chart.v(DVec2::new(0.5, 1e-9)).unwrap() < 1e-6 && chart.v(DVec2::new(0.5, -1e-9)).unwrap() > 1. - 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_models_read_concentric_circles_around_their_center() {
|
||||
// The start circle centered at its radius and the end at 1 minus its own share a center, with the end circle outside or inside the start circle
|
||||
for start_radius in [-1., -0.5, 0.25, 2., 3.] {
|
||||
let curvatures = [radius_curvature(start_radius), radius_curvature(1. - start_radius)];
|
||||
let [standard, apollonian] = [GradientModel::Standard, GradientModel::Apollonian].map(|model| AcrossChart::new(curvatures[0], curvatures[1], model));
|
||||
let cone = AcrossChart::Cone {
|
||||
cone: Cone::between(start_radius, 1. - start_radius),
|
||||
keep: None,
|
||||
};
|
||||
|
||||
assert!(matches!(standard, AcrossChart::Concentric { .. }), "{standard:?}");
|
||||
assert!(matches!(apollonian, AcrossChart::Concentric { .. }), "{apollonian:?}");
|
||||
for point in sample_points() {
|
||||
let expected = (point.y).atan2(point.x - start_radius).rem_euclid(TAU) / TAU;
|
||||
for (chart, name) in [(standard, "Standard"), (apollonian, "Apollonian"), (cone, "cone")] {
|
||||
let v = chart.v(point).unwrap_or_else(|| panic!("{name} leaves {point} unpainted with start radius {start_radius}"));
|
||||
assert!(turn_distance(v, expected) < 1e-9, "{name} with start radius {start_radius} at {point}: {v} rather than {expected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standard_contours_of_constant_position_are_rays_from_the_apex() {
|
||||
// Off-center pairs with an apex where the cone's circles shrink to a point
|
||||
for (start, end) in [(0., 0.75), (0.2, 1.5), (0.6, 0.3), (-0.3, -0.6), (2., -0.5)] {
|
||||
let cone = Cone::between(start, end);
|
||||
let chart = AcrossChart::new(radius_curvature(start), radius_curvature(end), GradientModel::Standard);
|
||||
assert!(matches!(chart, AcrossChart::Cone { .. }), "({start}, {end}) should be a cone, not {chart:?}");
|
||||
|
||||
let delta_radius = cone.end_radius - cone.start_radius;
|
||||
let apex_t = -cone.start_radius / delta_radius;
|
||||
let apex = DVec2::new(cone.start_center + apex_t * (cone.end_center - cone.start_center), 0.);
|
||||
|
||||
for angle in (0..24).map(|step| (step as f64 + 0.37) * TAU / 24.) {
|
||||
let direction = DVec2::from_angle(angle);
|
||||
let positions: Vec<f64> = [0.2, 0.5, 1., 2., 4.].into_iter().filter_map(|distance| chart.v(apex + direction * distance)).collect();
|
||||
for &v in &positions {
|
||||
assert!(turn_distance(v, positions[0]) < 1e-9, "({start}, {end}) along the ray at {angle}: {positions:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn across_paints_exactly_where_along_does() {
|
||||
for curvatures in curvature_pairs() {
|
||||
let standard = GradientStandard::new(curvatures[0], curvatures[1]);
|
||||
let chart = AcrossChart::new(curvatures[0], curvatures[1], GradientModel::Standard);
|
||||
|
||||
// A line end's cut and a nearly flat cone's split are drawn as straight lines across the gradient line, which the cone drawn at the flattest radius only nears
|
||||
let cut = match standard {
|
||||
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => keep.map(|keep| keep.at),
|
||||
GradientStandard::Profile { split, .. } => Some(split),
|
||||
_ => None,
|
||||
};
|
||||
for point in sample_points() {
|
||||
if cut.is_some_and(|cut| (point.x - cut).abs() < 0.1 * point.y.abs().max(0.1)) {
|
||||
continue;
|
||||
}
|
||||
assert_eq!(chart.v(point).is_some(), standard.t(point).is_some(), "Standard curvatures {curvatures:?} at {point}: {chart:?}");
|
||||
}
|
||||
|
||||
// Apollonian circles paint everywhere, read along or across them
|
||||
let chart = AcrossChart::new(curvatures[0], curvatures[1], GradientModel::Apollonian);
|
||||
assert!(chart.paints_everywhere(), "Apollonian curvatures {curvatures:?}: {chart:?}");
|
||||
assert!(sample_points().all(|point| chart.v(point).is_some()), "Apollonian curvatures {curvatures:?}: {chart:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positions_change_continuously_except_at_seams_and_where_contours_meet() {
|
||||
const STEP: f64 = 0.01;
|
||||
|
||||
for curvatures in curvature_pairs() {
|
||||
for model in [GradientModel::Standard, GradientModel::Apollonian] {
|
||||
let chart = AcrossChart::new(curvatures[0], curvatures[1], model);
|
||||
|
||||
// Where every contour of constant position meets, and a cut across the gradient line
|
||||
let mut singular_points = Vec::new();
|
||||
let mut cut = None;
|
||||
match chart {
|
||||
AcrossChart::Concentric { center } => singular_points.push(DVec2::new(center, 0.)),
|
||||
AcrossChart::Cone { cone, keep } => {
|
||||
let apex_t = -cone.start_radius / (cone.end_radius - cone.start_radius);
|
||||
singular_points.push(DVec2::new(cone.start_center + apex_t * (cone.end_center - cone.start_center), 0.));
|
||||
cut = keep.map(|keep| keep.at);
|
||||
}
|
||||
AcrossChart::Mobius { numerator, denominator } => {
|
||||
singular_points.push(DVec2::new(-numerator[1] / numerator[0], 0.));
|
||||
singular_points.push(DVec2::new(-denominator[1] / denominator[0], 0.));
|
||||
}
|
||||
AcrossChart::Bipolar { center_x, half_height, .. } => {
|
||||
singular_points.push(DVec2::new(center_x, half_height));
|
||||
singular_points.push(DVec2::new(center_x, -half_height));
|
||||
}
|
||||
AcrossChart::Linear | AcrossChart::Nothing => {}
|
||||
}
|
||||
let near_singular = |point: DVec2| singular_points.iter().any(|singular| (point - *singular).length() < 0.2) || cut.is_some_and(|cut| (point.x - cut).abs() < 0.02);
|
||||
|
||||
for point in sample_points().filter(|&point| !near_singular(point)) {
|
||||
for neighbor in [point + DVec2::new(STEP, 0.), point + DVec2::new(0., STEP)] {
|
||||
if near_singular(neighbor) {
|
||||
continue;
|
||||
}
|
||||
let (Some(v), Some(neighbor_v)) = (chart.v(point), chart.v(neighbor)) else { continue };
|
||||
|
||||
let change = if chart.winds() { turn_distance(v, neighbor_v) } else { (v - neighbor_v).abs() };
|
||||
assert!(change < 0.05, "{model:?} curvatures {curvatures:?} from {point} to {neighbor}: {v} to {neighbor_v} in {chart:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bipolar_chart_nears_the_linear_forms_as_crossing_curvatures_flatten() {
|
||||
// Over the view, the chart strays from `y` in proportion to the curvatures
|
||||
for curvature in [1e-3, 1e-4, 1e-6] {
|
||||
let tolerance = 300. * curvature;
|
||||
for [start, end] in [[curvature, curvature], [curvature, 2. * curvature], [3. * curvature, curvature]] {
|
||||
let chart = AcrossChart::new(start, end, GradientModel::Apollonian);
|
||||
assert!(matches!(chart, AcrossChart::Bipolar { .. }), "({start}, {end}) should cross, not {chart:?}");
|
||||
for point in sample_points() {
|
||||
let v = chart.v(point).unwrap();
|
||||
assert!((v - point.y).abs() < tolerance, "({start}, {end}) at {point}: {v}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Zero on the gradient line, and one unit per gradient length across its midpoint
|
||||
let chart = AcrossChart::new(0.6, 0.4, GradientModel::Apollonian);
|
||||
assert!(chart.v(DVec2::new(0.3, 0.)).unwrap().abs() < 1e-15);
|
||||
let rate = (chart.v(DVec2::new(0.5, 1e-6)).unwrap() - chart.v(DVec2::new(0.5, -1e-6)).unwrap()) / 2e-6;
|
||||
assert!((rate - 1.).abs() < 1e-6, "{rate}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apollonian_angles_run_around_the_limit_point_inside_the_end_contour() {
|
||||
// The start point inside the end circle, which encloses the start point as its limit point
|
||||
let start_point = AcrossChart::new(-1., 0.3, GradientModel::Apollonian);
|
||||
let AcrossChart::Mobius { numerator, .. } = start_point else { panic!("{start_point:?}") };
|
||||
assert!((-numerator[1] / numerator[0]).abs() < 1e-12, "{start_point:?}");
|
||||
|
||||
// The end a point, which is its own limit point
|
||||
let end_point = AcrossChart::new(0.8, 1., GradientModel::Apollonian);
|
||||
let AcrossChart::Mobius { numerator, .. } = end_point else { panic!("{end_point:?}") };
|
||||
assert!((-numerator[1] / numerator[0] - 1.).abs() < 1e-9, "{end_point:?}");
|
||||
|
||||
// Near the enclosed limit point, the position is the angle around it, from the seam on the +x side
|
||||
for angle in [0.1, 1., 2., 3., 4., 5., 6.] {
|
||||
let point = DVec2::from_angle(angle) * 1e-7;
|
||||
assert!(turn_distance(start_point.v(point).unwrap(), angle / TAU) < 1e-5, "at angle {angle}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_apollonian_chart_is_found_for_every_curvature_pair() {
|
||||
for start_step in -10..=10 {
|
||||
for end_step in -10..=10 {
|
||||
let (start, end) = (start_step as f64 / 10., end_step as f64 / 10.);
|
||||
let chart = AcrossChart::new(start, end, GradientModel::Apollonian);
|
||||
let along = GradientApollonian::new(start, end);
|
||||
for point in sample_points() {
|
||||
let v = chart.v(point);
|
||||
assert!(v.is_some_and(|v| !v.is_nan()), "({start}, {end}) at {point}: {v:?} in {chart:?}");
|
||||
assert!(!along.t(point).is_nan());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extreme_curvatures_compute_finitely() {
|
||||
let extremes = [4e-309, -4e-309, 1e-300, 6e-31, -6e-31, 7e-31, -7e-31, 1e-17, -1e-17];
|
||||
let curvatures = extremes.iter().flat_map(|&extreme| {
|
||||
[
|
||||
[extreme, 0.],
|
||||
[0., extreme],
|
||||
[extreme, 0.3],
|
||||
[-0.3, extreme],
|
||||
[extreme, extreme],
|
||||
[extreme, -extreme],
|
||||
[extreme, 1. - 1e-16],
|
||||
]
|
||||
});
|
||||
|
||||
for [start, end] in curvatures {
|
||||
for model in [GradientModel::Standard, GradientModel::Apollonian] {
|
||||
let chart = AcrossChart::new(start, end, model);
|
||||
for point in sample_points() {
|
||||
let v = chart.v(point);
|
||||
assert!(v.is_none_or(|v| !v.is_nan()), "{model:?} curvatures ({start}, {end}) at {point}: {chart:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,548 @@
|
||||
//! The Apollonian drawing of a gradient's curved end contours: the contours between them fill in as the family of circles the
|
||||
//! two end contours span, which never cross except where every one of them meets, and fill the whole plane.
|
||||
//!
|
||||
//! Everything here is in gradient space, laid out as in [`crate::gradient_standard`]. Each member of the family is spaced by where it
|
||||
//! crosses the gradient line, within the band between the end contours' crossings that lies nearest to the line's span from 0 to 1.
|
||||
//! Where the band is that span, a stop at 0.3 sits where the 0.3 contour crosses the line. This reproduces the linear and radial
|
||||
//! forms exactly, since their contours cross the line at a distance in proportion to their place along the ramp.
|
||||
|
||||
use crate::gradient_standard::{AxisRamp, Cone, GradientStandard, curvature_radius};
|
||||
use glam::DVec2;
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
|
||||
/// Stands in for a t of infinity, on the contours that cross the gradient line at infinity.
|
||||
const UNBOUNDED_T: f64 = 1e6;
|
||||
|
||||
/// A generalized circle `a(x² + y²) + bx + c = 0` with its center on the gradient line: a circle, a line where `a` is zero,
|
||||
/// or a point where it has zero radius.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct AxisCircle {
|
||||
pub a: f64,
|
||||
pub b: f64,
|
||||
pub c: f64,
|
||||
}
|
||||
|
||||
impl AxisCircle {
|
||||
/// The contour through the start point at the origin, curved by `alpha` toward the end point.
|
||||
pub fn start(alpha: f64) -> Self {
|
||||
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
|
||||
Self { a: sin, b: -2. * cos, c: 0. }
|
||||
}
|
||||
|
||||
/// The contour through the end point at (1, 0), curved by `alpha` toward the start point.
|
||||
pub fn end(alpha: f64) -> Self {
|
||||
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
|
||||
Self {
|
||||
a: sin,
|
||||
b: 2. * cos - 2. * sin,
|
||||
c: sin - 2. * cos,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn value(&self, point: DVec2) -> f64 {
|
||||
self.a * point.length_squared() + self.b * point.x + self.c
|
||||
}
|
||||
|
||||
/// The points where it crosses the gradient line, in homogeneous form.
|
||||
fn crossings(&self) -> [Homogeneous; 2] {
|
||||
solve_quadratic(self.a, self.b, self.c)
|
||||
}
|
||||
|
||||
/// The member of the family `self·weight + other·other_weight`.
|
||||
fn combine(&self, weight: f64, other: &Self, other_weight: f64) -> Self {
|
||||
Self {
|
||||
a: self.a * weight + other.a * other_weight,
|
||||
b: self.b * weight + other.b * other_weight,
|
||||
c: self.c * weight + other.c * other_weight,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A point on the gradient line in homogeneous form, `numerator / denominator`, so the point at infinity is just a zero denominator.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(crate) struct Homogeneous {
|
||||
pub(crate) numerator: f64,
|
||||
pub(crate) denominator: f64,
|
||||
}
|
||||
|
||||
impl Homogeneous {
|
||||
pub(crate) const INFINITY: Self = Self { numerator: 1., denominator: 0. };
|
||||
|
||||
pub(crate) fn value(&self) -> Option<f64> {
|
||||
(self.denominator != 0.).then(|| self.numerator / self.denominator)
|
||||
}
|
||||
|
||||
/// Scaled so the larger of its two parts has a magnitude of 1, keeping products of points in range.
|
||||
pub(crate) fn normalized(self) -> Self {
|
||||
let scale = self.numerator.abs().max(self.denominator.abs());
|
||||
if scale == 0. {
|
||||
return self;
|
||||
}
|
||||
Self {
|
||||
numerator: self.numerator / scale,
|
||||
denominator: self.denominator / scale,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the family of circles two end contours span is laid out.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(crate) enum CircleFamily {
|
||||
/// The end contours cross, so every member passes through the two points where the line member at `radical_x` meets them.
|
||||
Crossing { radical_x: f64 },
|
||||
/// The members nest around two limit points (normalized), which coincide where the end contours touch.
|
||||
Nesting { limit_points: [Homogeneous; 2] },
|
||||
}
|
||||
|
||||
impl CircleFamily {
|
||||
pub(crate) fn of(start: AxisCircle, end: AxisCircle) -> Self {
|
||||
// The members of the family that are points have a zero discriminant, which as a quadratic form in the two members'
|
||||
// weights has these coefficients. Its determinant says whether the family has two such points (it's hyperbolic), none
|
||||
// (elliptic, where the end contours cross), or one (parabolic, where they touch).
|
||||
let point_quadratic_start = start.b * start.b - 4. * start.a * start.c;
|
||||
let point_quadratic_cross = start.b * end.b - 2. * (start.a * end.c + end.a * start.c);
|
||||
let point_quadratic_end = end.b * end.b - 4. * end.a * end.c;
|
||||
let determinant = point_quadratic_start * point_quadratic_end - point_quadratic_cross * point_quadratic_cross;
|
||||
let scale = point_quadratic_start.abs().max(point_quadratic_end.abs()).max(point_quadratic_cross.abs()).max(f64::MIN_POSITIVE);
|
||||
|
||||
if determinant > 1e-12 * scale * scale {
|
||||
// The line through the two points where the end contours cross is the member with no curvature
|
||||
let line = start.combine(end.a, &end, -start.a);
|
||||
return Self::Crossing { radical_x: -line.c / line.b };
|
||||
}
|
||||
|
||||
// The limit points are where the point members sit, with a point member of no curvature being the point at infinity
|
||||
let limit_points = point_member_weights(point_quadratic_start, point_quadratic_cross, point_quadratic_end).map(|(start_weight, end_weight)| {
|
||||
let member = start.combine(start_weight, &end, end_weight);
|
||||
let magnitude = member.a.abs().max(member.b.abs()).max(member.c.abs());
|
||||
if member.a.abs() <= 1e-12 * magnitude {
|
||||
return Homogeneous::INFINITY;
|
||||
}
|
||||
|
||||
Homogeneous {
|
||||
numerator: -member.b,
|
||||
denominator: 2. * member.a,
|
||||
}
|
||||
.normalized()
|
||||
});
|
||||
|
||||
Self::Nesting { limit_points }
|
||||
}
|
||||
}
|
||||
|
||||
/// The roots of `a y² + b y + c = 0`, in homogeneous form so a vanishing `a` puts a root at infinity rather than dividing by zero.
|
||||
fn solve_quadratic(a: f64, b: f64, c: f64) -> [Homogeneous; 2] {
|
||||
let discriminant = (b * b - 4. * a * c).max(0.);
|
||||
let sign = if b >= 0. { 1. } else { -1. };
|
||||
let q = -0.5 * (b + sign * discriminant.sqrt());
|
||||
|
||||
[Homogeneous { numerator: q, denominator: a }.normalized(), Homogeneous { numerator: c, denominator: q }.normalized()]
|
||||
}
|
||||
|
||||
/// How the crossing of a pixel's contour is told apart from the other place the same circle crosses the gradient line.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum CrossingSelection {
|
||||
/// The end contours cross, so every member passes through the two points where they cross, and the gradient line is split by
|
||||
/// the line through those points at `radical_x`. Each side of a member circle is its own contour, crossing the gradient line
|
||||
/// on the same side of `radical_x` as the pixel.
|
||||
SameSideAs { radical_x: f64 },
|
||||
/// The end contours don't cross, so the members nest around two limit points that split the gradient line into two arcs, and
|
||||
/// every member crosses each arc once. The crossing on the arc holding the gradient's band is the one where
|
||||
/// `quadratic[0] y² + quadratic[1] y + quadratic[2]` (with `y` in homogeneous form) is smallest.
|
||||
OnArc { quadratic: [f64; 3] },
|
||||
}
|
||||
|
||||
/// Where the arc holding the band passes through infinity, the crossings beyond infinity on its other side.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Wrap {
|
||||
/// A point on the gradient line between the two limit points, which separates the arc's two sides of infinity.
|
||||
pub reference_x: f64,
|
||||
/// Which side of `reference_x` the band is on, `1` or `-1`.
|
||||
pub band_side: f64,
|
||||
/// The t of the crossings on the far side of infinity.
|
||||
pub t: f64,
|
||||
}
|
||||
|
||||
/// Everything needed to find the t of any pixel in an Apollonian gradient.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct GradientApollonian {
|
||||
pub start: AxisCircle,
|
||||
pub end: AxisCircle,
|
||||
pub selection: CrossingSelection,
|
||||
pub wrap: Option<Wrap>,
|
||||
/// The t of a crossing at `y` is `y * t_scale + t_offset`.
|
||||
pub t_scale: f64,
|
||||
pub t_offset: f64,
|
||||
/// What SVG draws in place of the Apollonian circles where no image the GPU renders of them can replace it.
|
||||
pub svg_stand_in: GradientStandard,
|
||||
}
|
||||
|
||||
impl GradientApollonian {
|
||||
/// The parameters of the gradient with these two curvatures, which must be finite and within -1 to 1.
|
||||
pub fn new(start_curvature: f64, end_curvature: f64) -> Self {
|
||||
let svg_stand_in = svg_stand_in(start_curvature, end_curvature);
|
||||
let start = AxisCircle::start(start_curvature);
|
||||
let end = AxisCircle::end(end_curvature);
|
||||
|
||||
let limit_points = match CircleFamily::of(start, end) {
|
||||
CircleFamily::Crossing { radical_x } => return Self::with_band(start, end, CrossingSelection::SameSideAs { radical_x }, None, 0., 1., svg_stand_in),
|
||||
CircleFamily::Nesting { limit_points } => limit_points,
|
||||
};
|
||||
|
||||
// Each crossing's place relative to the limit points, negative between them and positive beyond them
|
||||
let arc_quadratic = arc_quadratic(limit_points);
|
||||
let arc_of = |point: Homogeneous| evaluate_homogeneous_quadratic(arc_quadratic, point.normalized());
|
||||
|
||||
// Find each end contour's crossing on each arc, where a point contour (a limit point itself) lies on both
|
||||
let choose_on_arc = |crossings: [Homogeneous; 2], negative_arc: bool| {
|
||||
crossings
|
||||
.into_iter()
|
||||
.min_by(|a, b| {
|
||||
let (a, b) = (arc_of(*a), arc_of(*b));
|
||||
if negative_arc { a.total_cmp(&b) } else { b.total_cmp(&a) }
|
||||
})
|
||||
.unwrap_or(Homogeneous::INFINITY)
|
||||
};
|
||||
let candidates = [true, false].map(|negative_arc| {
|
||||
let band_start = choose_on_arc(start.crossings(), negative_arc);
|
||||
let band_end = choose_on_arc(end.crossings(), negative_arc);
|
||||
(negative_arc, band_start, band_end)
|
||||
});
|
||||
|
||||
// A band through infinity would give a contour within it an infinite t, so it's unusable. On the outer arc between finite limit
|
||||
// points, that's a band with its ends on opposite sides of their midpoint, which counts an end on a limit point as on its side.
|
||||
let limit_values = limit_points.map(|point| point.value());
|
||||
let usable = |negative_arc: bool, band_start: Homogeneous, band_end: Homogeneous| {
|
||||
let (Some(band_start), Some(band_end)) = (band_start.value(), band_end.value()) else {
|
||||
return false;
|
||||
};
|
||||
match limit_values {
|
||||
[Some(first), Some(second)] if !negative_arc => {
|
||||
let reference_x = (first + second) / 2.;
|
||||
(band_start > reference_x) == (band_end > reference_x)
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
|
||||
// Among the rest, prefer the band nearest to running from 0 to 1, measured continuously so the choice can't jump as a contour nears a point
|
||||
let distance_from_unit_band = |&(_, band_start, band_end): &(bool, Homogeneous, Homogeneous)| {
|
||||
band_start.value().map_or(f64::INFINITY, f64::abs) + band_end.value().map_or(f64::INFINITY, |band_end| (band_end - 1.).abs())
|
||||
};
|
||||
let chosen = candidates
|
||||
.into_iter()
|
||||
.filter(|&(negative_arc, band_start, band_end)| usable(negative_arc, band_start, band_end))
|
||||
.min_by(|a, b| distance_from_unit_band(a).total_cmp(&distance_from_unit_band(b)))
|
||||
.unwrap_or(candidates[1]);
|
||||
let (negative_arc, band_start, band_end) = chosen;
|
||||
|
||||
// Choosing the smallest value picks the crossing on the chosen arc
|
||||
let sign = if negative_arc { 1. } else { -1. };
|
||||
let selection = CrossingSelection::OnArc {
|
||||
quadratic: arc_quadratic.map(|coefficient| coefficient * sign),
|
||||
};
|
||||
|
||||
let band_start = band_start.value().unwrap_or(0.);
|
||||
let band_end = band_end.value().unwrap_or(1.);
|
||||
|
||||
// An outer arc between two finite limit points passes through infinity, beyond which its crossings belong past the band's far end
|
||||
let wrap = match (negative_arc, limit_values) {
|
||||
(false, [Some(first), Some(second)]) if (first - second).abs() > 0. => {
|
||||
let reference_x = (first + second) / 2.;
|
||||
let band_side = if band_start > reference_x { 1. } else { -1. };
|
||||
let t_direction = (band_end - band_start).signum();
|
||||
Some(Wrap {
|
||||
reference_x,
|
||||
band_side,
|
||||
t: band_side * t_direction * UNBOUNDED_T,
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
Self::with_band(start, end, selection, wrap, band_start, band_end, svg_stand_in)
|
||||
}
|
||||
|
||||
fn with_band(start: AxisCircle, end: AxisCircle, selection: CrossingSelection, wrap: Option<Wrap>, band_start: f64, band_end: f64, svg_stand_in: GradientStandard) -> Self {
|
||||
let width = band_end - band_start;
|
||||
let width = if width.abs() < 1e-12 { 1e-12_f64.copysign(width) } else { width };
|
||||
|
||||
Self {
|
||||
start,
|
||||
end,
|
||||
selection,
|
||||
wrap,
|
||||
t_scale: 1. / width,
|
||||
t_offset: -band_start / width,
|
||||
svg_stand_in,
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient's t at `point` in gradient space, by the same steps the renderer's shader takes.
|
||||
pub fn t(&self, point: DVec2) -> f64 {
|
||||
let start_value = self.start.value(point);
|
||||
let end_value = self.end.value(point);
|
||||
let scale = start_value.abs().max(end_value.abs());
|
||||
if scale == 0. {
|
||||
return 0.;
|
||||
}
|
||||
let (start_value, end_value) = (start_value / scale, end_value / scale);
|
||||
|
||||
// The pixel's contour is the member where the end contours' values keep this ratio, which crosses the gradient line at the
|
||||
// roots of this quadratic
|
||||
let a = end_value * self.start.a - start_value * self.end.a;
|
||||
let b = end_value * self.start.b - start_value * self.end.b;
|
||||
let c = end_value * self.start.c - start_value * self.end.c;
|
||||
let roots = solve_quadratic(a, b, c);
|
||||
|
||||
let crossing = match self.selection {
|
||||
CrossingSelection::SameSideAs { radical_x } => {
|
||||
// A pixel on the dividing line itself is on the line member, which crosses at the finite root
|
||||
let side = |root: Homogeneous| (root.numerator - radical_x * root.denominator) * root.denominator * (point.x - radical_x);
|
||||
let (first, second) = (side(roots[0]), side(roots[1]));
|
||||
let first_wins = if first == second {
|
||||
roots[0].denominator.abs() >= roots[1].denominator.abs()
|
||||
} else {
|
||||
first > second
|
||||
};
|
||||
if first_wins { roots[0] } else { roots[1] }
|
||||
}
|
||||
CrossingSelection::OnArc { quadratic } => {
|
||||
if evaluate_homogeneous_quadratic(quadratic, roots[0]) <= evaluate_homogeneous_quadratic(quadratic, roots[1]) {
|
||||
roots[0]
|
||||
} else {
|
||||
roots[1]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(wrap) = self.wrap
|
||||
&& (crossing.numerator - wrap.reference_x * crossing.denominator) * crossing.denominator * wrap.band_side < 0.
|
||||
{
|
||||
return wrap.t;
|
||||
}
|
||||
|
||||
if crossing.denominator == 0. {
|
||||
let direction = crossing.numerator * self.t_scale;
|
||||
return if direction == 0. { 0. } else { direction.signum() * UNBOUNDED_T };
|
||||
}
|
||||
crossing.numerator / crossing.denominator * self.t_scale + self.t_offset
|
||||
}
|
||||
}
|
||||
|
||||
/// SVG 2's own drawing of these curvatures where the end circles nest so it paints the whole plane, which is exact when they're concentric, or else the plain ramp.
|
||||
fn svg_stand_in(start_curvature: f64, end_curvature: f64) -> GradientStandard {
|
||||
let drawn = GradientStandard::new(start_curvature, end_curvature);
|
||||
let (start_radius, end_radius) = (curvature_radius(start_curvature), curvature_radius(end_curvature));
|
||||
let nested = if start_radius.is_finite() && end_radius.is_finite() {
|
||||
Cone::between(start_radius, end_radius).is_nested()
|
||||
} else {
|
||||
drawn.paints_everywhere()
|
||||
};
|
||||
|
||||
if nested { drawn } else { GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None } }
|
||||
}
|
||||
|
||||
/// The weights of the two members that are points, the roots of the homogeneous quadratic form `start s² + 2·cross·s·e + end e²`.
|
||||
fn point_member_weights(start: f64, cross: f64, end: f64) -> [(f64, f64); 2] {
|
||||
let discriminant = (cross * cross - start * end).max(0.).sqrt();
|
||||
|
||||
if start.abs() < 1e-12 && end.abs() < 1e-12 {
|
||||
// Both end contours are points already
|
||||
[(1., 0.), (0., 1.)]
|
||||
} else if start.abs() >= end.abs() {
|
||||
[((-cross + discriminant) / start, 1.), ((-cross - discriminant) / start, 1.)]
|
||||
} else {
|
||||
[(1., (-cross + discriminant) / end), (1., (-cross - discriminant) / end)]
|
||||
}
|
||||
}
|
||||
|
||||
/// The quadratic in a homogeneous point that is negative between the two limit points and positive beyond them.
|
||||
fn arc_quadratic([first, second]: [Homogeneous; 2]) -> [f64; 3] {
|
||||
// (y·d₁ - n₁)(y·d₂ - n₂) with the denominators kept nonnegative, so its sign doesn't depend on how each point is scaled
|
||||
let orient = |point: Homogeneous| {
|
||||
if point.denominator < 0. {
|
||||
Homogeneous {
|
||||
numerator: -point.numerator,
|
||||
denominator: -point.denominator,
|
||||
}
|
||||
} else {
|
||||
point
|
||||
}
|
||||
};
|
||||
let (first, second) = (orient(first), orient(second));
|
||||
|
||||
[
|
||||
first.denominator * second.denominator,
|
||||
-(first.denominator * second.numerator + first.numerator * second.denominator),
|
||||
first.numerator * second.numerator,
|
||||
]
|
||||
}
|
||||
|
||||
fn evaluate_homogeneous_quadratic([a, b, c]: [f64; 3], point: Homogeneous) -> f64 {
|
||||
let Homogeneous { numerator, denominator } = point;
|
||||
a * numerator * numerator + b * numerator * denominator + c * denominator * denominator
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::gradient::{LINEAR_CURVATURES, RADIAL_CURVATURES};
|
||||
use crate::gradient_standard::{GradientStandard, radius_curvature};
|
||||
|
||||
fn assert_close(actual: f64, expected: f64, context: &str) {
|
||||
assert!((actual - expected).abs() < 1e-6, "{context}: expected {expected}, got {actual}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_curvatures_space_contours_by_radius() {
|
||||
let parameters = GradientApollonian::new(RADIAL_CURVATURES[0], RADIAL_CURVATURES[1]);
|
||||
for radius in [0.1, 0.3, 0.75, 1., 1.5, 4.] {
|
||||
for angle in [0., 0.7, 2., 3.1, 4.5] {
|
||||
let point = DVec2::from_angle(angle) * radius;
|
||||
assert_close(parameters.t(point), radius, &format!("radius {radius} at angle {angle}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_curvatures_space_contours_by_distance_along_the_line() {
|
||||
let parameters = GradientApollonian::new(LINEAR_CURVATURES[0], LINEAR_CURVATURES[1]);
|
||||
for point in [DVec2::new(0.25, 0.), DVec2::new(0.6, 3.), DVec2::new(-2., -7.), DVec2::new(5., 0.5)] {
|
||||
assert_close(parameters.t(point), point.x, &format!("point {point}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concentric_curvatures_draw_what_svg_2_draws() {
|
||||
// End circles sharing a center, where the start circle is centered at `k` and the end circle at `1 - k`, so they're concentric when the end's `k` is 1 minus the start's
|
||||
for start_radius in [-1., -0.5, 0.25, 2., 3.] {
|
||||
let curvatures = [radius_curvature(start_radius), radius_curvature(1. - start_radius)];
|
||||
let (apollonian, cone) = (GradientApollonian::new(curvatures[0], curvatures[1]), GradientStandard::new(curvatures[0], curvatures[1]));
|
||||
|
||||
for x in -30..=40 {
|
||||
for y in -25..=25 {
|
||||
let point = DVec2::new(x as f64 * 0.1 + 0.0013, y as f64 * 0.1 + 0.0007);
|
||||
let Some(expected) = cone.t(point) else {
|
||||
panic!("concentric circles with start radius {start_radius} leave {point} unpainted");
|
||||
};
|
||||
assert!((apollonian.t(point) - expected).abs() < 1e-6 * expected.abs().max(1.), "start radius {start_radius} at {point}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_curvatures_space_contours_by_distance_ratio() {
|
||||
let parameters = GradientApollonian::new(1., 1.);
|
||||
for point in [DVec2::new(0.5, 0.), DVec2::new(0.5, 2.), DVec2::new(0.2, 0.3), DVec2::new(3., -1.)] {
|
||||
// The contours are the circles of Apollonius, each crossing the line between the points at y / (1 - y) = ratio
|
||||
let ratio = point.length() / (point - DVec2::X).length();
|
||||
assert_close(parameters.t(point), ratio / (1. + ratio), &format!("point {point}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curvatures_near_a_preset_render_like_it() {
|
||||
let radial = GradientApollonian::new(RADIAL_CURVATURES[0], RADIAL_CURVATURES[1]);
|
||||
let near_radial = GradientApollonian::new(RADIAL_CURVATURES[0] + 1e-7, RADIAL_CURVATURES[1] + 1e-7);
|
||||
let linear = GradientApollonian::new(LINEAR_CURVATURES[0], LINEAR_CURVATURES[1]);
|
||||
let near_linear = GradientApollonian::new(LINEAR_CURVATURES[0] + 1e-7, LINEAR_CURVATURES[1] - 1e-7);
|
||||
|
||||
for point in [DVec2::new(0.3, 0.2), DVec2::new(-0.5, 0.4), DVec2::new(0.9, -0.1)] {
|
||||
assert!((radial.t(point) - near_radial.t(point)).abs() < 1e-4, "near radial at {point}");
|
||||
assert!((linear.t(point) - near_linear.t(point)).abs() < 1e-4, "near linear at {point}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focal_gradient_pads_everywhere_outside_its_end_circle() {
|
||||
// The start point sits inside the end circle, off its center
|
||||
let parameters = GradientApollonian::new(1., 0.6);
|
||||
|
||||
assert_close(parameters.t(DVec2::X), 1., "end point");
|
||||
let inside = parameters.t(DVec2::new(0.5, 0.));
|
||||
assert!(inside > 0. && inside < 1., "inside: {inside}");
|
||||
for point in [DVec2::new(-5., 0.), DVec2::new(-0.5, 0.), DVec2::new(5., 0.), DVec2::new(0.3, 4.), DVec2::new(-40., 30.)] {
|
||||
let t = parameters.t(point);
|
||||
assert!(t > 1., "outside at {point}: {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_contours_fan_through_their_lens() {
|
||||
let parameters = GradientApollonian::new(0.6, 0.6);
|
||||
assert!(matches!(parameters.selection, CrossingSelection::SameSideAs { .. }));
|
||||
|
||||
for x in [0., 0.1, 0.25, 0.5, 0.8, 1.] {
|
||||
assert_close(parameters.t(DVec2::new(x, 0.)), x, &format!("on the line at {x}"));
|
||||
}
|
||||
// Mirrored across the gradient line
|
||||
assert_close(parameters.t(DVec2::new(0.3, 0.2)), parameters.t(DVec2::new(0.3, -0.2)), "mirror");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_curvature_pair_gives_a_number_everywhere() {
|
||||
for start_step in -10..=10 {
|
||||
for end_step in -10..=10 {
|
||||
let parameters = GradientApollonian::new(start_step as f64 / 10., end_step as f64 / 10.);
|
||||
for x in -8..=8 {
|
||||
for y in -8..=8 {
|
||||
let point = DVec2::new(x as f64 * 0.37, y as f64 * 0.41);
|
||||
let t = parameters.t(point);
|
||||
assert!(!t.is_nan(), "curvatures ({start_step}, {end_step}) at {point}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_curvature_pair_puts_the_start_point_at_0_and_the_end_point_at_1() {
|
||||
for start_step in -100..=100 {
|
||||
for end_step in -100..=100 {
|
||||
let (start_curvature, end_curvature) = (start_step as f64 / 100., end_step as f64 / 100.);
|
||||
let parameters = GradientApollonian::new(start_curvature, end_curvature);
|
||||
|
||||
assert_close(parameters.t(DVec2::ZERO), 0., &format!("start point with curvatures ({start_curvature}, {end_curvature})"));
|
||||
assert_close(parameters.t(DVec2::X), 1., &format!("end point with curvatures ({start_curvature}, {end_curvature})"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curvatures_reaching_a_line_or_a_point_change_the_gradient_continuously() {
|
||||
let nudge = 1e-6;
|
||||
for (curvatures, nearby_curvatures) in [
|
||||
// The start crossing the line, with the end a small circle
|
||||
([nudge, 0.8], [-nudge, 0.8]),
|
||||
// The end crossing the line, with the start a small circle
|
||||
([0.8, nudge], [0.8, -nudge]),
|
||||
// The start shrinking to a point inside the end circle, on either side of its center
|
||||
([1., 0.2], [1. - nudge, 0.2]),
|
||||
([1., 0.6], [1. - nudge, 0.6]),
|
||||
// The end shrinking to a point outside the start circle
|
||||
([0.8, 1.], [0.8, 1. - nudge]),
|
||||
([0.8, -1.], [0.8, -1. + nudge]),
|
||||
// The start's point from either side of the curvature's wrap seam
|
||||
([1. - nudge, 0.2], [-1. + nudge, 0.2]),
|
||||
] {
|
||||
let (parameters, nearby_parameters) = (
|
||||
GradientApollonian::new(curvatures[0], curvatures[1]),
|
||||
GradientApollonian::new(nearby_curvatures[0], nearby_curvatures[1]),
|
||||
);
|
||||
for x in -6..=10 {
|
||||
for y in -8..=8 {
|
||||
let point = DVec2::new(x as f64 * 0.25 + 0.013, y as f64 * 0.25 + 0.007);
|
||||
|
||||
// Clamped as the padded ramp draws it
|
||||
let (t, nearby_t) = (parameters.t(point).clamp(0., 1.), nearby_parameters.t(point).clamp(0., 1.));
|
||||
assert!(
|
||||
(t - nearby_t).abs() < 1e-3,
|
||||
"curvatures {curvatures:?} against {nearby_curvatures:?} at {point}: {t} against {nearby_t}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,845 @@
|
||||
//! Gradients with each of their two ends a contour curved between a line, a circle, and a point, drawn as SVG 2's focal radial
|
||||
//! gradient (the two-point cone) between the two end circles, and extended to the settings SVG 2 can't express.
|
||||
//!
|
||||
//! Everything here is in gradient space, where the gradient line runs from the start point at the origin to the end point
|
||||
//! at (1, 0). Each end's contour passes through its endpoint with its center on the line, and is described by its curvature
|
||||
//! `α ∈ [-1, 1]`, which sets its signed radius `k = cot(απ/2)` in gradient lengths: 0 is the line perpendicular to the
|
||||
//! gradient line, ±1 is the endpoint itself, and in between is a circle bowing toward (positive) or away from (negative) the
|
||||
//! other endpoint. The start circle is centered at `(k₀, 0)` and the end circle at `(1 - k₁, 0)`.
|
||||
//!
|
||||
//! Where SVG 2 leaves the plane unpainted, so does it. A line end takes SVG 2's own limit as that end's circle flattens bowing
|
||||
//! toward the other end. The Apollonian drawing of the same curvatures is in [`crate::gradient_apollonian`].
|
||||
|
||||
use crate::gradient::{GradientDirection, GradientForm, GradientModel, wrapped_curvature};
|
||||
use crate::gradient_across::{AcrossChart, GradientAcross};
|
||||
use crate::gradient_apollonian::GradientApollonian;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
|
||||
/// Past this radius, in gradient lengths, the cone is drawn as its own profile along the gradient line, carried straight across it.
|
||||
/// Renderers draw a cone this flat wrongly in single precision (Chromium already does at 10,000), while its circles sag from straight by
|
||||
/// only about `y² / 2r`, within about 0.002 of the profile.
|
||||
pub const NEAR_LINE_RADIUS: f64 = 2000.;
|
||||
|
||||
/// The flattest an end contour other than a line is drawn, as a radius in gradient lengths, which keeps every position renderers receive within single precision's range.
|
||||
/// A curvature nearer 0 than this radius allows is drawn this flat on its own side, so only a curvature of exactly 0 is a line.
|
||||
const FLATTEST_RADIUS: f64 = 1e30;
|
||||
|
||||
/// The narrowest a ramp along the gradient line is drawn, in gradient lengths, below which it's a step from its first to its last stop.
|
||||
/// Vello draws a gradient with ends closer than 10⁻⁶ as its first stop's color.
|
||||
const NARROWEST_RAMP: f64 = 1e-5;
|
||||
|
||||
/// The signed radius of an end contour in gradient lengths for its `curvature`: infinite for a line, 0 for a point, and otherwise at most 10³⁰ in size.
|
||||
pub fn curvature_radius(curvature: f64) -> f64 {
|
||||
if curvature == 0. {
|
||||
return f64::INFINITY;
|
||||
}
|
||||
if curvature.abs() == 1. {
|
||||
return 0.;
|
||||
}
|
||||
|
||||
let (sin, cos) = (curvature * FRAC_PI_2).sin_cos();
|
||||
(cos / sin).clamp(-FLATTEST_RADIUS, FLATTEST_RADIUS)
|
||||
}
|
||||
|
||||
/// The curvature of an end contour with this signed radius in gradient lengths, the inverse of [`curvature_radius`] (giving -1 for a point).
|
||||
pub fn radius_curvature(radius: f64) -> f64 {
|
||||
if radius == 0. { -1. } else { radius.recip().atan() / FRAC_PI_2 }
|
||||
}
|
||||
|
||||
/// SVG 2's two-point conical gradient: circle `t` has its center and radius interpolated between the start and end circles,
|
||||
/// both centered on the gradient line, for every real `t`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Cone {
|
||||
pub start_center: f64,
|
||||
pub start_radius: f64,
|
||||
pub end_center: f64,
|
||||
pub end_radius: f64,
|
||||
}
|
||||
|
||||
impl Cone {
|
||||
/// The largest `t` whose circle passes through `point` with a radius of at least 0, or `None` where SVG 2 leaves it unpainted.
|
||||
pub fn t(&self, point: DVec2) -> Option<f64> {
|
||||
let (delta_center, delta_radius) = (self.end_center - self.start_center, self.end_radius - self.start_radius);
|
||||
let scale = delta_center * delta_center + delta_radius * delta_radius;
|
||||
|
||||
// The circles through `point` are the roots of `a t² - 2 b t + c`
|
||||
let offset = point.x - self.start_center;
|
||||
let a = delta_center * delta_center - delta_radius * delta_radius;
|
||||
let b = offset * delta_center + self.start_radius * delta_radius;
|
||||
let c = offset * offset + point.y * point.y - self.start_radius * self.start_radius;
|
||||
|
||||
let valid = |t: f64| (self.start_radius + t * delta_radius >= 0.).then_some(t);
|
||||
let largest = |first: Option<f64>, second: Option<f64>| match (first, second) {
|
||||
(Some(first), Some(second)) => Some(first.max(second)),
|
||||
(first, second) => first.or(second),
|
||||
};
|
||||
|
||||
// Internally tangent circles leave one finite root
|
||||
if a.abs() < 1e-12 * scale {
|
||||
return (b != 0.).then(|| c / (2. * b)).and_then(valid);
|
||||
}
|
||||
|
||||
// Nested circles pass one circle through every point, which rounding mustn't lose where its two roots meet
|
||||
let discriminant = b * b - a * c;
|
||||
let discriminant = if a < 0. { discriminant.max(0.) } else { discriminant };
|
||||
if discriminant < 0. {
|
||||
return None;
|
||||
}
|
||||
|
||||
// The roots `q / a` and `c / q`, found without the cancellation of subtracting nearly equal terms
|
||||
let q = b + discriminant.sqrt().copysign(if b >= 0. { 1. } else { -1. });
|
||||
let near_root = (q != 0.).then(|| c / q).and_then(valid);
|
||||
largest(valid(q / a), near_root)
|
||||
}
|
||||
|
||||
/// The cone between the end circles with these signed radii.
|
||||
pub fn between(start: f64, end: f64) -> Self {
|
||||
Self {
|
||||
start_center: start,
|
||||
start_radius: start.abs(),
|
||||
end_center: 1. - end,
|
||||
end_radius: end.abs(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether its end circles are too close to tell apart, as renderers can't.
|
||||
pub fn is_identical(&self) -> bool {
|
||||
(self.end_center - self.start_center).abs() < 1e-6 && (self.end_radius - self.start_radius).abs() < 1e-6
|
||||
}
|
||||
|
||||
/// Whether every point lies on a circle of the cone, which happens where one end circle lies within the other without touching it.
|
||||
pub fn is_nested(&self) -> bool {
|
||||
let (delta_center, delta_radius) = (self.end_center - self.start_center, self.end_radius - self.start_radius);
|
||||
let a = delta_center * delta_center - delta_radius * delta_radius;
|
||||
a < -1e-12 * (delta_center * delta_center + delta_radius * delta_radius)
|
||||
}
|
||||
}
|
||||
|
||||
/// A ramp along the gradient line, from `t = 0` where it crosses `x = start` to `t = 1` where it crosses `x = end`.
|
||||
/// Each end is kept as exactly as it was found, and `width` (from `start` to `end`) without the cancellation of subtracting distant ends.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct AxisRamp {
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
pub width: f64,
|
||||
}
|
||||
|
||||
impl AxisRamp {
|
||||
pub const PLAIN: Self = Self { start: 0., end: 1., width: 1. };
|
||||
|
||||
pub fn new(start: f64, end: f64) -> Self {
|
||||
Self { start, end, width: end - start }
|
||||
}
|
||||
|
||||
/// Whether it's too narrow to draw as a ramp, so it's drawn as a step from its first stop's color to its last stop's at `start`.
|
||||
pub fn is_step(&self) -> bool {
|
||||
self.width.abs() < NARROWEST_RAMP
|
||||
}
|
||||
|
||||
/// Its end nearer the gradient's start, as `(x, t)`, which keeps positions measured from it precise near the start.
|
||||
pub fn anchor(&self) -> (f64, f64) {
|
||||
if self.end.abs() < self.start.abs() { (self.end, 1.) } else { (self.start, 0.) }
|
||||
}
|
||||
|
||||
/// The position along the ramp at `x`, or a step's first or last end's [`RampEnd::t`].
|
||||
pub fn t(&self, x: f64) -> f64 {
|
||||
if self.is_step() {
|
||||
let after = (x - self.start) * self.width >= 0.;
|
||||
return if after { RampEnd::Last.t() } else { RampEnd::First.t() };
|
||||
}
|
||||
|
||||
let (anchor, anchor_t) = self.anchor();
|
||||
anchor_t + (x - anchor) / self.width
|
||||
}
|
||||
}
|
||||
|
||||
/// The side of the line `x = at` across the gradient line that a paint is kept to, leaving the other side unpainted.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct HalfPlane {
|
||||
pub at: f64,
|
||||
/// Whether it keeps the side before `at` along the gradient line, rather than the side after.
|
||||
pub keeps_before: bool,
|
||||
}
|
||||
|
||||
impl HalfPlane {
|
||||
pub fn keeps(&self, x: f64) -> bool {
|
||||
if self.keeps_before { x < self.at } else { x > self.at }
|
||||
}
|
||||
}
|
||||
|
||||
/// One of a ramp's two end stops.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RampEnd {
|
||||
First,
|
||||
Last,
|
||||
}
|
||||
|
||||
impl RampEnd {
|
||||
/// The position along the ramp, past every end and repeat, that a padded ramp shows this end's color at.
|
||||
pub fn t(self) -> f64 {
|
||||
match self {
|
||||
Self::First => f64::NEG_INFINITY,
|
||||
Self::Last => f64::INFINITY,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a gradient with curved end contours is drawn, in gradient space.
|
||||
// TODO: Under the Repeat and Reflect spreads, SVG 2's limits at a line end are `max(x, 0)` at an end line and `min(x / ℓ₁, 1)` at a start line, which are drawn
|
||||
// as under the Pad spread instead, then repeated or reflected. Likewise, every Apollonian circle past the family's infinity takes the phase of the finite position standing in for it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum GradientStandard {
|
||||
/// SVG 2's cone.
|
||||
Cone(Cone),
|
||||
/// A ramp along the gradient line, kept to `keep` if given.
|
||||
Ramp { ramp: AxisRamp, keep: Option<HalfPlane> },
|
||||
/// An end stop's color, kept to `keep` if given.
|
||||
Solid { end: RampEnd, keep: Option<HalfPlane> },
|
||||
/// A nearly flat cone's profile along the gradient line, carried straight across it: a ramp before the line across it at `split` and another after.
|
||||
Profile { split: f64, before: AxisRamp, after: AxisRamp },
|
||||
/// Identical end circles, which SVG 2 leaves unpainted.
|
||||
Nothing,
|
||||
}
|
||||
|
||||
impl GradientStandard {
|
||||
/// How a gradient with these two curvatures is drawn.
|
||||
pub fn new(start_curvature: f64, end_curvature: f64) -> Self {
|
||||
let (start, end) = (curvature_radius(start_curvature), curvature_radius(end_curvature));
|
||||
|
||||
match (start.is_infinite(), end.is_infinite()) {
|
||||
(true, true) => Self::Ramp { ramp: AxisRamp::PLAIN, keep: None },
|
||||
(false, true) => Self::end_line(start, true),
|
||||
(true, false) => Self::start_line(end, true),
|
||||
_ if start.abs().max(end.abs()) > NEAR_LINE_RADIUS => Self::profile(start, end),
|
||||
_ => Self::cone(start, end),
|
||||
}
|
||||
}
|
||||
|
||||
/// SVG 2's cone between the start and end circles with these signed radii.
|
||||
fn cone(start: f64, end: f64) -> Self {
|
||||
// SVG 2 paints nothing between identical circles
|
||||
let cone = Cone::between(start, end);
|
||||
if cone.is_identical() { Self::Nothing } else { Self::Cone(cone) }
|
||||
}
|
||||
|
||||
/// SVG 2's cone between nearly flat end circles with these signed radii, as its profile along the gradient line carried straight across it.
|
||||
/// On the line, circle `t` passes through `x` where either edge of its diameter does, each edge moving in proportion to `t`. So each side
|
||||
/// of the apex, where the circles shrink to a point, takes one ramp: the larger of the edges' `t` for circles of a radius of at least 0.
|
||||
fn profile(start: f64, end: f64) -> Self {
|
||||
// Each edge of the circles' diameters along the gradient line runs from `2s` on the start circle to `1 - 2e` on the end circle, each
|
||||
// either an end's radius or 0, and moves by `1 - 2(s + e)`, summed first so distant edges don't lose the 1 to rounding
|
||||
let edge = |start_radius: f64, end_radius: f64| AxisRamp {
|
||||
start: 2. * start_radius,
|
||||
end: 1. - 2. * end_radius,
|
||||
width: 1. - 2. * (start_radius + end_radius),
|
||||
};
|
||||
let left = edge(start.min(0.), end.max(0.));
|
||||
let right = edge(start.max(0.), end.min(0.));
|
||||
let (start_left, start_right, delta_left) = (left.start, right.start, left.width);
|
||||
let growth = 2. * (end.abs() - start.abs());
|
||||
|
||||
// An edge that moves, with its direction, whose `t` is the cone's on the side of the apex where its circles have a radius of at least 0
|
||||
let edges = [left, right].into_iter().filter(|edge| edge.width != 0.).map(|edge| (edge, edge.width));
|
||||
|
||||
// With equal radii there's no apex, and the edge leading in `t` leads everywhere
|
||||
if growth == 0. {
|
||||
let leading = edges.max_by(|(a, _), (b, _)| a.t(0.).total_cmp(&b.t(0.))).map(|(ramp, _)| ramp);
|
||||
return Self::sides(0., leading, leading);
|
||||
}
|
||||
|
||||
// After the apex, the valid edges are those moving the way the diameter grows, and the steeper in `t` leads, while before it the reverse holds
|
||||
let side = |after: bool| {
|
||||
let valid = edges.clone().filter(|&(_, delta)| ((delta > 0.) == (growth > 0.)) == after);
|
||||
let leading = valid.max_by(|(_, a), (_, b)| {
|
||||
let steeper = a.recip().total_cmp(&b.recip());
|
||||
if after { steeper } else { steeper.reverse() }
|
||||
});
|
||||
leading.map(|(ramp, _)| ramp)
|
||||
};
|
||||
|
||||
// The apex lies where the diameter shrinks to 0
|
||||
let apex_t = -(start_right - start_left) / growth;
|
||||
let apex = start_left + apex_t * delta_left;
|
||||
if !apex.is_finite() || apex.abs() > FLATTEST_RADIUS {
|
||||
let ramp = side(apex < 0.);
|
||||
return Self::sides(0., ramp, ramp);
|
||||
}
|
||||
|
||||
Self::sides(apex, side(false), side(true))
|
||||
}
|
||||
|
||||
/// The ramp `before` the line across the gradient line at `split` and the one `after`, each unpainted where `None`.
|
||||
fn sides(split: f64, before: Option<AxisRamp>, after: Option<AxisRamp>) -> Self {
|
||||
let keep = |keeps_before| Some(HalfPlane { at: split, keeps_before });
|
||||
match (before, after) {
|
||||
(Some(before), Some(after)) if before == after => Self::Ramp { ramp: before, keep: None },
|
||||
(Some(before), Some(after)) => Self::Profile { split, before, after },
|
||||
(Some(ramp), None) => Self::Ramp { ramp, keep: keep(true) },
|
||||
(None, Some(ramp)) => Self::Ramp { ramp, keep: keep(false) },
|
||||
(None, None) => Self::Nothing,
|
||||
}
|
||||
}
|
||||
|
||||
/// SVG 2's limit as the end contour flattens into a line, bowing `inward` toward the start or away from it, beside the start circle of signed radius `start`.
|
||||
fn end_line(start: f64, inward: bool) -> Self {
|
||||
// The start circle's crossing of the gradient line that the flattening end circles meet
|
||||
let crossing = if inward { (2. * start).max(0.) } else { (2. * start).min(0.) };
|
||||
if (crossing - 1.).abs() < 1e-9 {
|
||||
return Self::Solid {
|
||||
end: RampEnd::First,
|
||||
keep: Some(HalfPlane { at: 1., keeps_before: true }),
|
||||
};
|
||||
}
|
||||
|
||||
// Unpainted past the crossing, except where it falls before the end point bowing inward
|
||||
Self::Ramp {
|
||||
ramp: AxisRamp::new(crossing, 1.),
|
||||
keep: (!inward || crossing > 1.).then_some(HalfPlane { at: crossing, keeps_before: inward }),
|
||||
}
|
||||
}
|
||||
|
||||
/// SVG 2's limit as the start contour flattens into a line, bowing `inward` toward the end or away from it, beside the end circle of signed radius `end`.
|
||||
fn start_line(end: f64, inward: bool) -> Self {
|
||||
// Bowing inward, the flattening start circles meet the end circle's backward crossing, or else its forward one
|
||||
let crossing = if inward { (1. - 2. * end).min(1.) } else { (1. - 2. * end).max(1.) };
|
||||
if inward && crossing > 0. {
|
||||
return Self::Ramp {
|
||||
ramp: AxisRamp::new(0., crossing),
|
||||
keep: None,
|
||||
};
|
||||
}
|
||||
|
||||
// The last stop's color fills the side of the crossing that SVG 2 paints
|
||||
Self::Solid {
|
||||
end: RampEnd::Last,
|
||||
keep: Some(HalfPlane { at: crossing, keeps_before: !inward }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether it draws as a paint masked to one side of a line: a paint kept to that side, or a profile's two sides.
|
||||
pub fn is_masked(&self) -> bool {
|
||||
matches!(self, Self::Ramp { keep: Some(_), .. } | Self::Solid { keep: Some(_), .. } | Self::Profile { .. })
|
||||
}
|
||||
|
||||
/// Whether it paints every point, rather than leaving some unpainted.
|
||||
pub fn paints_everywhere(&self) -> bool {
|
||||
match self {
|
||||
Self::Cone(cone) => cone.is_nested(),
|
||||
Self::Ramp { keep, .. } | Self::Solid { keep, .. } => keep.is_none(),
|
||||
Self::Profile { .. } => true,
|
||||
Self::Nothing => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The position along the ramp at `point`, or `None` where it's unpainted. An end stop's solid color is that end's [`RampEnd::t`].
|
||||
pub fn t(&self, point: DVec2) -> Option<f64> {
|
||||
let kept = |keep: &Option<HalfPlane>| keep.is_none_or(|keep| keep.keeps(point.x));
|
||||
|
||||
match self {
|
||||
Self::Cone(cone) => cone.t(point),
|
||||
Self::Ramp { ramp, keep } => kept(keep).then(|| ramp.t(point.x)),
|
||||
Self::Solid { end, keep } => kept(keep).then(|| end.t()),
|
||||
Self::Profile { split, before, after } => Some(if point.x < *split { before.t(point.x) } else { after.t(point.x) }),
|
||||
Self::Nothing => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a gradient's contours are laid out, decided by its curvatures and model, and how its colors run, decided by its direction.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum GradientShape {
|
||||
/// The linear form: both ends are lines.
|
||||
Linear,
|
||||
/// The radial form: the start is a point at the center of the end circle.
|
||||
Radial,
|
||||
/// Any other curvatures, drawn as SVG 2 draws them.
|
||||
Standard(GradientStandard),
|
||||
/// Any other curvatures, drawn as Apollonian circles.
|
||||
Apollonian(GradientApollonian),
|
||||
/// Any curvatures, with the colors running around the contours rather than from one end to the other.
|
||||
Across(GradientAcross),
|
||||
}
|
||||
|
||||
impl GradientShape {
|
||||
/// The shape of a gradient with these curvatures, each wrapped like [`wrapped_curvature`] and a line where it isn't finite, placed by `transform`.
|
||||
/// With curvatures other than a form's, a collapsed placement (like a zero-length gradient line) leaves the last stop's color, as SVG does.
|
||||
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel, direction: GradientDirection, transform: DAffine2) -> Self {
|
||||
let [start, end] = [start_curvature, end_curvature].map(|curvature| wrapped_curvature(curvature, 0.));
|
||||
let form = GradientForm::from_curvatures([start, end]);
|
||||
let collapsed = !transform.matrix2.determinant().recip().is_finite();
|
||||
|
||||
match (form, direction) {
|
||||
(None, _) if collapsed => Self::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }),
|
||||
(_, GradientDirection::Across) => Self::Across(GradientAcross {
|
||||
chart: AcrossChart::new(start, end, model),
|
||||
form,
|
||||
}),
|
||||
(Some(GradientForm::Linear), GradientDirection::Along) => Self::Linear,
|
||||
(Some(GradientForm::Radial), GradientDirection::Along) => Self::Radial,
|
||||
(None, GradientDirection::Along) if model == GradientModel::Apollonian => {
|
||||
// Identical end circles span no family of circles, so they draw the plain ramp
|
||||
let (start_radius, end_radius) = (curvature_radius(start), curvature_radius(end));
|
||||
if start_radius.is_finite() && end_radius.is_finite() && Cone::between(start_radius, end_radius).is_identical() {
|
||||
return Self::Standard(GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None });
|
||||
}
|
||||
|
||||
Self::Apollonian(GradientApollonian::new(start, end))
|
||||
}
|
||||
(None, GradientDirection::Along) => Self::Standard(GradientStandard::new(start, end)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether its position can fall before the start, which a radial gradient's distance from its center and an angle around the contours can't.
|
||||
pub fn reaches_before_start(&self) -> bool {
|
||||
match self {
|
||||
Self::Radial => false,
|
||||
Self::Across(across) => !across.chart.winds(),
|
||||
Self::Linear | Self::Standard(_) | Self::Apollonian(_) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether its position can fall past the end, which an angle around the contours can't.
|
||||
pub fn reaches_past_end(&self) -> bool {
|
||||
!matches!(self, Self::Across(across) if across.chart.winds())
|
||||
}
|
||||
|
||||
/// Whether it paints every point, rather than leaving some unpainted.
|
||||
pub fn paints_everywhere(&self) -> bool {
|
||||
match self {
|
||||
Self::Linear | Self::Radial | Self::Apollonian(_) => true,
|
||||
Self::Standard(gradient) => gradient.paints_everywhere(),
|
||||
Self::Across(across) => across.chart.paints_everywhere(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether SVG draws it exactly, which it does unless it's Apollonian circles (other than those between concentric end circles drawn as SVG 2's cone), or read across contours other than the linear form's.
|
||||
pub fn svg_draws_exactly(&self) -> bool {
|
||||
if let Self::Across(across) = self {
|
||||
return across.chart.svg_draws_exactly();
|
||||
}
|
||||
let Self::Apollonian(GradientApollonian { start, end, svg_stand_in, .. }) = self else {
|
||||
return true;
|
||||
};
|
||||
|
||||
// Each end circle is centered at `-b / 2a`, so they share a center where these products match
|
||||
let (start_product, end_product) = (start.b * end.a, end.b * start.a);
|
||||
let concentric = (start_product - end_product).abs() <= 1e-9 * (start_product.abs() + end_product.abs());
|
||||
concentric && matches!(svg_stand_in, GradientStandard::Cone(_))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Points spread over a view around the gradient line, kept off its exact rational coordinates.
|
||||
fn sample_points() -> impl Iterator<Item = DVec2> {
|
||||
(-30..=40).flat_map(|x| (-25..=25).map(move |y| DVec2::new(x as f64 * 0.1 + 0.0013, y as f64 * 0.1 + 0.0007)))
|
||||
}
|
||||
|
||||
/// The position a padded ramp shows, or `None` where unpainted.
|
||||
fn padded(t: Option<f64>) -> Option<f64> {
|
||||
t.map(|t| t.clamp(0., 1.))
|
||||
}
|
||||
|
||||
/// SVG 2's cone written independently in its circles' crossings of the gradient line, which stays precise for huge circles:
|
||||
/// circle `t` spans the diameter from `left(t)` to `right(t)`, each interpolated between the end circles' own, and counts
|
||||
/// where `right(t) >= left(t)`.
|
||||
fn reference_t(start: f64, end: f64, point: DVec2) -> Option<f64> {
|
||||
let (start_left, start_right) = ((2. * start).min(0.), (2. * start).max(0.));
|
||||
let (end_left, end_right) = ((1. - 2. * end).min(1.), (1. - 2. * end).max(1.));
|
||||
let (delta_left, delta_right) = (end_left - start_left, end_right - start_right);
|
||||
let scale = (delta_left * delta_left + delta_right * delta_right) / 2.;
|
||||
|
||||
// `(x - left(t))(x - right(t)) + y² = 0`, expanded in `t`
|
||||
let a = delta_left * delta_right;
|
||||
let b = -((point.x - start_left) * delta_right + (point.x - start_right) * delta_left);
|
||||
let c = (point.x - start_left) * (point.x - start_right) + point.y * point.y;
|
||||
let discriminant = b * b - 4. * a * c;
|
||||
let roots = match (a.abs() < 1e-12 * scale, discriminant >= 0.) {
|
||||
(true, _) => vec![-c / b],
|
||||
(false, true) => vec![(-b + discriminant.sqrt()) / (2. * a), (-b - discriminant.sqrt()) / (2. * a)],
|
||||
(false, false) => Vec::new(),
|
||||
};
|
||||
|
||||
roots
|
||||
.into_iter()
|
||||
.filter(|t| (start_right - start_left) + t * (delta_right - delta_left) >= -1e-9)
|
||||
.max_by(|a, b| a.total_cmp(b))
|
||||
}
|
||||
|
||||
/// Settings for each kind of pair of end circles, given by their signed radii, with what each is.
|
||||
const CONE_SETTINGS: [(f64, f64, &str); 6] = [
|
||||
(0., 0.75, "focal point inside the end circle, off its center"),
|
||||
(0.2, 1.5, "focal circle nested inside the end circle"),
|
||||
(2., -0.5, "end circle nested inside the start circle"),
|
||||
(0.6, 0.6, "crossing circles"),
|
||||
(-0.3, -0.3, "separate circles"),
|
||||
(0., -0.4, "focal point outside the end circle"),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn cones_take_svg_2s_largest_valid_circle() {
|
||||
for (start, end, setting) in CONE_SETTINGS {
|
||||
let gradient = GradientStandard::new(radius_curvature(start), radius_curvature(end));
|
||||
let GradientStandard::Cone(cone) = gradient else {
|
||||
panic!("{setting} should draw as a cone, not {gradient:?}");
|
||||
};
|
||||
|
||||
let mut unpainted = 0;
|
||||
for point in sample_points() {
|
||||
let (expected, actual) = (reference_t(start, end, point), gradient.t(point));
|
||||
match (expected, actual) {
|
||||
(Some(expected), Some(actual)) => {
|
||||
assert!((expected - actual).abs() < 1e-6 * expected.abs().max(1.), "{setting} at {point}: {actual} rather than {expected}");
|
||||
}
|
||||
(None, None) => unpainted += 1,
|
||||
_ => panic!("{setting} at {point}: {actual:?} rather than {expected:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
// Only circles neither inside the other leave some of the plane unpainted
|
||||
assert_eq!(unpainted > 0, !cone.is_nested(), "{setting}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_focal_point_off_center_takes_svg_2s_largest_circle() {
|
||||
// The focus at the start point, and the end circle of radius 0.75 centered at 0.25
|
||||
let gradient = GradientStandard::new(-1., radius_curvature(0.75));
|
||||
assert!((gradient.t(DVec2::new(-0.25, 0.)).unwrap() - 0.5).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_ends_are_svg_2s_limits_from_their_side() {
|
||||
const FLAT: f64 = 1e6;
|
||||
|
||||
// The other end's signed radius, through circles of each size and bend and a point
|
||||
let others = (-20..=20).filter(|&step| step != 0).map(|step| curvature_radius(step as f64 * 0.049)).chain([0.]);
|
||||
|
||||
for other in others {
|
||||
for inward in [true, false] {
|
||||
let flat = if inward { FLAT } else { -FLAT };
|
||||
for (limit, [start, end], which) in [
|
||||
(GradientStandard::end_line(other, inward), [other, flat], "end"),
|
||||
(GradientStandard::start_line(other, inward), [flat, other], "start"),
|
||||
] {
|
||||
let cut = match limit {
|
||||
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => keep,
|
||||
_ => panic!("an {which} line should draw as a ramp or solid color, not {limit:?}"),
|
||||
};
|
||||
|
||||
for point in sample_points() {
|
||||
// The cone's unpainted edge nears the cut line at a rate of the square root of its radius
|
||||
if cut.is_some_and(|cut| (point.x - cut.at).abs() < 0.02) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (expected, actual) = (padded(reference_t(start, end, point)), padded(limit.t(point)));
|
||||
let context = format!("{which} line bowing inward {inward}, beside radius {other} at {point}");
|
||||
match (expected, actual) {
|
||||
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 0.01, "{context}: {actual} rather than {expected}"),
|
||||
(None, None) => {}
|
||||
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_line_settings_take_the_chosen_limits() {
|
||||
// Both lines, and an end line beside a start bowing away from it, are the plain ramp
|
||||
assert_eq!(GradientStandard::new(0., 0.), GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None });
|
||||
assert_eq!(GradientStandard::new(-0.3, 0.), GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None });
|
||||
|
||||
// An end line beside a start circle reaching past the end point is cut off past the start circle's far crossing
|
||||
let start = 0.8;
|
||||
let GradientStandard::Ramp { ramp, keep: Some(keep) } = GradientStandard::new(radius_curvature(start), 0.) else {
|
||||
panic!("an end line beyond a large start circle should be cut off");
|
||||
};
|
||||
assert!((ramp.start - 2. * start).abs() < 1e-12 && ramp.end == 1.);
|
||||
assert!(keep.keeps_before && (keep.at - 2. * start).abs() < 1e-12);
|
||||
|
||||
// A start line takes the ramp to the end circle's backward crossing, or the last stop past that crossing once the end circle reaches the start point
|
||||
let GradientStandard::Ramp { ramp, keep: None } = GradientStandard::new(0., radius_curvature(0.25)) else {
|
||||
panic!("a start line beside a small end circle should be a ramp");
|
||||
};
|
||||
assert!(ramp.start == 0. && (ramp.end - 0.5).abs() < 1e-12);
|
||||
let GradientStandard::Solid { end: RampEnd::Last, keep: Some(keep) } = GradientStandard::new(0., radius_curvature(2.)) else {
|
||||
panic!("a start line beside an end circle reaching the start point should be the last stop");
|
||||
};
|
||||
assert!(!keep.keeps_before && (keep.at + 3.).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearly_flat_cones_draw_their_profile_along_the_line() {
|
||||
let settings = [
|
||||
(0.3, 2500.),
|
||||
(0.3, -2500.),
|
||||
(2500., 0.2),
|
||||
(-2500., 0.2),
|
||||
(-0.4, 3000.),
|
||||
(0., -2200.),
|
||||
// Both ends nearly flat: equal radii bowing apart and together, and an apex before the start at x = -3
|
||||
(-3000., 3000.),
|
||||
(3000., -3000.),
|
||||
(3000., -4000.),
|
||||
];
|
||||
for (start, end) in settings {
|
||||
let profile = GradientStandard::new(radius_curvature(start), radius_curvature(end));
|
||||
let split = match profile {
|
||||
GradientStandard::Profile { split, .. } => Some(split),
|
||||
GradientStandard::Ramp { keep, .. } => keep.map(|keep| keep.at),
|
||||
GradientStandard::Nothing => None,
|
||||
_ => panic!("({start}, {end}) should draw as its profile, not {profile:?}"),
|
||||
};
|
||||
|
||||
// Within a level or two of the cone itself, except beside the apex, where the cone's circles are small and its edges lean
|
||||
for point in sample_points() {
|
||||
if split.is_some_and(|split| (point.x - split).abs() < 0.05 + 0.05 * point.y.abs()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (expected, actual) = (padded(reference_t(start, end, point)), padded(profile.t(point)));
|
||||
let context = format!("({start}, {end}) at {point}");
|
||||
match (expected, actual) {
|
||||
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 0.01, "{context}: {actual} rather than {expected}"),
|
||||
(None, None) => {}
|
||||
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Codex's example, where the last stop shows everywhere
|
||||
let both_flat = GradientStandard::new(radius_curvature(-3000.), radius_curvature(3000.));
|
||||
assert_eq!(padded(both_flat.t(DVec2::new(0.5, 0.2))), Some(1.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_profile_of_a_flattening_end_nears_the_line_limits() {
|
||||
const FLAT: f64 = 1e9;
|
||||
|
||||
// The other end's signed radius, through circles of each size and bend and a point, and the start circle reaching the end point
|
||||
let others = (-20..=20).filter(|&step| step != 0).map(|step| curvature_radius(step as f64 * 0.049)).chain([0., 0.5]);
|
||||
|
||||
for other in others {
|
||||
for inward in [true, false] {
|
||||
let flat = if inward { FLAT } else { -FLAT };
|
||||
for (limit, profile, which) in [
|
||||
(GradientStandard::end_line(other, inward), GradientStandard::profile(other, flat), "end"),
|
||||
(GradientStandard::start_line(other, inward), GradientStandard::profile(flat, other), "start"),
|
||||
] {
|
||||
let cuts = [limit, profile].map(|gradient| match gradient {
|
||||
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => keep.map(|keep| keep.at),
|
||||
GradientStandard::Profile { split, .. } => Some(split),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
for point in sample_points() {
|
||||
if cuts.iter().flatten().any(|cut| (point.x - cut).abs() < 1e-3) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (expected, actual) = (padded(limit.t(point)), padded(profile.t(point)));
|
||||
let context = format!("{which} line bowing inward {inward}, beside radius {other} at {point}");
|
||||
match (expected, actual) {
|
||||
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 1e-6, "{context}: {actual} rather than {expected}"),
|
||||
(None, None) => {}
|
||||
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_end_line_through_a_start_circle_reaching_the_end_point_shows_the_first_stop() {
|
||||
let before_end_point = Some(HalfPlane { at: 1., keeps_before: true });
|
||||
assert_eq!(
|
||||
GradientStandard::end_line(0.5, true),
|
||||
GradientStandard::Solid {
|
||||
end: RampEnd::First,
|
||||
keep: before_end_point
|
||||
}
|
||||
);
|
||||
|
||||
let profile = GradientStandard::profile(0.5, 1e9);
|
||||
for point in sample_points().filter(|point| (point.x - 1.).abs() > 1e-3) {
|
||||
let t = padded(profile.t(point));
|
||||
assert!(if point.x < 1. { t.is_some_and(|t| t < 1e-6) } else { t.is_none() }, "at {point}: {t:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internally_tangent_circles_leave_the_far_side_of_their_tangent_line_unpainted() {
|
||||
// The start circle of radius 1 and the end circle of radius 0.5 touch at the start point
|
||||
let gradient = GradientStandard::new(radius_curvature(1.), radius_curvature(0.5));
|
||||
assert_eq!(gradient.t(DVec2::new(-1., 0.)), None);
|
||||
assert!(gradient.t(DVec2::new(0.5, 0.)).is_some_and(|t| (t - 1.5).abs() < 1e-12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nearly_flat_cones_keep_their_ramps_ends_and_widths() {
|
||||
// Equal radii of a million ramp from 2 million to the end point, reaching 1 exactly there so the Clear spread clears past it
|
||||
let gradient = GradientStandard::profile(1e6, 1e6);
|
||||
assert!((gradient.t(DVec2::new(0.75, 0.)).unwrap() - (1. + 0.25 / 1_999_999.)).abs() < 1e-15);
|
||||
assert_eq!(gradient.t(DVec2::X), Some(1.));
|
||||
|
||||
// A ramp a gradient length wide, 200,000 gradient lengths before the start, stays a ramp
|
||||
let gradient = GradientStandard::profile(-1e5, 1e5);
|
||||
assert!((gradient.t(DVec2::new(-199_999.5, 0.)).unwrap() - 0.5).abs() < 1e-9);
|
||||
|
||||
// Opposite radii of 10¹⁶ keep the 1 that their distant edges differ by, which makes the start's edge lead
|
||||
let at = DVec2::new(0.5, 0.);
|
||||
assert!((GradientStandard::profile(-1e16, 1e16).t(at).unwrap() - (2e16 + 0.5)).abs() < 4.);
|
||||
assert!((GradientStandard::profile(1e16, -1e16).t(at).unwrap() - 0.5).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extreme_curvatures_compute_finitely() {
|
||||
// Curvatures so near a line that their radii overflow when doubled, and either side of radii of 10³⁰ gradient lengths
|
||||
let extremes = [4e-309, -4e-309, 1e-300, 6e-31, -6e-31, 7e-31, -7e-31, 1e-17, -1e-17];
|
||||
let curvatures = extremes.iter().flat_map(|&extreme| {
|
||||
[
|
||||
[extreme, 0.],
|
||||
[0., extreme],
|
||||
[extreme, 0.3],
|
||||
[-0.3, extreme],
|
||||
[extreme, extreme],
|
||||
[extreme, -extreme],
|
||||
[extreme, 1. - 1e-16],
|
||||
]
|
||||
});
|
||||
|
||||
for [start, end] in curvatures {
|
||||
let gradient = GradientStandard::new(start, end);
|
||||
for point in sample_points() {
|
||||
// A position may be an end stop's infinity but not a number lost to overflow
|
||||
let t = gradient.t(point);
|
||||
assert!(t.is_none_or(|t| !t.is_nan()), "curvatures ({start}, {end}) at {point}: {gradient:?}");
|
||||
}
|
||||
}
|
||||
assert_eq!((curvature_radius(4e-309), curvature_radius(-4e-309)), (FLATTEST_RADIUS, -FLATTEST_RADIUS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curvatures_beside_zero_keep_their_side() {
|
||||
// Beside a start circle reaching past the midpoint, an end flattening from either side nears a different limit than the line
|
||||
let start = radius_curvature(0.4);
|
||||
for side in [1., -1.] {
|
||||
let beside_zero = GradientStandard::new(start, side * 1e-40);
|
||||
let flattening = GradientStandard::new(start, radius_curvature(side * 1e20));
|
||||
|
||||
for point in sample_points() {
|
||||
let (expected, actual) = (padded(flattening.t(point)), padded(beside_zero.t(point)));
|
||||
let context = format!("end curvature beside 0 on side {side} at {point}");
|
||||
match (expected, actual) {
|
||||
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 1e-6, "{context}: {actual} rather than {expected}"),
|
||||
(None, None) => {}
|
||||
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identical_circles_leave_nothing() {
|
||||
let curvature = radius_curvature(0.5);
|
||||
assert_eq!(GradientStandard::new(curvature, curvature), GradientStandard::Nothing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_radial_preset_draws_distance_from_its_center() {
|
||||
let gradient = GradientStandard::new(-1., 0.5);
|
||||
for point in sample_points() {
|
||||
let t = gradient.t(point).unwrap();
|
||||
assert!((t - point.length()).abs() < 1e-9, "at {point}: {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_length_gradient_line_leaves_the_last_stop_once_curved() {
|
||||
let collapsed = DAffine2::from_cols(DVec2::ZERO, DVec2::Y, DVec2::new(3., 4.));
|
||||
for model in [GradientModel::Standard, GradientModel::Apollonian] {
|
||||
let shape = |[start, end]: [f64; 2]| GradientShape::new(start, end, model, GradientDirection::Along, collapsed);
|
||||
|
||||
assert_eq!(shape([0.3, 0.2]), GradientShape::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }));
|
||||
// The forms keep drawing as they always have
|
||||
assert_eq!(shape([0., 0.]), GradientShape::Linear);
|
||||
assert_eq!(shape([-1., 0.5]), GradientShape::Radial);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apollonian_gradients_stand_in_for_svg_with_its_own_drawing_where_that_paints_everywhere() {
|
||||
let placement = DAffine2::IDENTITY;
|
||||
let stand_in = |curvatures: [f64; 2]| match GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, placement) {
|
||||
GradientShape::Apollonian(apollonian) => apollonian.svg_stand_in,
|
||||
shape => panic!("curvatures {curvatures:?} should draw Apollonian circles, not {shape:?}"),
|
||||
};
|
||||
|
||||
// Concentric end circles draw SVG 2's own drawing, a cone or for huge ones its profile, while crossing ones draw the plain ramp however flat they are
|
||||
let plain_ramp = GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None };
|
||||
for concentric in [[radius_curvature(2.), radius_curvature(-1.)], [radius_curvature(3000.), radius_curvature(-2999.)]] {
|
||||
let drawn = GradientStandard::new(concentric[0], concentric[1]);
|
||||
assert!(drawn.paints_everywhere(), "{drawn:?}");
|
||||
assert_eq!(stand_in(concentric), drawn);
|
||||
}
|
||||
for crossing in [0.6, 3000.] {
|
||||
assert_eq!(stand_in([radius_curvature(crossing), radius_curvature(crossing)]), plain_ramp, "radii of {crossing}");
|
||||
}
|
||||
|
||||
// Identical end circles span no family of circles, so they draw the plain ramp everywhere
|
||||
let identical = radius_curvature(0.5);
|
||||
assert_eq!(
|
||||
GradientShape::new(identical, identical, GradientModel::Apollonian, GradientDirection::Along, placement),
|
||||
GradientShape::Standard(plain_ramp)
|
||||
);
|
||||
|
||||
// The forms stay native under either model
|
||||
assert_eq!(GradientShape::new(0., 0., GradientModel::Apollonian, GradientDirection::Along, placement), GradientShape::Linear);
|
||||
assert_eq!(GradientShape::new(-1., 0.5, GradientModel::Apollonian, GradientDirection::Along, placement), GradientShape::Radial);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_draws_every_shape_exactly_but_apollonian_circles_it_cant_draw_as_a_cone() {
|
||||
let exact = |curvatures: [f64; 2], model: GradientModel| GradientShape::new(curvatures[0], curvatures[1], model, GradientDirection::Along, DAffine2::IDENTITY).svg_draws_exactly();
|
||||
|
||||
// Concentric end circles, the start centered at its radius and the end at 1 minus its own, have Apollonian circles that are SVG 2's cone
|
||||
for [start, end] in [[2., -1.], [-0.5, 1.5], [0.25, 0.75]] {
|
||||
let curvatures = [radius_curvature(start), radius_curvature(end)];
|
||||
assert!(matches!(
|
||||
GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, DAffine2::IDENTITY),
|
||||
GradientShape::Apollonian(_)
|
||||
));
|
||||
assert!(exact(curvatures, GradientModel::Apollonian), "radii {start} and {end}");
|
||||
}
|
||||
|
||||
// Crossing, nested off center, a line beside a circle, a point beside a circle, and concentric ones so large SVG draws them by their profile
|
||||
let off_center = [
|
||||
[radius_curvature(0.6), radius_curvature(0.6)],
|
||||
[radius_curvature(2.), radius_curvature(-0.5)],
|
||||
[0., radius_curvature(0.5)],
|
||||
[1., 0.3],
|
||||
];
|
||||
for curvatures in off_center.into_iter().chain([[radius_curvature(3000.), radius_curvature(-2999.)]]) {
|
||||
assert!(!exact(curvatures, GradientModel::Apollonian), "curvatures {curvatures:?}");
|
||||
assert!(exact(curvatures, GradientModel::Standard), "curvatures {curvatures:?} drawn as SVG 2 draws them");
|
||||
}
|
||||
|
||||
// The forms stay native under either model
|
||||
assert!(exact([0., 0.], GradientModel::Apollonian) && exact([-1., 0.5], GradientModel::Apollonian));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radius_curvatures_invert_curvature_radii() {
|
||||
for curvature in [-0.9, -0.5, -0.1, 0.1, 0.5, 0.9] {
|
||||
assert!((radius_curvature(curvature_radius(curvature)) - curvature).abs() < 1e-12);
|
||||
}
|
||||
assert_eq!(curvature_radius(radius_curvature(0.)), 0.);
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,17 @@
|
||||
extern crate log;
|
||||
|
||||
pub mod gradient;
|
||||
pub mod gradient_across;
|
||||
pub mod gradient_apollonian;
|
||||
pub mod gradient_standard;
|
||||
pub mod math;
|
||||
pub mod vector;
|
||||
|
||||
// Re-export commonly used types at the crate root
|
||||
pub use core_types as gcore;
|
||||
pub use gradient::{Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
|
||||
pub use gradient::{
|
||||
Gradient, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop,
|
||||
};
|
||||
pub use math::QuadExt;
|
||||
pub use vector::Vector;
|
||||
pub use vector::reference_point::ReferencePoint;
|
||||
|
||||
@@ -84,7 +84,9 @@ impl WgpuExecutor {
|
||||
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
|
||||
|
||||
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
self.inner.vello_renderer.render(self, &mut canvas, draw, view, size, &texture)?;
|
||||
self.inner
|
||||
.vello_renderer
|
||||
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
@@ -93,7 +95,7 @@ impl WgpuExecutor {
|
||||
pub fn render_vello_scene_on_canvas(&self, canvas: &mut VelloCanvas, scene: VelloSceneBuilder) -> Result<Texture> {
|
||||
let texture = self.request_texture(UVec2::new(scene.width() as u32, scene.height() as u32));
|
||||
|
||||
self.inner.vello_renderer.render_scene(self, canvas, scene, &texture);
|
||||
self.inner.vello_renderer.render_scene(canvas, &self.context().device, &self.context().queue, scene, &texture);
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
@@ -163,11 +165,7 @@ impl WgpuExecutor {
|
||||
}
|
||||
|
||||
pub fn request_texture_with_format(&self, size: UVec2, format: wgpu::TextureFormat) -> Texture {
|
||||
self.request_texture_with_mips(size, format, 1)
|
||||
}
|
||||
|
||||
pub fn request_texture_with_mips(&self, size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> Texture {
|
||||
self.inner.texture_cache.lock().unwrap().request_texture(self.context(), size, format, mip_level_count)
|
||||
self.inner.texture_cache.lock().unwrap().request_texture(&self.context().device, size, format)
|
||||
}
|
||||
|
||||
pub fn create_buffer(&self, desc: &wgpu::BufferDescriptor) -> Buffer {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::WgpuContext;
|
||||
use glam::UVec2;
|
||||
use raster_types::Texture;
|
||||
use std::collections::VecDeque;
|
||||
@@ -17,23 +16,24 @@ impl TextureCache {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn request_texture(&mut self, context: &WgpuContext, size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> Texture {
|
||||
pub fn request_texture(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> Texture {
|
||||
let size = size.max(UVec2::ONE);
|
||||
|
||||
if let Some(pos) = self.textures.iter().position(|texture| {
|
||||
UVec2::new(texture.width(), texture.height()) == size && texture.format() == format && texture.mip_level_count() == mip_level_count && !texture.is_shared() && !texture.is_weakly_shared()
|
||||
}) {
|
||||
if let Some(pos) = self
|
||||
.textures
|
||||
.iter()
|
||||
.position(|texture| UVec2::new(texture.width(), texture.height()) == size && texture.format() == format && !texture.is_shared() && !texture.is_weakly_shared())
|
||||
{
|
||||
let entry = self.textures.remove(pos).unwrap();
|
||||
let texture = entry.clone();
|
||||
self.textures.push_back(entry);
|
||||
return texture;
|
||||
}
|
||||
|
||||
self.evict_until_fits(memory_size_estimate(size, format, mip_level_count));
|
||||
let incoming_bytes = size.x as u64 * size.y as u64 * format.block_copy_size(None).unwrap_or(4) as u64;
|
||||
self.evict_until_fits(incoming_bytes);
|
||||
|
||||
let usage = wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT;
|
||||
let texture: Texture = context
|
||||
.device
|
||||
let texture: Texture = device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(&format!("cached_{}x{}", size.x, size.y)),
|
||||
size: wgpu::Extent3d {
|
||||
@@ -41,11 +41,11 @@ impl TextureCache {
|
||||
height: size.y,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: usage & context.adapter.get_texture_format_features(format).allowed_usages,
|
||||
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
})
|
||||
.into();
|
||||
@@ -83,20 +83,12 @@ impl TextureCache {
|
||||
}
|
||||
}
|
||||
|
||||
fn memory_size_estimate(size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> u64 {
|
||||
let texel_bytes = format.block_copy_size(None).unwrap_or(4) as u64;
|
||||
(0..mip_level_count)
|
||||
.map(|level| (size >> level).max(UVec2::ONE))
|
||||
.map(|level_size| level_size.x as u64 * level_size.y as u64 * texel_bytes)
|
||||
.sum()
|
||||
}
|
||||
|
||||
trait TextureMemoryCostEstimateExt {
|
||||
fn memory_size_estimate(&self) -> u64;
|
||||
}
|
||||
|
||||
impl TextureMemoryCostEstimateExt for wgpu::Texture {
|
||||
fn memory_size_estimate(&self) -> u64 {
|
||||
memory_size_estimate(UVec2::new(self.width(), self.height()), self.format(), self.mip_level_count())
|
||||
self.width() as u64 * self.height() as u64 * self.format().block_copy_size(None).unwrap_or(4) as u64
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,10 @@
|
||||
//! from `vello_adjustments.wgsl`, while the kinds that compilers struggle to build inside its loop each get a shader and pass of their own. Steps read their
|
||||
//! settings from a texture, so changing those recompiles nothing.
|
||||
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_effects::{WORKING_FORMAT, pass_pipeline};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use glam::UVec2;
|
||||
use graphic_types::Adjustment;
|
||||
use raster_kernels::adjustment_steps::{AdjustmentSteps, StepKind, shader_constants};
|
||||
use raster_types::{Texture, TextureWeakRef};
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
@@ -25,8 +22,11 @@ const STANDALONE_KINDS: [StepKind; 2] = [StepKind::GradientMap, StepKind::ColorL
|
||||
/// How many runs of adjustments keep their encoded and uploaded steps past the render that last used them. Their tables are kept apart.
|
||||
const MAX_CACHED_RUNS: usize = 8;
|
||||
|
||||
/// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of the largest buffer wgpu allocates by default,
|
||||
/// which an upload passes through.
|
||||
/// How many bytes of tables stay uploaded past the render that last used them, the least recently used making way first.
|
||||
const TABLE_CACHE_BYTES: u64 = 256 << 20;
|
||||
|
||||
/// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of what the cache keeps and of the largest buffer
|
||||
/// wgpu allocates by default, which an upload passes through.
|
||||
const MAX_TABLE_TEXELS: usize = 1 << 23;
|
||||
|
||||
/// The format each pass of a run split across several hands its result on to the next in, where the GPU can render into it, so the split rounds nothing.
|
||||
@@ -344,15 +344,15 @@ fn texels_texture_descriptor(label: &'static str, width: u32, height: u32) -> wg
|
||||
}
|
||||
|
||||
/// A texture holding `texels` in rows as wide as the GPU allows, the last padded out, or `None` if they need more rows than it allows too.
|
||||
fn upload_texels(executor: &WgpuExecutor, queue: &wgpu::Queue, texels: &[[f32; 4]]) -> Option<Texture> {
|
||||
let max_dimension = executor.context().device.limits().max_texture_dimension_2d as usize;
|
||||
fn upload_texels(device: &wgpu::Device, queue: &wgpu::Queue, label: &'static str, texels: &[[f32; 4]]) -> Option<wgpu::Texture> {
|
||||
let max_dimension = device.limits().max_texture_dimension_2d as usize;
|
||||
let width = texels.len().clamp(1, max_dimension);
|
||||
let height = texels.len().div_ceil(width).max(1);
|
||||
if height > max_dimension {
|
||||
return None;
|
||||
}
|
||||
|
||||
let texture = executor.request_texture_with_format(UVec2::new(width as u32, height as u32), wgpu::TextureFormat::Rgba32Float);
|
||||
let texture = device.create_texture(&texels_texture_descriptor(label, width as u32, height as u32));
|
||||
let write_rows = |first_row: usize, rows: usize, data: &[[f32; 4]]| {
|
||||
let texture_rows = wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
@@ -397,12 +397,12 @@ pub(crate) struct PreparedPass {
|
||||
|
||||
/// The shader and the uploaded steps of each pass carrying out a run with these `steps`, each pass's texels starting with its step count,
|
||||
/// or `None` if any holds more than the GPU can read.
|
||||
fn upload_passes(executor: &WgpuExecutor, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option<Vec<(AdjustmentShader, Texture)>> {
|
||||
fn upload_passes(device: &wgpu::Device, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option<Vec<(AdjustmentShader, wgpu::Texture)>> {
|
||||
(pass_steps(steps.kinds()).into_iter())
|
||||
.map(|pass| {
|
||||
let shader = AdjustmentShader::for_pass(&steps.kinds()[pass.clone()]);
|
||||
let texels: Vec<[f32; 4]> = std::iter::once([pass.len() as f32, 0., 0., 0.]).chain(steps.step_texels(pass).iter().copied()).collect();
|
||||
upload_texels(executor, queue, &texels).map(|texture| (shader, texture))
|
||||
upload_texels(device, queue, "vello_adjustments_steps", &texels).map(|texture| (shader, texture))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -419,14 +419,15 @@ pub(crate) struct AdjustmentUploads {
|
||||
struct CachedRun {
|
||||
hash: u64,
|
||||
steps: AdjustmentSteps,
|
||||
passes: Option<Vec<(AdjustmentShader, TextureWeakRef)>>,
|
||||
passes: Option<Vec<(AdjustmentShader, wgpu::Texture)>>,
|
||||
last_used: u64,
|
||||
}
|
||||
|
||||
/// The tables of a run as uploaded, shared by every run reading the same ones, or `None` in place of the upload for tables too large for the GPU even resampled.
|
||||
struct CachedTables {
|
||||
key: u64,
|
||||
uploaded: Option<TextureWeakRef>,
|
||||
uploaded: Option<wgpu::Texture>,
|
||||
bytes: u64,
|
||||
last_used: u64,
|
||||
}
|
||||
|
||||
@@ -437,95 +438,70 @@ pub(crate) fn adjustment_run_hash(run: &[&Adjustment]) -> u64 {
|
||||
std::hash::Hasher::finish(&hasher)
|
||||
}
|
||||
|
||||
fn downgrade_passes(passes: &[(AdjustmentShader, Texture)]) -> Vec<(AdjustmentShader, TextureWeakRef)> {
|
||||
passes.iter().map(|(shader, texture)| (*shader, texture.downgrade())).collect()
|
||||
}
|
||||
|
||||
impl AdjustmentUploads {
|
||||
/// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has, with the uploads it reads added to `held`.
|
||||
/// A run that changes no color or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart.
|
||||
pub(crate) fn prepare(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64, held: &mut Vec<Texture>) -> Vec<PreparedPass> {
|
||||
/// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has. A run that changes no color
|
||||
/// or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart.
|
||||
pub(crate) fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64) -> Vec<PreparedPass> {
|
||||
let hash = adjustment_run_hash(run);
|
||||
let mut uploaded = None;
|
||||
let index = self.runs.iter().position(|cached| cached.hash == hash).unwrap_or_else(|| {
|
||||
let steps = AdjustmentSteps::encode(run);
|
||||
uploaded = upload_passes(executor, queue, &steps);
|
||||
if uploaded.is_none() {
|
||||
let passes = upload_passes(device, queue, &steps);
|
||||
if passes.is_none() {
|
||||
log::error!("Adjustments hold more settings than the GPU can read, so they're left out");
|
||||
}
|
||||
|
||||
self.runs.push(CachedRun {
|
||||
hash,
|
||||
steps,
|
||||
passes: uploaded.as_deref().map(downgrade_passes),
|
||||
passes,
|
||||
last_used: render_count,
|
||||
});
|
||||
self.runs.len() - 1
|
||||
});
|
||||
let cached_run = &mut self.runs[index];
|
||||
cached_run.last_used = render_count;
|
||||
let Some(cached_passes) = &cached_run.passes else { return Vec::new() };
|
||||
let parked = cached_passes.iter().map(|(shader, texture)| Some((*shader, texture.upgrade()?))).collect();
|
||||
let passes = match uploaded.or(parked) {
|
||||
Some(passes) => passes,
|
||||
None => {
|
||||
let Some(passes) = upload_passes(executor, queue, &cached_run.steps) else { return Vec::new() };
|
||||
cached_run.passes = Some(downgrade_passes(&passes));
|
||||
passes
|
||||
}
|
||||
};
|
||||
let Some(passes) = cached_run.passes.clone() else { return Vec::new() };
|
||||
if passes.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let tables = match cached_run.steps.table_key() {
|
||||
Some(key) => {
|
||||
let index = self.tables.iter().position(|cached| cached.key == key);
|
||||
let parked = index.map(|index| self.tables[index].uploaded.as_ref().map(TextureWeakRef::upgrade));
|
||||
let tables = match parked {
|
||||
// Failed to upload
|
||||
Some(None) => return Vec::new(),
|
||||
// Parked
|
||||
Some(Some(Some(tables))) => Some(tables),
|
||||
// Not parked
|
||||
Some(Some(None)) | None => {
|
||||
// As many texels as one texture holds and one upload carries
|
||||
let limits = executor.context().device.limits();
|
||||
let max_dimension = limits.max_texture_dimension_2d as usize;
|
||||
let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize;
|
||||
let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded));
|
||||
let index = self.tables.iter().position(|cached| cached.key == key).unwrap_or_else(|| {
|
||||
// As many texels as one texture holds and one upload carries
|
||||
let limits = device.limits();
|
||||
let max_dimension = limits.max_texture_dimension_2d as usize;
|
||||
let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize;
|
||||
let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded));
|
||||
|
||||
let uploaded = upload_texels(executor, queue, &texels);
|
||||
if uploaded.is_none() {
|
||||
log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out");
|
||||
}
|
||||
let cached = CachedTables {
|
||||
key,
|
||||
uploaded: uploaded.as_ref().map(Texture::downgrade),
|
||||
last_used: render_count,
|
||||
};
|
||||
match index {
|
||||
Some(index) => self.tables[index] = cached,
|
||||
None => self.tables.push(cached),
|
||||
}
|
||||
uploaded
|
||||
let uploaded = upload_texels(device, queue, "vello_adjustments_tables", &texels);
|
||||
if uploaded.is_none() {
|
||||
log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out");
|
||||
}
|
||||
};
|
||||
let Some(tables) = tables else { return Vec::new() };
|
||||
if let Some(index) = index {
|
||||
self.tables[index].last_used = render_count;
|
||||
}
|
||||
Some(tables)
|
||||
|
||||
self.tables.push(CachedTables {
|
||||
key,
|
||||
bytes: uploaded
|
||||
.as_ref()
|
||||
.map_or(0, |texture| u64::from(texture.width()) * u64::from(texture.height()) * size_of::<[f32; 4]>() as u64),
|
||||
uploaded,
|
||||
last_used: render_count,
|
||||
});
|
||||
self.tables.len() - 1
|
||||
});
|
||||
let cached_tables = &mut self.tables[index];
|
||||
cached_tables.last_used = render_count;
|
||||
let Some(uploaded) = cached_tables.uploaded.clone() else { return Vec::new() };
|
||||
Some(uploaded)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
held.extend(passes.iter().map(|(_, steps)| steps.clone()).chain(tables.clone()));
|
||||
(passes.into_iter())
|
||||
.map(|(shader, steps)| PreparedPass {
|
||||
shader,
|
||||
steps: (*steps).clone(),
|
||||
tables: tables.as_ref().map(|tables| (**tables).clone()),
|
||||
steps,
|
||||
tables: tables.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -537,7 +513,13 @@ impl AdjustmentUploads {
|
||||
let used_this_render = self.runs.iter().take_while(|cached| cached.last_used == render_count).count();
|
||||
self.runs.truncate(used_this_render.max(MAX_CACHED_RUNS));
|
||||
|
||||
self.tables.retain(|cached| cached.uploaded.as_ref().is_none_or(|tables| tables.upgrade().is_some()));
|
||||
// Tables are kept within a byte budget instead, since one can take up hundreds of megabytes
|
||||
self.tables.sort_by_key(|cached| Reverse(cached.last_used));
|
||||
let mut kept_bytes = 0;
|
||||
self.tables.retain(|cached| {
|
||||
kept_bytes += cached.bytes;
|
||||
cached.last_used == render_count || kept_bytes <= TABLE_CACHE_BYTES
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! The GPU passes that carry out an item's effects on its content, between rendering the content offscreen and drawing the result back.
|
||||
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_adjustments::{AdjustmentShaders, AdjustmentUploads, PassEncodings, PreparedPass};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use core_types::Color;
|
||||
@@ -15,7 +14,6 @@ use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, Halft
|
||||
use graphic_types::{Adjustment, BevelDirection, BevelStyle, BevelTechnique, EffectOperation, Effects, GlowSource, GlowTechnique};
|
||||
use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH, chamfer_passes};
|
||||
use raster_kernels::resample_kernels::MotionBlurShear;
|
||||
use raster_types::Texture;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use vello_gpu::kurbo::Affine;
|
||||
@@ -52,6 +50,9 @@ const GRADIENT_SAMPLES: u32 = GRADIENT_TABLE_SIZE as u32;
|
||||
const PARAMETER_TAPS: usize = 81;
|
||||
const _: () = assert!(PARAMETER_TAPS > 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2));
|
||||
|
||||
/// How many renders a pooled texture survives unused before it is freed.
|
||||
const UNUSED_TEXTURE_RENDER_LIMIT: u64 = 3;
|
||||
|
||||
/// The shader's parameters, laid out to match its `Parameters` struct.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Pod, Zeroable)]
|
||||
@@ -274,7 +275,7 @@ impl EffectPasses {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn apply(
|
||||
&self,
|
||||
executor: &WgpuExecutor,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
textures: &mut EffectTextures,
|
||||
content: &wgpu::Texture,
|
||||
@@ -288,10 +289,8 @@ impl EffectPasses {
|
||||
backdrop: Option<(&wgpu::Texture, Affine)>,
|
||||
capture: Option<EffectCapture>,
|
||||
) -> Vec<(wgpu::Texture, BlendMode)> {
|
||||
let device = &executor.context().device;
|
||||
let mut recorder = PassRecorder {
|
||||
passes: self,
|
||||
executor,
|
||||
device,
|
||||
queue,
|
||||
encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_effects") }),
|
||||
@@ -1013,7 +1012,7 @@ impl EffectPasses {
|
||||
// The content at full strength is read only by an operation after the run, or shown as the result where no fill fades it
|
||||
let full_is_read = filled.is_none() || position + run.len() < operations.len();
|
||||
|
||||
let prepared_passes = recorder.textures.prepare_adjustments(recorder.executor, queue, &run);
|
||||
let prepared_passes = recorder.textures.prepare_adjustments(device, queue, &run);
|
||||
|
||||
// Each pass but the last hands its result on in the chained format, so splitting the run rounds nothing
|
||||
for (index, prepared) in prepared_passes.iter().enumerate() {
|
||||
@@ -1244,7 +1243,7 @@ impl EffectPasses {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn adjust_image(
|
||||
&self,
|
||||
executor: &WgpuExecutor,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
textures: &mut EffectTextures,
|
||||
image: &wgpu::Texture,
|
||||
@@ -1253,10 +1252,8 @@ impl EffectPasses {
|
||||
target: &wgpu::Texture,
|
||||
) {
|
||||
let size = UVec2::new(image.width(), image.height());
|
||||
let device = &executor.context().device;
|
||||
let mut recorder = PassRecorder {
|
||||
passes: self,
|
||||
executor,
|
||||
device,
|
||||
queue,
|
||||
encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
@@ -1288,20 +1285,19 @@ impl EffectPasses {
|
||||
}
|
||||
chained.into_iter().for_each(|texture| recorder.textures.release(texture));
|
||||
|
||||
self.record_mipmaps(executor, &mut recorder.encoder, recorder.textures, target);
|
||||
self.record_mipmaps(device, &mut recorder.encoder, recorder.textures, target);
|
||||
queue.submit([recorder.encoder.finish()]);
|
||||
}
|
||||
|
||||
/// Records the averaging of each of `texture`'s smaller mip levels from the one above it, like the levels of an uploaded image.
|
||||
/// Each is halved into a pooled texture and copied into place, since WebGL sets the levels read for a whole texture, so none is drawn into while another is read.
|
||||
pub(crate) fn record_mipmaps(&self, executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) {
|
||||
let device = &executor.context().device;
|
||||
pub(crate) fn record_mipmaps(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) {
|
||||
let format = texture.format();
|
||||
let mut above: Option<wgpu::Texture> = None;
|
||||
|
||||
for index in 1..texture.mip_level_count() {
|
||||
let level_size = UVec2::new(texture.width() >> index, texture.height() >> index).max(UVec2::ONE);
|
||||
let level = textures.acquire(executor, level_size, format);
|
||||
let level = textures.acquire(device, level_size, format);
|
||||
|
||||
// The first level reads the top one through a view of every level
|
||||
let source = above.as_ref().unwrap_or(texture).create_view(&wgpu::TextureViewDescriptor::default());
|
||||
@@ -1454,7 +1450,6 @@ fn premultiplied_gamma_channels(color: Color) -> [f32; 4] {
|
||||
/// Records the passes of one effects group, whose images all share one size.
|
||||
struct PassRecorder<'a> {
|
||||
passes: &'a EffectPasses,
|
||||
executor: &'a WgpuExecutor,
|
||||
device: &'a wgpu::Device,
|
||||
queue: &'a wgpu::Queue,
|
||||
encoder: wgpu::CommandEncoder,
|
||||
@@ -1475,7 +1470,7 @@ impl PassRecorder<'_> {
|
||||
content: Option<&wgpu::Texture>,
|
||||
parameters: Parameters,
|
||||
) -> wgpu::Texture {
|
||||
let target = self.textures.acquire(self.executor, size, format);
|
||||
let target = self.textures.acquire(self.device, size, format);
|
||||
|
||||
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let (source, secondary, content) = (view(source), secondary.map(view), content.map(view));
|
||||
@@ -1623,7 +1618,7 @@ impl PassRecorder<'_> {
|
||||
fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, content: &wgpu::Texture, fades: bool, grain: Option<&styles::GlowGrain>) -> Option<wgpu::Texture> {
|
||||
let (samples, opacity) = paint.gradient_samples(GRADIENT_SAMPLES as usize)?;
|
||||
let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
|
||||
let samples = self.row_texture(wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
let samples = self.row_texture("vello_effects_gradient", wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
|
||||
let parameters = Parameters {
|
||||
values: [if fades { 1. } else { 0. }, GRADIENT_GLOW_FADE as f32, opacity, grain.map_or(0., |grain| grain.amounts[0] as f32)],
|
||||
@@ -1678,17 +1673,27 @@ impl PassRecorder<'_> {
|
||||
let samples: Vec<half::f16> = (0..CONTOUR_SAMPLES)
|
||||
.map(|index| half::f16::from_f64(contour.evaluate(index as f64 / (CONTOUR_SAMPLES - 1) as f64).clamp(0., 1.)))
|
||||
.collect();
|
||||
self.row_texture(COVERAGE_FORMAT, CONTOUR_SAMPLES, bytemuck::cast_slice(&samples))
|
||||
self.row_texture("vello_effects_contour", COVERAGE_FORMAT, CONTOUR_SAMPLES, bytemuck::cast_slice(&samples))
|
||||
}
|
||||
|
||||
/// A texture one row of `width` texels tall holding `data` in the `format`, for shaders to interpolate between its samples.
|
||||
fn row_texture(&mut self, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture {
|
||||
/// It's made fresh rather than pooled, since its upload runs ahead of the passes recorded before it that a pooled texture may still serve.
|
||||
fn row_texture(&mut self, label: &str, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture {
|
||||
let extent = wgpu::Extent3d {
|
||||
width,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = self.executor.request_texture_with_format(UVec2::new(width, 1), format);
|
||||
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: extent,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
self.queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
@@ -1704,9 +1709,7 @@ impl PassRecorder<'_> {
|
||||
},
|
||||
extent,
|
||||
);
|
||||
let row = (*texture).clone();
|
||||
self.textures.held.push(texture);
|
||||
row
|
||||
texture
|
||||
}
|
||||
|
||||
/// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 (times the Blend If weight if any) fades the content that shows over it.
|
||||
@@ -1915,7 +1918,7 @@ impl PassRecorder<'_> {
|
||||
/// The image (of any format a shader can load from) with a pass of adjustments carried out on it into a texture of `format`, reading what was `prepared` for the pass,
|
||||
/// in the `encodings` of its source and result.
|
||||
fn adjust(&mut self, image: &wgpu::Texture, prepared: &PreparedPass, format: wgpu::TextureFormat, encodings: PassEncodings) -> wgpu::Texture {
|
||||
let target = self.textures.acquire(self.executor, self.size, format);
|
||||
let target = self.textures.acquire(self.device, self.size, format);
|
||||
|
||||
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.adjust_into(&view(&target), format, &view(image), prepared, encodings);
|
||||
@@ -2011,11 +2014,11 @@ impl PassRecorder<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Textures for the effect passes and the content they work on, taken from the texture pool and held until the render ends.
|
||||
/// Textures for the effect passes and the content they work on, kept between renders for reuse at the same sizes.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct EffectTextures {
|
||||
held: Vec<Texture>,
|
||||
released: Vec<wgpu::Texture>,
|
||||
/// Each unused texture with the render it was last used in.
|
||||
free: Vec<(wgpu::Texture, u64)>,
|
||||
/// The uploads of recent runs of adjustments.
|
||||
adjustments: AdjustmentUploads,
|
||||
render_count: u64,
|
||||
@@ -2026,32 +2029,43 @@ pub(crate) struct EffectTextures {
|
||||
|
||||
impl EffectTextures {
|
||||
/// What each pass carrying out a run of adjustments reads, as [`AdjustmentUploads::prepare`] gives it.
|
||||
pub(crate) fn prepare_adjustments(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec<PreparedPass> {
|
||||
self.adjustments.prepare(executor, queue, run, self.render_count, &mut self.held)
|
||||
pub(crate) fn prepare_adjustments(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec<PreparedPass> {
|
||||
self.adjustments.prepare(device, queue, run, self.render_count)
|
||||
}
|
||||
|
||||
pub(crate) fn acquire(&mut self, executor: &WgpuExecutor, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture {
|
||||
pub(crate) fn acquire(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture {
|
||||
let size = size.max(UVec2::ONE);
|
||||
let matches = |texture: &wgpu::Texture| texture.width() == size.x && texture.height() == size.y && texture.format() == format;
|
||||
if let Some(index) = self.released.iter().position(matches) {
|
||||
return self.released.swap_remove(index);
|
||||
if let Some(index) = self.free.iter().position(|(texture, _)| matches(texture)) {
|
||||
return self.free.swap_remove(index).0;
|
||||
}
|
||||
|
||||
let texture = executor.request_texture_with_format(size, format);
|
||||
let acquired = (*texture).clone();
|
||||
self.held.push(texture);
|
||||
acquired
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_effects_texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: size.x,
|
||||
height: size.y,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns a texture to the pool once the passes recorded so far are done with it, since later passes are recorded and submitted after them.
|
||||
pub(crate) fn release(&mut self, texture: wgpu::Texture) {
|
||||
self.released.push(texture);
|
||||
self.free.push((texture, self.render_count));
|
||||
}
|
||||
|
||||
/// Frees the textures no recent render has used.
|
||||
pub(crate) fn finish_render(&mut self) {
|
||||
self.released.clear();
|
||||
self.held.clear();
|
||||
self.adjustments.finish_render(self.render_count);
|
||||
let render_count = self.render_count;
|
||||
self.free.retain(|(_, last_used)| render_count - last_used < UNUSED_TEXTURE_RENDER_LIMIT);
|
||||
self.adjustments.finish_render(render_count);
|
||||
|
||||
self.render_count += 1;
|
||||
}
|
||||
@@ -2094,10 +2108,7 @@ mod tests {
|
||||
use core_types::list::Item;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let passes = EffectPasses::new(&context.device, &context.adapter);
|
||||
if !passes.renders_working_formats {
|
||||
return;
|
||||
@@ -2135,12 +2146,12 @@ mod tests {
|
||||
let effects = Effects::from_operations(operations);
|
||||
|
||||
let mut textures = EffectTextures::default();
|
||||
let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let queue = context.queue.lock();
|
||||
let apply = |textures: &mut EffectTextures, effects: &Effects| {
|
||||
textures.drawn_passes.clear();
|
||||
let layers = EffectLayers::plan(effects, BlendMode::Normal, 1., false);
|
||||
let results = passes.apply(&executor, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
};
|
||||
let draw = |textures: &mut EffectTextures| {
|
||||
@@ -2162,7 +2173,7 @@ mod tests {
|
||||
textures.drawn_passes.clear();
|
||||
let effects = Effects::from_operations(operations);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, false);
|
||||
let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
textures.drawn_passes.clone()
|
||||
};
|
||||
@@ -2193,10 +2204,7 @@ mod tests {
|
||||
fn effects_blending_normally_at_a_full_fill_take_no_more_passes_when_layered() {
|
||||
use graphic_types::effects::EffectKind;
|
||||
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let passes = EffectPasses::new(&context.device, &context.adapter);
|
||||
if !passes.renders_working_formats {
|
||||
return;
|
||||
@@ -2204,12 +2212,12 @@ mod tests {
|
||||
|
||||
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::DropShadow), EffectOperation::default_for(EffectKind::InnerShadow)]);
|
||||
let mut textures = EffectTextures::default();
|
||||
let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let queue = context.queue.lock();
|
||||
let mut drawn = |layered: bool| {
|
||||
textures.drawn_passes.clear();
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., layered);
|
||||
let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
textures.drawn_passes.clone()
|
||||
};
|
||||
@@ -2220,10 +2228,7 @@ mod tests {
|
||||
fn a_bevel_without_a_gloss_contour_or_texture_lights_its_highlight_and_shadow_directly() {
|
||||
use graphic_types::effects::EffectKind;
|
||||
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let passes = EffectPasses::new(&context.device, &context.adapter);
|
||||
if !passes.renders_working_formats {
|
||||
return;
|
||||
@@ -2231,10 +2236,10 @@ mod tests {
|
||||
|
||||
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::BevelAndEmboss)]);
|
||||
let mut textures = EffectTextures::default();
|
||||
let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let queue = context.queue.lock();
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
|
||||
let drawn = |label: &str| textures.drawn_passes.iter().filter(|&&drawn| drawn == label).count();
|
||||
@@ -2243,10 +2248,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_table_stays_uploaded_while_the_settings_beside_it_change() {
|
||||
let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
|
||||
return;
|
||||
};
|
||||
let context = executor.context();
|
||||
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return };
|
||||
let queue = context.queue.lock();
|
||||
|
||||
let lookup = Adjustment::ColorLookup {
|
||||
@@ -2256,7 +2258,7 @@ mod tests {
|
||||
let prepare = |textures: &mut EffectTextures, posterize_levels| {
|
||||
let posterize = Adjustment::Posterize { levels: posterize_levels };
|
||||
// Color Lookup's pass and then Posterize's, which share the run's tables
|
||||
let mut prepared = textures.prepare_adjustments(&executor, &queue, &[&lookup, &posterize]);
|
||||
let mut prepared = textures.prepare_adjustments(&context.device, &queue, &[&lookup, &posterize]);
|
||||
prepared.pop().map(|prepared| (prepared.steps, prepared.tables))
|
||||
};
|
||||
|
||||
@@ -2268,13 +2270,11 @@ mod tests {
|
||||
panic!("The run reads its table")
|
||||
};
|
||||
assert!(first_steps == again_steps && first_table == again_table);
|
||||
let Some((other_steps, _)) = prepare(&mut textures, 5) else { panic!("The run reads its table") };
|
||||
assert!(other_steps != first_steps);
|
||||
for levels in 5..20 {
|
||||
let Some((_, Some(table))) = prepare(&mut textures, levels) else {
|
||||
let Some((steps, Some(table))) = prepare(&mut textures, levels) else {
|
||||
panic!("The run reads its table")
|
||||
};
|
||||
assert!(table == first_table);
|
||||
assert!(steps != first_steps && table == first_table);
|
||||
textures.finish_render();
|
||||
}
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ impl PassRecorder<'_> {
|
||||
})
|
||||
.map(half::f16::from_f32)
|
||||
.collect();
|
||||
let table = self.row_texture(wgpu::TextureFormat::Rgba16Float, 256, bytemuck::cast_slice(&blends));
|
||||
let table = self.row_texture("vello_effects_masked_radius_blur", wgpu::TextureFormat::Rgba16Float, 256, bytemuck::cast_slice(&blends));
|
||||
let interpolation = self.run("masked_radius_blur_interpolation", WORKING_FORMAT, self.size, luminance, Some(&table), None, Parameters::default());
|
||||
|
||||
if full_is_read && let Some(blurred) = self.masked_radius_blur_image(full.as_ref().unwrap_or(content), &interpolation, levels, linear) {
|
||||
|
||||
@@ -74,7 +74,7 @@ impl PassRecorder<'_> {
|
||||
return band;
|
||||
};
|
||||
let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
|
||||
let samples = self.row_texture(wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
let samples = self.row_texture("vello_effects_gradient", wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
|
||||
let parameters = Parameters {
|
||||
amount: opacity,
|
||||
|
||||
@@ -40,7 +40,7 @@ impl PassRecorder<'_> {
|
||||
let vertices = 12 * (columns + rows) + 24 + 6 * columns * rows;
|
||||
|
||||
let format = texture.format();
|
||||
let warped = self.textures.acquire(self.executor, self.size, format);
|
||||
let warped = self.textures.acquire(self.device, self.size, format);
|
||||
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let reading = self.passes.bind_group(self.device, self.size, &view(&texture), None, None, parameters);
|
||||
let mesh = (self.passes).pipeline_with(self.device, "warp_vertex", "warp_effect", format, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING));
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
//! The GPU pass that renders tiles of generators' patterns, matching the CPU's renders of them.
|
||||
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_render::TEXTURE_FORMAT;
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use glam::{DVec2, UVec2};
|
||||
use glam::DVec2;
|
||||
use graphic_types::generator::{
|
||||
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseSettings, NoiseType,
|
||||
};
|
||||
use raster_kernels::mandelbrot::{MandelbrotSetup, ReferenceOrbit, resolves_in_32_bits};
|
||||
use raster_types::Texture;
|
||||
use std::iter::zip;
|
||||
use std::sync::OnceLock;
|
||||
use wgpu::util::DeviceExt;
|
||||
@@ -272,7 +270,7 @@ impl Tile {
|
||||
}
|
||||
|
||||
/// The texture holding a reference orbit's values and their raisings for the Mandelbrot shader, in rows of `REFERENCE_ROW_LENGTH`, or one empty texel without one.
|
||||
fn reference_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, reference: Option<&ReferenceOrbit>) -> Texture {
|
||||
fn reference_texture(device: &wgpu::Device, queue: &wgpu::Queue, reference: Option<&ReferenceOrbit>) -> wgpu::Texture {
|
||||
let (values, raised_values) = reference.map_or((&[][..], &[][..]), |reference| (&reference.values[..], &reference.raised_values[..]));
|
||||
let (width, height) = (values.len().clamp(1, REFERENCE_ROW_LENGTH), values.len().div_ceil(REFERENCE_ROW_LENGTH).max(1));
|
||||
|
||||
@@ -281,18 +279,25 @@ fn reference_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, reference: Op
|
||||
*texel = [value.x, value.y, raised.x, raised.y];
|
||||
}
|
||||
|
||||
let texture = executor.request_texture_with_format(UVec2::new(width as u32, height as u32), wgpu::TextureFormat::Rgba32Float);
|
||||
queue.write_texture(
|
||||
texture.as_image_copy(),
|
||||
bytemuck::cast_slice(&texels),
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(width as u32 * size_of::<[f32; 4]>() as u32),
|
||||
rows_per_image: Some(height as u32),
|
||||
device.create_texture_with_data(
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("vello_generator_reference_orbit"),
|
||||
size: wgpu::Extent3d {
|
||||
width: width as u32,
|
||||
height: height as u32,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba32Float,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
},
|
||||
texture.size(),
|
||||
);
|
||||
texture
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
bytemuck::cast_slice(&texels),
|
||||
)
|
||||
}
|
||||
|
||||
/// The pipelines of the pass, one for each shader.
|
||||
@@ -381,24 +386,26 @@ impl GeneratorPasses {
|
||||
}
|
||||
|
||||
/// A texture for square tiles `pixels` across to be rendered into, with the mip levels they're drawn from.
|
||||
pub(crate) fn tile_texture(executor: &WgpuExecutor, pixels: u32) -> Texture {
|
||||
executor.request_texture_with_mips(UVec2::splat(pixels), TEXTURE_FORMAT, TILE_MIP_LEVELS)
|
||||
pub(crate) fn tile_texture(device: &wgpu::Device, pixels: u32) -> wgpu::Texture {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_generator_tile"),
|
||||
size: wgpu::Extent3d {
|
||||
width: pixels,
|
||||
height: pixels,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: TILE_MIP_LEVELS,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
|
||||
/// Records the rendering of a square tile of `pattern` into the top mip level of `texture`, with its top left corner at `corner` of the pattern's space and pixels `texel` units across.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn render_tile(
|
||||
&self,
|
||||
executor: &WgpuExecutor,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
held: &mut Vec<Texture>,
|
||||
texture: &wgpu::Texture,
|
||||
pattern: &GeneratorPattern,
|
||||
corner: DVec2,
|
||||
texel: f64,
|
||||
) {
|
||||
let device = &executor.context().device;
|
||||
pub(crate) fn render_tile(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture, pattern: &GeneratorPattern, corner: DVec2, texel: f64) {
|
||||
let tile = Tile::new(pattern, corner, texel, texture.width());
|
||||
let (pipeline, bind_group_layout) = self.pipeline(device, tile.shader);
|
||||
|
||||
@@ -407,12 +414,7 @@ impl GeneratorPasses {
|
||||
contents: &tile.parameters,
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
let reference_view = (tile.shader == Shader::Mandelbrot).then(|| {
|
||||
let reference = reference_texture(executor, queue, tile.reference.as_ref());
|
||||
let view = reference.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(reference);
|
||||
view
|
||||
});
|
||||
let reference_view = (tile.shader == Shader::Mandelbrot).then(|| reference_texture(device, queue, tile.reference.as_ref()).create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
let mut entries = vec![wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::WgpuExecutor;
|
||||
use crate::vello_adjustments::adjustment_run_hash;
|
||||
use crate::vello_effects::{EffectPasses, EffectTextures};
|
||||
use crate::vello_generators::GeneratorPasses;
|
||||
@@ -6,7 +5,7 @@ use core_types::blending::BlendMode;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graphic_types::effect_layers::EffectLayers;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::raster_types::{CPU, Image, Raster, Texture, TextureWeakRef, WeakCPU};
|
||||
use graphic_types::raster_types::{CPU, Image, Raster, WeakCPU};
|
||||
use graphic_types::{Adjustment, Effects};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use std::collections::HashMap;
|
||||
@@ -26,6 +25,12 @@ pub(crate) const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba
|
||||
/// 16-bit unorm comes first for holding every 8-bit level exactly, unlike half floats.
|
||||
const PRECISE_FORMATS: &[wgpu::TextureFormat] = &[wgpu::TextureFormat::Rgba16Unorm, wgpu::TextureFormat::Rgba16Float];
|
||||
|
||||
/// How many renders a GPU texture's premultiplied copy survives without being drawn before it is freed.
|
||||
const UNUSED_IMAGE_RENDER_LIMIT: u64 = 60;
|
||||
|
||||
/// About the most tiles of generators kept between renders, past which the least recently drawn are freed. Tiles drawn in the same render are kept or freed together.
|
||||
const MAX_CACHED_GENERATOR_TILES: usize = 256;
|
||||
|
||||
/// How many times a render with too much content for Vello GPU is halved, reaching areas 1/4096 the size of the original.
|
||||
const MAX_SPLIT_DEPTH: u32 = 12;
|
||||
|
||||
@@ -49,6 +54,8 @@ pub(crate) struct VelloRenderer {
|
||||
pub struct VelloCanvas {
|
||||
/// Scenes to draw into, one for each depth of effects groups nested in a render, reused between renders to keep their allocations.
|
||||
spare_scenes: Vec<vello_gpu::Scene>,
|
||||
/// The premultiplied texture Vello GPU renders into before conversion to straight alpha, kept while the render size stays the same.
|
||||
premultiplied_target: Option<wgpu::Texture>,
|
||||
images: ImageTextures,
|
||||
effect_textures: EffectTextures,
|
||||
}
|
||||
@@ -64,7 +71,8 @@ enum TargetAlpha {
|
||||
struct RenderContext<'a> {
|
||||
renderer: &'a VelloRenderer,
|
||||
canvas: &'a mut VelloCanvas,
|
||||
executor: &'a WgpuExecutor,
|
||||
device: &'a wgpu::Device,
|
||||
queue: &'a Queue,
|
||||
}
|
||||
|
||||
impl VelloRenderer {
|
||||
@@ -113,10 +121,12 @@ impl VelloRenderer {
|
||||
|
||||
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target` (an `Rgba8Unorm` texture of `size` with straight alpha).
|
||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(crate) fn render(
|
||||
&self,
|
||||
executor: &WgpuExecutor,
|
||||
canvas: &mut VelloCanvas,
|
||||
device: &wgpu::Device,
|
||||
queue: &Queue,
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
view: Affine,
|
||||
size: UVec2,
|
||||
@@ -127,7 +137,12 @@ impl VelloRenderer {
|
||||
}
|
||||
|
||||
canvas.images.render_count += 1;
|
||||
let mut context = RenderContext { renderer: self, canvas, executor };
|
||||
let mut context = RenderContext {
|
||||
renderer: self,
|
||||
canvas,
|
||||
device,
|
||||
queue,
|
||||
};
|
||||
context.render_area(draw, view, size, target, TargetAlpha::Straight);
|
||||
canvas.images.free_unused();
|
||||
canvas.effect_textures.finish_render();
|
||||
@@ -137,30 +152,25 @@ impl VelloRenderer {
|
||||
|
||||
/// Renders a `scene` drawn beforehand on `canvas` into `target` (an `Rgba8Unorm` texture of the scene's size with straight alpha).
|
||||
/// Unlike [`Self::render`], it can't split the scene, so one with more content than Vello GPU can hold renders transparent.
|
||||
pub(crate) fn render_scene(&self, executor: &WgpuExecutor, canvas: &mut VelloCanvas, scene: VelloSceneBuilder, target: &wgpu::Texture) {
|
||||
pub(crate) fn render_scene(&self, canvas: &mut VelloCanvas, device: &wgpu::Device, queue: &Queue, scene: VelloSceneBuilder, target: &wgpu::Texture) {
|
||||
canvas.images.render_count += 1;
|
||||
let max_texture_size = scene.max_texture_size();
|
||||
let mut context = RenderContext { renderer: self, canvas, executor };
|
||||
let mut context = RenderContext {
|
||||
renderer: self,
|
||||
canvas,
|
||||
device,
|
||||
queue,
|
||||
};
|
||||
let (scene, images) = scene.finish();
|
||||
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) {
|
||||
log::error!("Vello GPU failed to render: {error}");
|
||||
clear(&executor.context().device, &executor.context().queue, target);
|
||||
clear(device, queue, target);
|
||||
}
|
||||
canvas.images.free_unused();
|
||||
canvas.effect_textures.finish_render();
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> RenderContext<'a> {
|
||||
fn device(&self) -> &'a wgpu::Device {
|
||||
&self.executor.context().device
|
||||
}
|
||||
|
||||
fn queue(&self) -> &'a Queue {
|
||||
&self.executor.context().queue
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderContext<'_> {
|
||||
/// Renders the scene `draw` draws into `target`, a texture of `size`, splitting its area into halves while it holds more content than one render can.
|
||||
fn render_area(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) {
|
||||
@@ -172,7 +182,7 @@ impl RenderContext<'_> {
|
||||
/// Renders each half of the area of `target`, a texture of `size`, after rendering it whole failed with `error`, splitting again each half that still holds too much.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_halves(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha, error: RenderError, split_depth: u32) {
|
||||
let (device, queue) = (self.device(), self.queue());
|
||||
let (device, queue) = (self.device, self.queue);
|
||||
|
||||
// Each half covers less of the scene, so it has less content and smaller layers to hold
|
||||
let too_much_to_hold = matches!(
|
||||
@@ -193,9 +203,14 @@ impl RenderContext<'_> {
|
||||
let top = size.y / 2;
|
||||
[(UVec2::ZERO, UVec2::new(size.x, top)), (UVec2::new(0, top), UVec2::new(size.x, size.y - top))]
|
||||
};
|
||||
let executor = self.executor;
|
||||
let halves = halves.map(|(offset, half_size)| {
|
||||
let half_target = executor.request_texture_with_format(half_size, target.format());
|
||||
let half_target = create_texture(
|
||||
device,
|
||||
"vello_gpu_split_target",
|
||||
half_size,
|
||||
target.format(),
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
|
||||
);
|
||||
let half_view = Affine::translate((-(offset.x as f64), -(offset.y as f64))) * view;
|
||||
let rendered = self.render_once(draw, half_view, half_size, &half_target, target_alpha);
|
||||
(offset, half_size, half_view, half_target, rendered)
|
||||
@@ -239,7 +254,7 @@ impl RenderContext<'_> {
|
||||
|
||||
/// Renders the scene `draw` draws into `target`, a texture of `size`, in a single Vello GPU render.
|
||||
fn render_once(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> {
|
||||
let max_texture_size = self.device().limits().max_texture_dimension_2d;
|
||||
let max_texture_size = self.device.limits().max_texture_dimension_2d;
|
||||
let max_size = max_texture_size.min(u16::MAX as u32);
|
||||
let (mut scene, mut images, apron) = self.draw_scene(draw, view, size, max_texture_size, largest_apron(size, max_size));
|
||||
|
||||
@@ -251,11 +266,17 @@ impl RenderContext<'_> {
|
||||
let grown_view = Affine::translate((apron as f64, apron as f64)) * view;
|
||||
let (scene, images, _) = self.draw_scene(draw, grown_view, grown_size, max_texture_size, 0);
|
||||
|
||||
let grown_target = self.executor.request_texture_with_format(grown_size, target.format());
|
||||
let grown_target = create_texture(
|
||||
self.device,
|
||||
"vello_gpu_grown_target",
|
||||
grown_size,
|
||||
target.format(),
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
|
||||
);
|
||||
let rendered = self.submit(&scene, images, max_texture_size, &grown_target, target_alpha, true);
|
||||
self.canvas.spare_scenes.push(scene);
|
||||
|
||||
let mut encoder = self.device().create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_grown_copy") });
|
||||
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_grown_copy") });
|
||||
encoder.copy_texture_to_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
origin: wgpu::Origin3d { x: apron, y: apron, z: 0 },
|
||||
@@ -268,7 +289,7 @@ impl RenderContext<'_> {
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
self.queue().submit([encoder.finish()]);
|
||||
self.queue.submit([encoder.finish()]);
|
||||
return rendered;
|
||||
}
|
||||
|
||||
@@ -313,34 +334,23 @@ impl RenderContext<'_> {
|
||||
/// Renders a drawn scene, with the images it draws, into `target`, a texture of the scene's size, in a single Vello GPU render.
|
||||
/// The effects results it draws are freed for reuse after it, even if it fails when `release_failed`.
|
||||
fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec<SceneImage>, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha, release_failed: bool) -> Result<(), RenderError> {
|
||||
let device = self.device();
|
||||
let device = self.device;
|
||||
let (width, height) = (scene.width(), scene.height());
|
||||
let size = UVec2::new(width as u32, height as u32);
|
||||
|
||||
// Locked from here to the submission, so drawing a scene doesn't hold up other uses of the queue
|
||||
let queue = self.queue().lock();
|
||||
let queue = self.queue.lock();
|
||||
|
||||
// Each render submits its own encoder, since Vello GPU stages its uploads for the next submission
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_render") });
|
||||
|
||||
// Supply the textures of the images the scene draws, under the IDs it drew them with
|
||||
let mut texture_bindings = TextureBindings::new();
|
||||
let mut held = Vec::new();
|
||||
for (id, image) in images.iter().enumerate() {
|
||||
let view = match image {
|
||||
SceneImage::Texture(source) => {
|
||||
let premultiplied = self.executor.request_texture(UVec2::new(source.width(), source.height()));
|
||||
let view = premultiplied.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.renderer.alpha_conversion.premultiply(device, &mut encoder, &source_view, source.format().is_srgb(), &view);
|
||||
held.push(premultiplied);
|
||||
Some(view)
|
||||
}
|
||||
_ => self
|
||||
.canvas
|
||||
.images
|
||||
.prepare(self.executor, &queue, &mut encoder, &mut self.canvas.effect_textures, self.renderer, image, max_texture_size, &mut held),
|
||||
};
|
||||
let view = self
|
||||
.canvas
|
||||
.images
|
||||
.prepare(device, &queue, &mut encoder, &mut self.canvas.effect_textures, self.renderer, image, max_texture_size);
|
||||
|
||||
// Adjustments draw a copy of the texture they're carried out on
|
||||
let view = match image {
|
||||
@@ -348,7 +358,7 @@ impl RenderContext<'_> {
|
||||
let effects = (&self.renderer.effect_passes, &mut self.canvas.effect_textures);
|
||||
self.canvas
|
||||
.images
|
||||
.prepare_adjusted(self.executor, &queue, effects, raster, adjustments, max_texture_size, self.renderer.precise_format, &mut held)
|
||||
.prepare_adjusted(device, &queue, effects, raster, adjustments, max_texture_size, self.renderer.precise_format)
|
||||
}),
|
||||
_ => view,
|
||||
};
|
||||
@@ -360,10 +370,21 @@ impl RenderContext<'_> {
|
||||
|
||||
// Vello GPU renders premultiplied, which is converted to straight alpha unless the target wants it premultiplied
|
||||
let target_view = target.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let premultiplied_target = (target_alpha == TargetAlpha::Straight).then(|| self.executor.request_texture(size));
|
||||
let premultiplied_view = match &premultiplied_target {
|
||||
Some(texture) => texture.create_view(&wgpu::TextureViewDescriptor::default()),
|
||||
None => target_view.clone(),
|
||||
let premultiplied_view = match (target_alpha, &self.canvas.premultiplied_target) {
|
||||
(TargetAlpha::Premultiplied, _) => target_view.clone(),
|
||||
(TargetAlpha::Straight, Some(texture)) if texture.width() == size.x && texture.height() == size.y => texture.create_view(&wgpu::TextureViewDescriptor::default()),
|
||||
(TargetAlpha::Straight, _) => {
|
||||
let texture = create_texture(
|
||||
device,
|
||||
"vello_gpu_premultiplied_target",
|
||||
size,
|
||||
TEXTURE_FORMAT,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
);
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.canvas.premultiplied_target = Some(texture);
|
||||
view
|
||||
}
|
||||
};
|
||||
let target_init = TargetInit::Clear(ClearSettings::Viewport { color: peniko::Color::TRANSPARENT });
|
||||
|
||||
@@ -424,24 +445,24 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) -> Vec<(wgpu::Texture, BlendMode)> {
|
||||
let content_texture = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
|
||||
let content_texture = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format);
|
||||
self.render_area(draw, view, size, &content_texture, TargetAlpha::Premultiplied);
|
||||
|
||||
// The effects' drawn paints, each rendered over the same pixels as the content
|
||||
let paint_count = effects.operations().map(|operation| operation.drawn_paints().count()).sum();
|
||||
let paint_textures: Vec<wgpu::Texture> = (0..paint_count)
|
||||
.map(|index| {
|
||||
let paint_texture = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
|
||||
let paint_texture = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format);
|
||||
self.render_area(&mut |scene| draw_paint(index, scene), view, size, &paint_texture, TargetAlpha::Premultiplied);
|
||||
paint_texture
|
||||
})
|
||||
.collect();
|
||||
|
||||
let queue = self.queue().lock();
|
||||
let effect_textures = &mut self.canvas.effect_textures;
|
||||
let queue = self.queue.lock();
|
||||
let effect_passes = &self.renderer.effect_passes;
|
||||
let results = effect_passes.apply(
|
||||
self.executor,
|
||||
self.device,
|
||||
&queue,
|
||||
effect_textures,
|
||||
&content_texture,
|
||||
@@ -463,7 +484,7 @@ impl EffectsRenderer for RenderContext<'_> {
|
||||
|
||||
fn render_backdrop(&mut self, scene: &vello_gpu::Scene, images: &[SceneImage], max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
let size = UVec2::new(scene.width() as u32, scene.height() as u32);
|
||||
let backdrop = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
|
||||
let backdrop = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format);
|
||||
|
||||
// A failed render leaves the scene to go on drawing what it drew, so the results it draws stay in use
|
||||
match self.submit(scene, images.to_vec(), max_texture_size, &backdrop, TargetAlpha::Premultiplied, false) {
|
||||
@@ -494,117 +515,122 @@ fn clear(device: &wgpu::Device, queue: &Queue, target: &wgpu::Texture) {
|
||||
queue.submit([encoder.finish()]);
|
||||
}
|
||||
|
||||
/// Identifies the pixels behind an image texture: a blob of CPU pixels or a CPU raster.
|
||||
/// Identifies the pixels behind an image texture: a blob of CPU pixels, a GPU texture, or a tile of a generator's pattern.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
enum ImageKey {
|
||||
Blob(u64),
|
||||
Raster(u64),
|
||||
Texture(wgpu::Texture),
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
/// A premultiplied copy of an image's pixels that Vello GPU samples as an external texture.
|
||||
struct ImageTexture {
|
||||
texture: TextureWeakRef,
|
||||
texture: wgpu::Texture,
|
||||
last_used: u64,
|
||||
/// The CPU raster pixels copied into the texture, which is freed once they're gone since they can't be drawn again.
|
||||
raster: Option<WeakCPU>,
|
||||
/// Copies with runs of adjustments carried out on them, one for each run the image is drawn with.
|
||||
adjusted: Vec<AdjustedTexture>,
|
||||
/// The raster's straight linear colors in 32-bit floats that adjustments are carried out from, kept while any adjusted copy is.
|
||||
adjustment_source: Option<TextureWeakRef>,
|
||||
adjustment_source: Option<wgpu::Texture>,
|
||||
}
|
||||
|
||||
/// A copy of an image's texture with a run of adjustments carried out on it, made over for another run.
|
||||
/// A copy of an image's texture with a run of adjustments carried out on it, made over in place for another run.
|
||||
struct AdjustedTexture {
|
||||
texture: TextureWeakRef,
|
||||
run_hash: u64,
|
||||
texture: wgpu::Texture,
|
||||
/// The hash of the run carried out on it, or `None` until one is.
|
||||
run_hash: Option<u64>,
|
||||
last_used: u64,
|
||||
}
|
||||
|
||||
/// The textures of the images recent renders drew, parked in the texture pool between renders.
|
||||
/// The textures of the images recent renders drew, each freed once it goes unused for long enough.
|
||||
#[derive(Default)]
|
||||
struct ImageTextures {
|
||||
textures: HashMap<ImageKey, ImageTexture>,
|
||||
generator_tiles: HashMap<GeneratorTile, TextureWeakRef>,
|
||||
/// The textures of the generator tiles the last render freed, for its next render's new tiles to take over, as when changing a generator's settings replaces every tile.
|
||||
spare_generator_tiles: Vec<wgpu::Texture>,
|
||||
render_count: u64,
|
||||
}
|
||||
|
||||
impl ImageTextures {
|
||||
/// A view of the premultiplied texture for `image`, uploading CPU pixels or rendering a generator's tile the first time they're drawn.
|
||||
/// GPU textures are converted again at every render since the texture cache hands their textures out again with new contents.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn prepare(
|
||||
&mut self,
|
||||
executor: &WgpuExecutor,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
effect_textures: &mut EffectTextures,
|
||||
renderer: &VelloRenderer,
|
||||
image: &SceneImage,
|
||||
max_texture_size: u32,
|
||||
held: &mut Vec<Texture>,
|
||||
) -> Option<wgpu::TextureView> {
|
||||
let key = match image {
|
||||
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
|
||||
SceneImage::Raster { raster, .. } => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::GeneratorTile { pattern, tile } => {
|
||||
let texture = match self.generator_tiles.get(tile).and_then(TextureWeakRef::upgrade) {
|
||||
Some(texture) => texture,
|
||||
None => {
|
||||
let texture = GeneratorPasses::tile_texture(executor, GeneratorTile::SAMPLES);
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
renderer.generator_passes.render_tile(executor, queue, encoder, held, &texture, pattern, corner, texel);
|
||||
renderer.effect_passes.record_mipmaps(executor, encoder, effect_textures, &texture);
|
||||
self.generator_tiles.insert(*tile, texture.downgrade());
|
||||
texture
|
||||
}
|
||||
};
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(texture);
|
||||
return Some(view);
|
||||
}
|
||||
SceneImage::Texture(texture) => ImageKey::Texture((**texture).clone()),
|
||||
SceneImage::GeneratorTile { tile, .. } => ImageKey::GeneratorTile(*tile),
|
||||
// Effects results are premultiplied already
|
||||
SceneImage::Rendered(texture) => return Some(texture.create_view(&wgpu::TextureViewDescriptor::default())),
|
||||
SceneImage::Texture(_) => return None,
|
||||
};
|
||||
|
||||
let texture = match self.textures.get(&key).and_then(|image_texture| image_texture.texture.upgrade()) {
|
||||
Some(texture) => texture,
|
||||
None => {
|
||||
let texture = match image {
|
||||
SceneImage::Pixels(data) => {
|
||||
if data.format != peniko::ImageFormat::Rgba8 {
|
||||
log::error!("Unsupported image format {:?}", data.format);
|
||||
return None;
|
||||
}
|
||||
|
||||
upload_pixels(executor, queue, data.data.data(), data.width, data.height, data.alpha_type, max_texture_size)?
|
||||
if !self.textures.contains_key(&key) {
|
||||
let texture = match image {
|
||||
SceneImage::Pixels(data) => {
|
||||
if data.format != peniko::ImageFormat::Rgba8 {
|
||||
log::error!("Unsupported image format {:?}", data.format);
|
||||
return None;
|
||||
}
|
||||
SceneImage::Raster { raster, .. } => {
|
||||
let (pixels, width, height) = raster.to_flat_u8();
|
||||
upload_pixels(executor, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
SceneImage::Rendered(_) | SceneImage::Texture(_) | SceneImage::GeneratorTile { .. } => return None,
|
||||
};
|
||||
let raster = match image {
|
||||
SceneImage::Raster { raster, .. } => Some(raster.downgrade()),
|
||||
SceneImage::Pixels(_) | SceneImage::Texture(_) | SceneImage::Rendered(_) | SceneImage::GeneratorTile { .. } => None,
|
||||
};
|
||||
self.textures.insert(
|
||||
key.clone(),
|
||||
ImageTexture {
|
||||
texture: texture.downgrade(),
|
||||
last_used: 0,
|
||||
raster,
|
||||
adjusted: Vec::new(),
|
||||
adjustment_source: None,
|
||||
},
|
||||
);
|
||||
texture
|
||||
}
|
||||
};
|
||||
|
||||
self.textures.get_mut(&key)?.last_used = self.render_count;
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(texture);
|
||||
upload_pixels(device, queue, data.data.data(), data.width, data.height, data.alpha_type, max_texture_size)?
|
||||
}
|
||||
SceneImage::Raster { raster, .. } => {
|
||||
let (pixels, width, height) = raster.to_flat_u8();
|
||||
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
SceneImage::GeneratorTile { pattern, tile } => {
|
||||
let texture = (self.spare_generator_tiles.pop()).unwrap_or_else(|| GeneratorPasses::tile_texture(device, GeneratorTile::SAMPLES));
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
renderer.generator_passes.render_tile(device, queue, encoder, &texture, pattern, corner, texel);
|
||||
renderer.effect_passes.record_mipmaps(device, encoder, effect_textures, &texture);
|
||||
texture
|
||||
}
|
||||
SceneImage::Rendered(_) => return None,
|
||||
SceneImage::Texture(texture) => create_texture(
|
||||
device,
|
||||
"vello_gpu_premultiplied_image",
|
||||
UVec2::new(texture.width(), texture.height()),
|
||||
TEXTURE_FORMAT,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
),
|
||||
};
|
||||
let raster = match image {
|
||||
SceneImage::Raster { raster, .. } => Some(raster.downgrade()),
|
||||
SceneImage::Pixels(_) | SceneImage::Texture(_) | SceneImage::Rendered(_) | SceneImage::GeneratorTile { .. } => None,
|
||||
};
|
||||
self.textures.insert(
|
||||
key.clone(),
|
||||
ImageTexture {
|
||||
texture,
|
||||
last_used: 0,
|
||||
raster,
|
||||
adjusted: Vec::new(),
|
||||
adjustment_source: None,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let image_texture = self.textures.get_mut(&key)?;
|
||||
image_texture.last_used = self.render_count;
|
||||
let view = image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
if let SceneImage::Texture(source) = image {
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
renderer.alpha_conversion.premultiply(device, encoder, &source_view, source.format().is_srgb(), &view);
|
||||
}
|
||||
|
||||
Some(view)
|
||||
}
|
||||
|
||||
@@ -612,38 +638,30 @@ impl ImageTextures {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn prepare_adjusted(
|
||||
&mut self,
|
||||
executor: &WgpuExecutor,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
effects: (&EffectPasses, &mut EffectTextures),
|
||||
raster: &Raster<CPU>,
|
||||
run: &[Adjustment],
|
||||
max_texture_size: u32,
|
||||
precise_format: wgpu::TextureFormat,
|
||||
held: &mut Vec<Texture>,
|
||||
) -> Option<wgpu::TextureView> {
|
||||
let (effect_passes, effect_textures) = effects;
|
||||
let run: Vec<&Adjustment> = run.iter().collect();
|
||||
let run_hash = adjustment_run_hash(&run);
|
||||
let render_count = self.render_count;
|
||||
let image_texture = self.textures.get_mut(&ImageKey::Raster(raster.buffer_id()))?;
|
||||
let image = image_texture.texture.upgrade()?;
|
||||
|
||||
// A run seen before has its copy
|
||||
let seen = (image_texture.adjusted.iter_mut()).find(|copy| copy.run_hash == run_hash).and_then(|copy| {
|
||||
if let Some(copy) = image_texture.adjusted.iter_mut().find(|copy| copy.run_hash == Some(run_hash)) {
|
||||
copy.last_used = render_count;
|
||||
copy.texture.upgrade()
|
||||
});
|
||||
if let Some(copy) = seen {
|
||||
let view = copy.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(copy);
|
||||
return Some(view);
|
||||
return Some(copy.texture.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
}
|
||||
image_texture.adjusted.retain(|copy| copy.run_hash != run_hash);
|
||||
|
||||
// A run that changes no color draws the texture itself
|
||||
let prepared = effect_textures.prepare_adjustments(executor, queue, &run);
|
||||
let prepared = effect_textures.prepare_adjustments(device, queue, &run);
|
||||
if prepared.is_empty() {
|
||||
return Some(image.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
return Some(image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default()));
|
||||
}
|
||||
|
||||
// A new run takes over the copy longest unused, as when dragging a slider makes a new run every render
|
||||
@@ -651,59 +669,85 @@ impl ImageTextures {
|
||||
.filter(|(_, copy)| copy.last_used < render_count)
|
||||
.min_by_key(|(_, copy)| copy.last_used)
|
||||
.map(|(index, _)| index);
|
||||
if let Some(index) = reusable {
|
||||
image_texture.adjusted.swap_remove(index);
|
||||
}
|
||||
let copy = executor.request_texture_with_mips(UVec2::new(image.width(), image.height()), precise_format, image.mip_level_count());
|
||||
|
||||
// Adjusting the raster's own colors, rather than its 8-bit premultiplied texture, keeps faint colors from banding and steps landing as on the CPU
|
||||
let source = match image_texture.adjustment_source.as_ref().and_then(TextureWeakRef::upgrade) {
|
||||
Some(source) => Some(source),
|
||||
let index = match reusable {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
let source = upload_adjustment_source(executor, queue, raster.data(), max_texture_size);
|
||||
image_texture.adjustment_source = source.as_ref().map(Texture::downgrade);
|
||||
source
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_adjusted_image"),
|
||||
size: image_texture.texture.size(),
|
||||
mip_level_count: image_texture.texture.mip_level_count(),
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: precise_format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
image_texture.adjusted.push(AdjustedTexture {
|
||||
texture,
|
||||
run_hash: None,
|
||||
last_used: render_count,
|
||||
});
|
||||
image_texture.adjusted.len() - 1
|
||||
}
|
||||
};
|
||||
let (source, straight_linear) = match &source {
|
||||
|
||||
// Adjusting the raster's own colors, rather than its 8-bit premultiplied texture, keeps faint colors from banding and steps landing as on the CPU
|
||||
if image_texture.adjustment_source.is_none() {
|
||||
image_texture.adjustment_source = upload_adjustment_source(device, queue, raster.data(), max_texture_size);
|
||||
}
|
||||
let (source, straight_linear) = match &image_texture.adjustment_source {
|
||||
Some(source) => (source, true),
|
||||
None => (&image, false),
|
||||
None => (&image_texture.texture, false),
|
||||
};
|
||||
|
||||
effect_passes.adjust_image(executor, queue, effect_textures, source, straight_linear, &prepared, ©);
|
||||
image_texture.adjusted.push(AdjustedTexture {
|
||||
texture: copy.downgrade(),
|
||||
run_hash,
|
||||
last_used: render_count,
|
||||
});
|
||||
let copy = &mut image_texture.adjusted[index];
|
||||
effect_passes.adjust_image(device, queue, effect_textures, source, straight_linear, &prepared, ©.texture);
|
||||
copy.run_hash = Some(run_hash);
|
||||
copy.last_used = render_count;
|
||||
|
||||
let view = copy.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
held.push(copy);
|
||||
Some(view)
|
||||
Some(copy.texture.create_view(&wgpu::TextureViewDescriptor::default()))
|
||||
}
|
||||
|
||||
fn free_unused(&mut self) {
|
||||
let render_count = self.render_count;
|
||||
let in_use = |last_used: u64| render_count - last_used < UNUSED_IMAGE_RENDER_LIMIT;
|
||||
|
||||
let kept = |key: &ImageKey, image_texture: &ImageTexture| match key {
|
||||
// CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return
|
||||
ImageKey::Blob(_) => image_texture.last_used == render_count,
|
||||
ImageKey::Raster(_) => image_texture.last_used == render_count || image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive),
|
||||
ImageKey::Raster(_) => image_texture.last_used == render_count || (in_use(image_texture.last_used) && image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive)),
|
||||
ImageKey::Texture(_) | ImageKey::GeneratorTile(_) => in_use(image_texture.last_used),
|
||||
};
|
||||
|
||||
self.textures.retain(|key, image_texture| kept(key, image_texture) && image_texture.texture.upgrade().is_some());
|
||||
self.generator_tiles.retain(|_, texture| texture.upgrade().is_some());
|
||||
// Spares this render didn't take over are freed, and the tiles it freed become the next render's spares
|
||||
self.spare_generator_tiles.clear();
|
||||
let unused = self.textures.extract_if(|key, image_texture| !kept(key, image_texture));
|
||||
let unused_tiles = unused.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_))).map(|(_, image_texture)| image_texture.texture);
|
||||
self.spare_generator_tiles.extend(unused_tiles);
|
||||
|
||||
self.textures.values_mut().for_each(|image_texture| {
|
||||
image_texture.adjusted.retain(|copy| copy.texture.upgrade().is_some());
|
||||
image_texture.adjusted.retain(|copy| in_use(copy.last_used));
|
||||
if image_texture.adjusted.is_empty() {
|
||||
image_texture.adjustment_source = None;
|
||||
}
|
||||
});
|
||||
|
||||
// Panning and zooming across a generator leaves tiles behind faster than they go unused for long, so the least recent beyond a limit are freed too
|
||||
let mut tile_ages: Vec<u64> = (self.textures.iter())
|
||||
.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_)))
|
||||
.map(|(_, image_texture)| image_texture.last_used)
|
||||
.collect();
|
||||
if tile_ages.len() > MAX_CACHED_GENERATOR_TILES {
|
||||
let excess = tile_ages.len() - MAX_CACHED_GENERATOR_TILES;
|
||||
let (_, &mut oldest_kept, _) = tile_ages.select_nth_unstable(excess);
|
||||
let least_recent = (self.textures).extract_if(|key, image_texture| matches!(key, ImageKey::GeneratorTile(_)) && image_texture.last_used < oldest_kept);
|
||||
self.spare_generator_tiles.extend(least_recent.map(|(_, image_texture)| image_texture.texture));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Uploads CPU pixels as a premultiplied texture, downscaling them by a whole factor if they exceed `max_texture_size`.
|
||||
fn upload_pixels(executor: &WgpuExecutor, queue: &wgpu::Queue, pixels: &[u8], width: u32, height: u32, alpha_type: peniko::ImageAlphaType, max_texture_size: u32) -> Option<Texture> {
|
||||
fn upload_pixels(device: &wgpu::Device, queue: &wgpu::Queue, pixels: &[u8], width: u32, height: u32, alpha_type: peniko::ImageAlphaType, max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
}
|
||||
@@ -732,7 +776,20 @@ fn upload_pixels(executor: &WgpuExecutor, queue: &wgpu::Queue, pixels: &[u8], wi
|
||||
|
||||
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
|
||||
let level_count = texture_width.max(texture_height).ilog2() + 1;
|
||||
let texture = executor.request_texture_with_mips(UVec2::new(texture_width, texture_height), TEXTURE_FORMAT, level_count);
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_image"),
|
||||
size: wgpu::Extent3d {
|
||||
width: texture_width,
|
||||
height: texture_height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
|
||||
let (mut level_pixels, mut level_width, mut level_height) = (pixels, texture_width, texture_height);
|
||||
for level in 0..level_count {
|
||||
@@ -823,7 +880,7 @@ fn box_downscale<Channel: Copy + Into<f32>>(pixels: &[Channel], width: u32, heig
|
||||
|
||||
/// Uploads a raster's straight linear colors as one level of 32-bit floats, the size [`upload_pixels`] makes them, so adjustments read the CPU's exact values.
|
||||
/// A raster too large for one texture is averaged down to fit on premultiplied gamma-encoded channels, as [`upload_pixels`] averages them.
|
||||
fn upload_adjustment_source(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Image<core_types::Color>, max_texture_size: u32) -> Option<Texture> {
|
||||
fn upload_adjustment_source(device: &wgpu::Device, queue: &wgpu::Queue, image: &Image<core_types::Color>, max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
let (width, height) = (image.width, image.height);
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
@@ -860,7 +917,16 @@ fn upload_adjustment_source(executor: &WgpuExecutor, queue: &wgpu::Queue, image:
|
||||
height: texture_height,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let texture = executor.request_texture_with_format(UVec2::new(texture_width, texture_height), format);
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_adjustment_source"),
|
||||
size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
@@ -899,6 +965,23 @@ fn clear_texture(encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView) {
|
||||
});
|
||||
}
|
||||
|
||||
fn create_texture(device: &wgpu::Device, label: &str, size: UVec2, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> wgpu::Texture {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d {
|
||||
width: size.x.max(1),
|
||||
height: size.y.max(1),
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
|
||||
/// Full-target passes converting between straight and premultiplied alpha.
|
||||
struct AlphaConversion {
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::WgpuExecutor;
|
||||
use core_types::blending::BlendMode;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graphic_types::MinimumMaximumMode;
|
||||
use graphic_types::vector_types::gradient::{GradientDirection, GradientModel, GradientSpread};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use vello_gpu::kurbo::{Affine, BezPath, Line, ParamCurve, PathSeg, Point, Rect, Stroke, Vec2};
|
||||
use vello_gpu::peniko::{self, Color, Fill};
|
||||
@@ -369,6 +370,412 @@ fn degenerate_strokes_render() {
|
||||
let Some(_) = render(size, draw) else { return };
|
||||
}
|
||||
|
||||
/// A gradient from black to white read in gamma, placed by `placement`, with these curvatures and model, or none if `None`.
|
||||
fn curved_black_to_white_gradient(placement: DAffine2, curvatures: Option<[f64; 2]>, model: GradientModel) -> graphic_types::Graphic {
|
||||
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_START_CURVATURE, Item};
|
||||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientSpace};
|
||||
|
||||
let mut item = Item::new_from_element(Gradient::from(vec![GraphicColor::BLACK, GraphicColor::WHITE]))
|
||||
.with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma)
|
||||
.with_attribute(ATTR_TRANSFORM, placement);
|
||||
if let Some([start, end]) = curvatures {
|
||||
item.set_attribute(ATTR_GRADIENT_START_CURVATURE, start);
|
||||
item.set_attribute(ATTR_GRADIENT_END_CURVATURE, end);
|
||||
item.set_attribute(ATTR_GRADIENT_MODEL, model);
|
||||
}
|
||||
graphic_types::Graphic::Gradient(item)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curved_gradients_match_their_cpu_evaluation() {
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::gradient_standard::radius_curvature;
|
||||
use std::fmt::Write;
|
||||
|
||||
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100), and then sheared
|
||||
let placements = [
|
||||
DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.)),
|
||||
DAffine2::from_cols(DVec2::new(50., 10.), DVec2::new(15., 35.), DVec2::new(60., 100.)),
|
||||
];
|
||||
|
||||
let radius = radius_curvature;
|
||||
let settings = [
|
||||
([-1., radius(0.75)], "a focal point inside the end circle, off its center"),
|
||||
([radius(0.2), radius(1.5)], "a focal circle nested inside the end circle"),
|
||||
([radius(2.), radius(-0.5)], "an end circle nested inside the start circle"),
|
||||
([radius(0.6), radius(0.6)], "crossing circles"),
|
||||
([0.5, 0.25], "crossing circles of different sizes"),
|
||||
([radius(-0.3), radius(-0.3)], "separate circles of the same size"),
|
||||
([radius(-0.2), radius(-0.4)], "separate circles of different sizes"),
|
||||
([-1., radius(-0.4)], "a focal point outside the end circle"),
|
||||
([-1., -1.], "two points"),
|
||||
([radius(0.5), radius(0.5)], "identical circles"),
|
||||
([radius(0.3), radius(2500.)], "an end nearly a line"),
|
||||
([radius(0.8), 0.], "an end line beside a start circle reaching past the end"),
|
||||
([radius(-0.4), 0.], "an end line beside a start circle bowing away"),
|
||||
([0., radius(2.)], "a start line beside an end circle reaching past the start"),
|
||||
([radius(1.), radius(0.5)], "internally tangent circles"),
|
||||
([radius(3000.), radius(-4000.)], "both ends nearly flat around an apex"),
|
||||
([radius(-3000.), radius(3000.)], "both ends nearly flat, bowing apart"),
|
||||
([7e-31, 0.3], "a start nearly too flat to draw as a circle"),
|
||||
([4e-309, -1e-300], "both ends past computing as circles"),
|
||||
];
|
||||
|
||||
let mut report = String::new();
|
||||
for (curvatures, setting) in settings {
|
||||
for placement in placements {
|
||||
let Some(line) = compare_curved_gradient_with_cpu(curvatures, placement, GradientSpread::Pad, setting) else {
|
||||
return;
|
||||
};
|
||||
let _ = writeln!(report, "{line}");
|
||||
}
|
||||
}
|
||||
eprintln!("{report}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn far_and_wide_curved_ramps_match_their_cpu_evaluation() {
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::gradient_standard::radius_curvature;
|
||||
|
||||
// Equal radii of a million ramp from 2 million to the end point, where t reaches 1 exactly, so Clear clears and Repeat restarts just past it
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.));
|
||||
for spread in [GradientSpread::Clear, GradientSpread::Repeat] {
|
||||
let curvatures = [radius_curvature(1e6), radius_curvature(1e6)];
|
||||
let Some(line) = compare_curved_gradient_with_cpu(curvatures, placement, spread, "equal radii of a million") else {
|
||||
return;
|
||||
};
|
||||
eprintln!("{line}");
|
||||
}
|
||||
|
||||
// A ramp a gradient length wide, 200,000 gradient lengths before the start, drawn across 100 pixels
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(100.), 0., DVec2::new(100. * 200_000., 100.));
|
||||
let curvatures = [radius_curvature(-1e5), radius_curvature(1e5)];
|
||||
let Some(line) = compare_curved_gradient_with_cpu(curvatures, placement, GradientSpread::Pad, "a ramp 200,000 back") else {
|
||||
return;
|
||||
};
|
||||
eprintln!("{line}");
|
||||
}
|
||||
|
||||
/// Renders a black to white gradient with these curvatures, placed by `placement` and read with `spread`, into a 200 by 200 view, and checks
|
||||
/// each pixel against the CPU's evaluation, returning a line describing how they compare, or `None` without a GPU.
|
||||
fn compare_curved_gradient_with_cpu(curvatures: [f64; 2], placement: DAffine2, spread: GradientSpread, setting: &str) -> Option<String> {
|
||||
use core_types::list::ATTR_GRADIENT_SPREAD;
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::gradient_standard::GradientStandard;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(200, 200);
|
||||
let graphic = match curved_black_to_white_gradient(placement, Some(curvatures), GradientModel::Standard) {
|
||||
graphic_types::Graphic::Gradient(item) => graphic_types::Graphic::Gradient(item.with_attribute(ATTR_GRADIENT_SPREAD, spread)),
|
||||
graphic => graphic,
|
||||
};
|
||||
let pixels = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?;
|
||||
|
||||
// The CPU's level at a point on the screen, or `None` where it's unpainted
|
||||
let gradient = GradientStandard::new(curvatures[0], curvatures[1]);
|
||||
let to_gradient = placement.inverse();
|
||||
let level_at = |point: DVec2| {
|
||||
let t = gradient.t(to_gradient.transform_point2(point))?;
|
||||
let position = match spread {
|
||||
GradientSpread::Clear if !(0. ..=1.).contains(&t) => return None,
|
||||
GradientSpread::Repeat if t.is_infinite() => (t > 0.) as u8 as f64,
|
||||
GradientSpread::Repeat => t - t.floor(),
|
||||
_ => t.clamp(0., 1.),
|
||||
};
|
||||
Some((position * 255.).round() as i32)
|
||||
};
|
||||
let center = |x: i32, y: i32| DVec2::new(x as f64 + 0.5, y as f64 + 0.5);
|
||||
let expected = |x: i32, y: i32| level_at(center(x, y));
|
||||
|
||||
// Each pixel takes the level at its center, except that one beside a step in the ramp or an edge of the painted area may land anywhere between its neighbors' levels
|
||||
let (mut worst, mut beside_steps, mut out_of_range, mut disagreements) = (0, 0, Vec::new(), 0);
|
||||
for y in 1..size.y as i32 - 1 {
|
||||
for x in 1..size.x as i32 - 1 {
|
||||
let neighborhood: Vec<Option<i32>> = (-1..=1).flat_map(|dy| (-1..=1).map(move |dx| (x + dx, y + dy))).map(|(x, y)| expected(x, y)).collect();
|
||||
let painted_neighbors = neighborhood.iter().filter(|level| level.is_some()).count();
|
||||
let levels = neighborhood.iter().flatten();
|
||||
let (lowest, highest) = (*levels.clone().min().unwrap_or(&0), *levels.max().unwrap_or(&255));
|
||||
let [red, _, _, alpha] = pixel(&pixels, size, x as u32, y as u32);
|
||||
let red = red as i32;
|
||||
|
||||
match (alpha, expected(x, y)) {
|
||||
(0, None) => {}
|
||||
(255, Some(level)) if painted_neighbors == 9 && highest - lowest <= 32 => worst = worst.max((red - level).abs()),
|
||||
(255, Some(_)) => {
|
||||
beside_steps += 1;
|
||||
|
||||
// A center on a step (to within single precision) may take either side's level, which a sliver thinner than a pixel can hide from every neighbor
|
||||
let nudged = [DVec2::X, -DVec2::X, DVec2::Y, -DVec2::Y].map(|direction| level_at(center(x, y) + direction * 1e-3));
|
||||
let (lowest, highest) = nudged.iter().flatten().fold((lowest, highest), |(lowest, highest), &level| (lowest.min(level), highest.max(level)));
|
||||
|
||||
if red < lowest - 3 || red > highest + 3 {
|
||||
let point = to_gradient.transform_point2(center(x, y));
|
||||
out_of_range.push(format!("pixel ({x}, {y}) at {point} is {red} beside {lowest} to {highest}"));
|
||||
}
|
||||
}
|
||||
_ if painted_neighbors != 0 && painted_neighbors != 9 => {}
|
||||
_ => disagreements += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let context = format!("{setting} {curvatures:?}, {spread:?}, placed by {placement:?}");
|
||||
assert!(worst <= 3, "{context}: up to {worst} levels from the CPU");
|
||||
assert!(out_of_range.is_empty(), "{context}: pixels beside steps out of their neighbors' range: {out_of_range:?}");
|
||||
assert_eq!(disagreements, 0, "{context}: pixels disagreeing with the CPU on being painted");
|
||||
Some(format!(
|
||||
"{context}: within {worst} levels, {beside_steps} pixels beside steps in their neighbors' range, {disagreements} disagree on being painted"
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apollonian_gradients_match_their_cpu_evaluation() {
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::gradient_standard::GradientShape;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(200, 200);
|
||||
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100)
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.));
|
||||
|
||||
for curvatures in [
|
||||
[1., 0.6],
|
||||
[0.6, 0.6],
|
||||
[-0.5, 0.2952],
|
||||
[1., 1.],
|
||||
[0.5, 0.25],
|
||||
[0.3, -0.3],
|
||||
[0.8, 1.],
|
||||
[0.9, 0.2],
|
||||
[0.9, 0.9],
|
||||
[0.001, 0.8],
|
||||
// The outer arc through infinity, with the band offset from the start and with the wrap's t negative
|
||||
[0.9, 0.6],
|
||||
[0.6, 1.],
|
||||
] {
|
||||
let GradientShape::Apollonian(parameters) = GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, placement) else {
|
||||
panic!("curvatures {curvatures:?} should draw Apollonian circles");
|
||||
};
|
||||
let graphic = curved_black_to_white_gradient(placement, Some(curvatures), GradientModel::Apollonian);
|
||||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let mut worst = 0_i32;
|
||||
for y in (5..195).step_by(10) {
|
||||
for x in (5..195).step_by(10) {
|
||||
let point = placement.inverse().transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
|
||||
let expected = (parameters.t(point).clamp(0., 1.) * 255.).round() as i32;
|
||||
worst = worst.max((expected - pixel(&pixels, size, x, y)[0] as i32).abs());
|
||||
}
|
||||
}
|
||||
assert!(worst <= 3, "curvatures {curvatures:?} differ from the CPU evaluation by up to {worst} levels");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn across_gradients_match_their_cpu_evaluation() {
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::gradient_standard::radius_curvature;
|
||||
use std::fmt::Write;
|
||||
|
||||
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100), and then sheared
|
||||
let placements = [
|
||||
DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.)),
|
||||
DAffine2::from_cols(DVec2::new(50., 10.), DVec2::new(15., 35.), DVec2::new(60., 100.)),
|
||||
];
|
||||
|
||||
let radius = radius_curvature;
|
||||
let (standard, apollonian) = (GradientModel::Standard, GradientModel::Apollonian);
|
||||
let settings = [
|
||||
([0., 0.], standard, "the linear form"),
|
||||
([-1., 0.5], standard, "the radial form"),
|
||||
([radius(2.), radius(-1.)], standard, "concentric circles"),
|
||||
([-1., radius(0.75)], standard, "a focal point inside the end circle, off its center"),
|
||||
([radius(0.2), radius(1.5)], standard, "a focal circle nested inside the end circle"),
|
||||
([radius(0.6), radius(0.6)], standard, "crossing circles"),
|
||||
([radius(-0.2), radius(-0.4)], standard, "separate circles"),
|
||||
([radius(0.8), 0.], standard, "an end line beside a start circle reaching past the end"),
|
||||
([radius(0.45), 0.], standard, "an end line beside a start circle nearly reaching the end"),
|
||||
([radius(0.6), 0.], standard, "an end line beside a start circle just past the end"),
|
||||
([radius(3000.), radius(-4000.)], standard, "both ends nearly flat around an apex"),
|
||||
([radius(2.), radius(-1.)], apollonian, "concentric Apollonian circles"),
|
||||
([1., 0.3], apollonian, "Apollonian circles around the start point"),
|
||||
([0.9, 0.2], apollonian, "nested Apollonian circles"),
|
||||
([0.8, 1.], apollonian, "Apollonian circles around the end point"),
|
||||
([1., 1.], apollonian, "Apollonian circles of two points"),
|
||||
([0.6, 0.6], apollonian, "crossing Apollonian circles"),
|
||||
([0.5, 0.25], apollonian, "crossing Apollonian circles of different sizes"),
|
||||
];
|
||||
|
||||
let mut report = String::new();
|
||||
for (curvatures, model, setting) in settings {
|
||||
for placement in placements {
|
||||
for spread in [GradientSpread::Pad, GradientSpread::Repeat] {
|
||||
let Some(line) = compare_across_gradient_with_cpu(curvatures, model, placement, spread, setting) else {
|
||||
return;
|
||||
};
|
||||
let _ = writeln!(report, "{line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("{report}");
|
||||
}
|
||||
|
||||
/// Renders a black to white gradient read across its contours, with these curvatures and model, placed by `placement` and read with `spread`, into a
|
||||
/// 200 by 200 view, and checks each pixel against the CPU's evaluation, returning a line describing how they compare, or `None` without a GPU.
|
||||
fn compare_across_gradient_with_cpu(curvatures: [f64; 2], model: GradientModel, placement: DAffine2, spread: GradientSpread, setting: &str) -> Option<String> {
|
||||
use core_types::list::{ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_SPREAD};
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::gradient_standard::GradientShape;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(200, 200);
|
||||
let graphic = match curved_black_to_white_gradient(placement, Some(curvatures), model) {
|
||||
graphic_types::Graphic::Gradient(item) => {
|
||||
graphic_types::Graphic::Gradient(item.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across).with_attribute(ATTR_GRADIENT_SPREAD, spread))
|
||||
}
|
||||
graphic => graphic,
|
||||
};
|
||||
let pixels = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?;
|
||||
|
||||
// The CPU's level at a point on the screen, or `None` where it's unpainted, which the spread repeats only where the position doesn't wind
|
||||
let GradientShape::Across(across) = GradientShape::new(curvatures[0], curvatures[1], model, GradientDirection::Across, placement) else {
|
||||
panic!("{setting} should be read across its contours");
|
||||
};
|
||||
let to_gradient = placement.inverse();
|
||||
let level_at = |point: DVec2| {
|
||||
let v = across.chart.v(to_gradient.transform_point2(point))?;
|
||||
let position = match spread {
|
||||
_ if across.chart.winds() => v,
|
||||
GradientSpread::Repeat => v - v.floor(),
|
||||
_ => v.clamp(0., 1.),
|
||||
};
|
||||
Some((position * 255.).round() as i32)
|
||||
};
|
||||
let expected = |x: i32, y: i32| level_at(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
|
||||
|
||||
// Each pixel takes the level at its center, except within two pixels of a seam where the position wraps, a step, or an edge of the painted area, which only rounding and antialiasing tell apart
|
||||
let (mut worst, mut beside_steps, mut disagreements) = (0, 0, 0);
|
||||
for y in 2..size.y as i32 - 2 {
|
||||
for x in 2..size.x as i32 - 2 {
|
||||
let neighborhood: Vec<Option<i32>> = (-2..=2).flat_map(|dy| (-2..=2).map(move |dx| (x + dx, y + dy))).map(|(x, y)| expected(x, y)).collect();
|
||||
let painted_neighbors = neighborhood.iter().filter(|level| level.is_some()).count();
|
||||
let levels = neighborhood.iter().flatten();
|
||||
let (lowest, highest) = (*levels.clone().min().unwrap_or(&0), *levels.max().unwrap_or(&255));
|
||||
let [red, _, _, alpha] = pixel(&pixels, size, x as u32, y as u32);
|
||||
|
||||
match (alpha, expected(x, y)) {
|
||||
(0, None) => {}
|
||||
(255, Some(level)) if painted_neighbors == 25 && highest - lowest <= 64 => worst = worst.max((red as i32 - level).abs()),
|
||||
(255, Some(_)) => beside_steps += 1,
|
||||
_ if painted_neighbors != 0 && painted_neighbors != 25 => {}
|
||||
_ => disagreements += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let context = format!("{setting} {curvatures:?}, {spread:?}, placed by {placement:?}");
|
||||
assert!(worst <= 3, "{context}: up to {worst} levels from the CPU");
|
||||
assert_eq!(disagreements, 0, "{context}: pixels disagreeing with the CPU on being painted");
|
||||
Some(format!("{context}: within {worst} levels, {beside_steps} pixels beside seams and steps"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_stop_curved_gradients_leave_their_gaps_unpainted() {
|
||||
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, Item};
|
||||
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::gradient::Gradient;
|
||||
use graphic_types::vector_types::gradient_standard::radius_curvature;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(200, 200);
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.));
|
||||
|
||||
// Crossing circles of radius 0.6, whose cone paints the strip within 0.6 of the gradient line, in one half-transparent red stop
|
||||
let item = Item::new_from_element(Gradient::from(vec![GraphicColor::from_rgbaf32_unchecked(1., 0., 0., 0.5)]))
|
||||
.with_attribute(ATTR_TRANSFORM, placement)
|
||||
.with_attribute(ATTR_GRADIENT_START_CURVATURE, radius_curvature(0.6))
|
||||
.with_attribute(ATTR_GRADIENT_END_CURVATURE, radius_curvature(0.6));
|
||||
let graphic = graphic_types::Graphic::Gradient(item);
|
||||
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// At (0.5, 0) on the cone and (0.5, 1) in its gap
|
||||
let (on_cone, in_gap) = (pixel(&pixels, size, 85, 100)[3], pixel(&pixels, size, 85, 150)[3]);
|
||||
assert!(on_cone.abs_diff(128) <= 1, "on the cone: alpha {on_cone}");
|
||||
assert_eq!(in_gap, 0, "in the gap: alpha {in_gap}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_presets_render_on_the_gpu_as_their_forms_did() {
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::GradientForm;
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let size = UVec2::new(160, 120);
|
||||
let placement = DAffine2::from_cols(DVec2::new(40., 10.), DVec2::new(-12., 30.), DVec2::new(70., 55.));
|
||||
let render_graphic = |graphic: &graphic_types::Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
|
||||
|
||||
for form in [GradientForm::Linear, GradientForm::Radial] {
|
||||
// The brush each form was drawn with before curvatures: the unit line placed without shear, or the unit circle placed as is
|
||||
let (kind, brush_placement): (peniko::GradientKind, DAffine2) = match form {
|
||||
GradientForm::Linear => {
|
||||
let line = placement.matrix2.x_axis.project_onto(placement.matrix2.y_axis.perp());
|
||||
let desheared = DAffine2::from_cols(line, line.perp(), placement.translation);
|
||||
(
|
||||
peniko::LinearGradientPosition {
|
||||
start: Point::ORIGIN,
|
||||
end: Point::new(1., 0.),
|
||||
}
|
||||
.into(),
|
||||
desheared,
|
||||
)
|
||||
}
|
||||
GradientForm::Radial => (
|
||||
peniko::RadialGradientPosition {
|
||||
start_center: Point::ORIGIN,
|
||||
start_radius: 0.,
|
||||
end_center: Point::ORIGIN,
|
||||
end_radius: 1.,
|
||||
}
|
||||
.into(),
|
||||
placement,
|
||||
),
|
||||
};
|
||||
let brush = peniko::Brush::Gradient(
|
||||
peniko::Gradient {
|
||||
kind,
|
||||
interpolation_alpha_space: peniko::InterpolationAlphaSpace::Unpremultiplied,
|
||||
..Default::default()
|
||||
}
|
||||
.with_stops([Color::from_rgb8(0, 0, 0), Color::from_rgb8(255, 255, 255)]),
|
||||
);
|
||||
let Some(by_brush) = render(size, |scene| scene.fill_viewport(&brush, Some(Affine::new(brush_placement.to_cols_array())))) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Its curvatures draw those pixels under either model, and absent curvatures are the linear form's
|
||||
let absent = (form == GradientForm::Linear).then_some((None, GradientModel::Apollonian));
|
||||
for (curvatures, model) in [(Some(form.curvatures()), GradientModel::Standard), (Some(form.curvatures()), GradientModel::Apollonian)]
|
||||
.into_iter()
|
||||
.chain(absent)
|
||||
{
|
||||
let Some(by_curvatures) = render_graphic(&curved_black_to_white_gradient(placement, curvatures, model)) else {
|
||||
return;
|
||||
};
|
||||
assert!(
|
||||
by_curvatures == by_brush,
|
||||
"{form:?} with curvatures {curvatures:?} and the {model:?} model should draw the pixels of its brush from before curvatures"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders an opaque white square from (`min`, `min`) to (`max`, `max`) through `effects` with `fill`.
|
||||
fn render_square_with_effects(effects: Vec<graphic_types::EffectOperation>, fill: f32, min: f64, max: f64, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||||
render_square_with_effects_in(effects, DAffine2::IDENTITY, fill, min, max, size)
|
||||
@@ -1647,7 +2054,7 @@ fn gpu_effect_texels(effects: &graphic_types::Effects, texels: &[[half::f16; 4]]
|
||||
|
||||
let mut textures = crate::vello_effects::EffectTextures::default();
|
||||
let layers = graphic_types::effect_layers::EffectLayers::plan(effects, BlendMode::Normal, 1., false);
|
||||
let results = effect_passes.apply(executor, &queue, &mut textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &paints, None, None);
|
||||
let results = effect_passes.apply(device, &queue, &mut textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &paints, None, None);
|
||||
let (result, _) = results.into_iter().next()?;
|
||||
drop(queue);
|
||||
|
||||
@@ -3488,8 +3895,8 @@ fn captured_box_blurs_hold_their_results_for_svg_however_slight() {
|
||||
fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::ATTR_GRADIENT_FORM;
|
||||
use core_types::list::Item;
|
||||
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||||
use glam::DVec2;
|
||||
@@ -3799,17 +4206,30 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let gradient = |form: GradientForm, transform: DAffine2| {
|
||||
let gradient_item = |transform: DAffine2| {
|
||||
let stops = [(0., [0.9, 0.1, 0.4, 1.]), (0.5, [0.2, 0.3, 0.9, 0.5]), (1., [1., 0.9, 0.7, 1.])].map(|(position, [red, green, blue, alpha])| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: GraphicColor::from_rgbaf32_unchecked(red, green, blue, alpha),
|
||||
});
|
||||
let item = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform);
|
||||
Graphic::from(item.with_attribute(ATTR_GRADIENT_FORM, form))
|
||||
Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform)
|
||||
};
|
||||
let gradient = |form: GradientForm, transform: DAffine2| {
|
||||
let [start_curvature, end_curvature] = form.curvatures();
|
||||
Graphic::from(
|
||||
gradient_item(transform)
|
||||
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature)
|
||||
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature),
|
||||
)
|
||||
};
|
||||
let linear = gradient(GradientForm::Linear, DAffine2::from_translation(DVec2::new(45., 60.)) * DAffine2::from_scale(DVec2::splat(60.)));
|
||||
let radial = gradient(GradientForm::Radial, DAffine2::from_translation(DVec2::splat(75.)) * DAffine2::from_scale(DVec2::splat(30.)));
|
||||
// Curvatures between the two forms, with crossing end circles whose cone leaves gaps unpainted, and the same curvatures drawn as Apollonian circles
|
||||
let curved_item = gradient_item(DAffine2::from_translation(DVec2::new(55., 70.)) * DAffine2::from_scale(DVec2::splat(30.)))
|
||||
.with_attribute(ATTR_GRADIENT_START_CURVATURE, 0.5)
|
||||
.with_attribute(ATTR_GRADIENT_END_CURVATURE, 0.25);
|
||||
let curved = Graphic::from(curved_item.clone());
|
||||
let apollonian = Graphic::from(curved_item.with_attribute(ATTR_GRADIENT_MODEL, GradientModel::Apollonian));
|
||||
|
||||
// A checkerboard spanning the render from `start` to `end` with a pixel for each of the render's, so sampling it needs no interpolation
|
||||
let checkerboard = |start: u32, end: u32| {
|
||||
@@ -3850,11 +4270,15 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
overlay(&linear, BlendMode::Normal, 40.),
|
||||
overlay(&radial, BlendMode::Multiply, 100.),
|
||||
overlay(&checker, BlendMode::Screen, 100.),
|
||||
overlay(&curved, BlendMode::Normal, 100.),
|
||||
overlay(&apollonian, BlendMode::Normal, 100.),
|
||||
]);
|
||||
// Outlines drawn with paints placed on their own, the image covering the outline as well as the content
|
||||
paint_cases.extend([
|
||||
vec![outline(linear.clone(), 6., StrokeAlign::Outside, false)],
|
||||
vec![outline(radial.clone(), 8., StrokeAlign::Center, false)],
|
||||
vec![outline(curved.clone(), 8., StrokeAlign::Center, false)],
|
||||
vec![outline(apollonian.clone(), 8., StrokeAlign::Center, false)],
|
||||
vec![outline(checkerboard(min - 10, max + 10), 9., StrokeAlign::Center, false)],
|
||||
]);
|
||||
// Bevels with gloss contours, contours, and textures
|
||||
@@ -3975,6 +4399,7 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
vec![mask(&mask_image, MaskMode::Alpha, 70., 3., true)],
|
||||
vec![mask(&linear, MaskMode::Luminance, 100., 6., false)],
|
||||
vec![mask(&radial, MaskMode::Alpha, 100., 0., false)],
|
||||
vec![mask(&curved, MaskMode::Luminance, 100., 0., false)],
|
||||
vec![mask(&mask_image, MaskMode::Luminance, 100., 2., false), mask_shadow.clone()],
|
||||
vec![mask_shadow.clone(), mask(&linear, MaskMode::Luminance, 80., 0., true)],
|
||||
vec![blur(2., false, false), mask(&radial, MaskMode::Luminance, 100., 1.5, false), mask_shadow.clone()],
|
||||
@@ -4369,7 +4794,7 @@ fn gpu_adjusted_texels(run: &[graphic_types::Adjustment], texels: &[[half::f16;
|
||||
let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment));
|
||||
let mut textures = crate::vello_effects::EffectTextures::default();
|
||||
let layers = graphic_types::effect_layers::EffectLayers::plan(&effects, core_types::blending::BlendMode::Normal, fill, false);
|
||||
let results = effect_passes.apply(executor, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let results = effect_passes.apply(device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
|
||||
let (adjusted, _) = results.into_iter().next().expect("the adjustments draw one layer");
|
||||
drop(queue);
|
||||
|
||||
@@ -6366,10 +6791,8 @@ fn generator_tile_pixels(pattern: &graphic_types::generator::GeneratorPattern, c
|
||||
|
||||
let queue = executor.context().queue.lock();
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("generator_tile_test") });
|
||||
let mut held = Vec::new();
|
||||
(executor.inner.vello_renderer.generator_passes).render_tile(executor, &queue, &mut encoder, &mut held, &texture, pattern, corner, texel);
|
||||
(executor.inner.vello_renderer.generator_passes).render_tile(device, &queue, &mut encoder, &texture, pattern, corner, texel);
|
||||
queue.submit([encoder.finish()]);
|
||||
drop(held);
|
||||
drop(queue);
|
||||
|
||||
let bytes = executor.read_texture_pixels(&texture).expect("Failed to read back the tile");
|
||||
@@ -6425,7 +6848,7 @@ fn generator_tiles_are_reused_across_a_pan() {
|
||||
let Some(executor) = executor() else { return };
|
||||
let _turn = take_turn();
|
||||
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
|
||||
let tiles = |canvas: &crate::VelloCanvas| canvas.images.generator_tiles.len();
|
||||
let tiles = |canvas: &crate::VelloCanvas| canvas.images.textures.len();
|
||||
|
||||
// A pattern drawn two pixels to a unit, in tiles of 256 pixels, panned by part of a tile
|
||||
let mut canvas = crate::VelloCanvas::default();
|
||||
@@ -6444,6 +6867,44 @@ fn generator_tiles_are_reused_across_a_pan() {
|
||||
assert!(panned < first, "panning renders only the tiles newly in view, not all {first} again (rendered {panned})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_generator_tiles_take_over_the_textures_of_freed_ones() {
|
||||
use graphic_types::generator::{GeneratorPattern, NoiseSettings};
|
||||
|
||||
let Some(executor) = executor() else { return };
|
||||
let _turn = take_turn();
|
||||
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
|
||||
let tile_textures = |canvas: &crate::VelloCanvas| -> Vec<wgpu::Texture> {
|
||||
(canvas.images.textures.iter())
|
||||
.filter(|(key, _)| matches!(key, super::ImageKey::GeneratorTile(_)))
|
||||
.map(|(_, image_texture)| image_texture.texture.clone())
|
||||
.collect()
|
||||
};
|
||||
|
||||
let mut canvas = crate::VelloCanvas::default();
|
||||
let draw = |canvas: &mut crate::VelloCanvas, seed: i64| {
|
||||
let mut scene = VelloSceneBuilder::new(512, 512, Affine::IDENTITY, max_texture_size);
|
||||
scene.draw_generator(&GeneratorPattern::Noise(NoiseSettings { seed, ..noise_settings() }), Affine::scale(2.));
|
||||
executor.render_vello_scene_on_canvas(canvas, scene).unwrap();
|
||||
};
|
||||
|
||||
// The first pattern's tiles, freed once another is drawn for long enough
|
||||
draw(&mut canvas, 1);
|
||||
let freed = tile_textures(&canvas);
|
||||
for _ in 0..super::UNUSED_IMAGE_RENDER_LIMIT {
|
||||
draw(&mut canvas, 2);
|
||||
}
|
||||
|
||||
// The textures in use since the first pattern was freed are the second's and the third's, which takes over the first's
|
||||
let second = tile_textures(&canvas);
|
||||
draw(&mut canvas, 3);
|
||||
let third: Vec<_> = tile_textures(&canvas).into_iter().filter(|texture| !second.contains(texture)).collect();
|
||||
assert!(
|
||||
third.len() == freed.len() && third.iter().all(|texture| freed.contains(texture)),
|
||||
"the third pattern's tiles render into the textures of the first's"
|
||||
);
|
||||
}
|
||||
|
||||
/// An effect stamped on content at `placement` the way its node stamps it, with displacement maps lined up with the content where it lies.
|
||||
fn stamped_at(operation: &graphic_types::EffectOperation, placement: DAffine2) -> graphic_types::Effect {
|
||||
let mut operation = operation.clone();
|
||||
|
||||
@@ -28,7 +28,10 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
} = parsed;
|
||||
let core_types = crate_ident.gcore()?;
|
||||
|
||||
let category = attributes.category.as_ref().map(syn::LitStr::value).unwrap_or_default();
|
||||
let category = attributes
|
||||
.category
|
||||
.as_ref()
|
||||
.expect("The 'category' attribute is required and should be checked during parsing, but was not found during codegen");
|
||||
let mod_name = format_ident!("_{}_mod", mod_name);
|
||||
|
||||
let display_name = match &attributes.display_name.as_ref() {
|
||||
@@ -598,7 +601,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
Some(path) => quote!(Some(#path(#(&#declared_field_names),*))),
|
||||
None => quote!(None),
|
||||
};
|
||||
let keep_previous = attributes.flags.keep_previous;
|
||||
let data_clones = data_field_names.iter().map(|name| quote!(let #name = self.#name.clone();));
|
||||
let landed_call = landed(quote!(self::#fn_name(__context #(, &#data_field_names)* #(, #regular_field_names)*).await));
|
||||
quote! {
|
||||
@@ -630,7 +632,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let __runtime = _runtime.element().clone();
|
||||
let __context = __input.clone();
|
||||
#(#data_clones)*
|
||||
let __state = self.slots.resolve(__key, &__runtime, __source, __placeholder, #keep_previous, move || async move { #landed_call });
|
||||
let __state = self.slots.resolve(__key, &__runtime, __source, __placeholder, move || async move { #landed_call });
|
||||
__cell.merge(__state)
|
||||
}
|
||||
}
|
||||
@@ -836,15 +838,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
footprint_invariant,
|
||||
forwards_input,
|
||||
inject_scope,
|
||||
adapter,
|
||||
transient,
|
||||
..
|
||||
} = attributes.flags;
|
||||
let adapter = match adapter {
|
||||
Some(AdapterKind::Conversion) => quote!(Some(gcore::registry::AdapterKind::Conversion)),
|
||||
Some(AdapterKind::Rank) => quote!(Some(gcore::registry::AdapterKind::Rank)),
|
||||
None => quote!(None),
|
||||
};
|
||||
let asynchronous = parsed.is_async;
|
||||
let version = attributes.version.unwrap_or(1);
|
||||
// A node returning a `Destructure` struct records its fields as output connectors
|
||||
@@ -1058,8 +1053,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
forwards_input: #forwards_input,
|
||||
inject_scope: #inject_scope,
|
||||
asynchronous: #asynchronous,
|
||||
adapter: #adapter,
|
||||
transient: #transient,
|
||||
},
|
||||
version: #version,
|
||||
output_fields: #output_fields,
|
||||
|
||||
@@ -52,20 +52,8 @@ pub(crate) struct NodeFlags {
|
||||
pub(crate) skip_impl: bool,
|
||||
/// Whether the node refuses placeholder data.
|
||||
pub(crate) no_partial: bool,
|
||||
pub(crate) transient: bool,
|
||||
/// Whether a pending evaluation returns the latest landed output instead of the placeholder.
|
||||
pub(crate) keep_previous: bool,
|
||||
/// Set on the `Destructure` derive's generated extractor nodes, which take the struct rather than an `Item` or `List`. Not parsed from source.
|
||||
pub(crate) destructure_extractor: bool,
|
||||
/// Whether type resolution may insert this node on an edge, and how it changes the wire.
|
||||
pub(crate) adapter: Option<AdapterKind>,
|
||||
}
|
||||
|
||||
/// Mirrors `core_types::registry::AdapterKind`, which this proc-macro crate cannot depend on.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum AdapterKind {
|
||||
Conversion,
|
||||
Rank,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
@@ -569,25 +557,6 @@ impl Parse for NodeFnAttributes {
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., forwards_input, ...)]
|
||||
"forwards_input" => set_flag(&mut flags.forwards_input, meta, "forwards_input")?,
|
||||
// Marks the node as an adapter that type resolution may insert on an edge, either converting the wire's element type or changing its rank.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., adapter(conversion), ...)]
|
||||
// #[node_macro::node(..., adapter(rank), ...)]
|
||||
"adapter" => {
|
||||
let meta = meta.require_list()?;
|
||||
if flags.adapter.is_some() {
|
||||
return Err(Error::new_spanned(meta, "Multiple 'adapter' attributes are not allowed"));
|
||||
}
|
||||
let kind: Ident = meta
|
||||
.parse_args()
|
||||
.map_err(|_| Error::new_spanned(meta, "Expected 'conversion' or 'rank' for 'adapter', e.g., adapter(rank)"))?;
|
||||
flags.adapter = Some(match kind.to_string().as_str() {
|
||||
"conversion" => AdapterKind::Conversion,
|
||||
"rank" => AdapterKind::Rank,
|
||||
_ => return Err(Error::new_spanned(kind, "Expected 'conversion' or 'rank' for 'adapter', e.g., adapter(rank)")),
|
||||
});
|
||||
}
|
||||
// Instructs the preprocessor to make this node available as a scope.
|
||||
// Other nodes can then access it with `#[scope(node::IDENTIFIER)]`.
|
||||
//
|
||||
@@ -629,24 +598,13 @@ impl Parse for NodeFnAttributes {
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., no_partial, ...)]
|
||||
"no_partial" => set_flag(&mut flags.no_partial, meta, "no_partial")?,
|
||||
// Marks a node that only code inserts into networks at runtime, so users never place it and documents never store it.
|
||||
// It replaces 'category', keeps the node out of the node catalog, and exempts it from versions and migrations.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(transient, ...)]
|
||||
"transient" => set_flag(&mut flags.transient, meta, "transient")?,
|
||||
// Makes a pending evaluation return the latest landed output instead of the placeholder
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., keep_previous, ...)]
|
||||
"keep_previous" => set_flag(&mut flags.keep_previous, meta, "keep_previous")?,
|
||||
_ => {
|
||||
return Err(Error::new_spanned(
|
||||
meta,
|
||||
indoc!(
|
||||
r#"
|
||||
Unsupported attribute in `node`.
|
||||
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'adapter', 'inject_scope', 'placeholder', 'no_partial', 'transient', 'keep_previous', and 'version'.
|
||||
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
|
||||
Example usage:
|
||||
#[node_macro::node(..., name("Test Node"), ...)]
|
||||
"#
|
||||
@@ -656,28 +614,17 @@ impl Parse for NodeFnAttributes {
|
||||
}
|
||||
}
|
||||
|
||||
match (&category, flags.transient) {
|
||||
(Some(category), true) => {
|
||||
return Err(Error::new_spanned(category, "The attributes 'transient' and 'category' cannot be combined"));
|
||||
}
|
||||
(None, false) => {
|
||||
return Err(Error::new_spanned(
|
||||
nested,
|
||||
indoc!(
|
||||
r#"
|
||||
One of the attributes 'category' or 'transient' is required.
|
||||
Example usage:
|
||||
#[node_macro::node(..., category("Value"), ...)]
|
||||
"#,
|
||||
),
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if flags.transient
|
||||
&& let Some(version) = nested.iter().find(|meta| meta.path().is_ident("version"))
|
||||
{
|
||||
return Err(Error::new_spanned(version, "The attributes 'transient' and 'version' cannot be combined"));
|
||||
if category.is_none() {
|
||||
return Err(Error::new_spanned(
|
||||
nested,
|
||||
indoc!(
|
||||
r#"
|
||||
The attribute 'category' is required.
|
||||
Example usage:
|
||||
#[node_macro::node(..., category("Value"), ...)]
|
||||
"#,
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(NodeFnAttributes {
|
||||
@@ -1791,28 +1738,6 @@ mod tests {
|
||||
assert!(error_message.contains("Versions start at 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transient() {
|
||||
let input = quote!(
|
||||
fn add(a: f64, b: f64) -> f64 {
|
||||
a + b
|
||||
}
|
||||
);
|
||||
|
||||
let transient = parse_node_fn(quote!(transient, memoize), input.clone()).unwrap();
|
||||
assert!(transient.attributes.flags.transient);
|
||||
assert_eq!(transient.attributes.category, None);
|
||||
|
||||
let error_message = parse_node_fn(quote!(transient, category("Math: Arithmetic")), input.clone()).unwrap_err().to_string();
|
||||
assert!(error_message.contains("'transient' and 'category' cannot be combined"));
|
||||
|
||||
let error_message = parse_node_fn(quote!(transient, version(2)), input.clone()).unwrap_err().to_string();
|
||||
assert!(error_message.contains("'transient' and 'version' cannot be combined"));
|
||||
|
||||
let error_message = parse_node_fn(quote!(memoize), input).unwrap_err().to_string();
|
||||
assert!(error_message.contains("One of the attributes 'category' or 'transient' is required"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_async_node() {
|
||||
let attr = quote!(category("IO"));
|
||||
|
||||
@@ -459,9 +459,6 @@ fn validate_async(parsed: &ParsedNodeFn) {
|
||||
if parsed.attributes.placeholder.is_some() && !parsed.is_async {
|
||||
emit_error!(parsed.fn_name.span(), "Only an async node can have a `placeholder`");
|
||||
}
|
||||
if parsed.attributes.flags.keep_previous && !parsed.is_async {
|
||||
emit_error!(parsed.fn_name.span(), "Only an async node can have `keep_previous`");
|
||||
}
|
||||
}
|
||||
|
||||
/// The arguments that aren't parameters, which are `#[data]` state and the inputs the compiler fills in, go after the parameters.
|
||||
|
||||
@@ -685,7 +685,7 @@ fn paint_overlay<T: PaintFitBounds>(
|
||||
mod test {
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::{ATTR_EFFECTS, Item};
|
||||
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
|
||||
use core_types::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::{Effects, Graphic};
|
||||
@@ -825,7 +825,10 @@ mod test {
|
||||
}
|
||||
|
||||
fn gradient_paints(transform: Option<DAffine2>, form: GradientForm) -> [Graphic; 2] {
|
||||
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_GRADIENT_FORM, form);
|
||||
let [start_curvature, end_curvature] = form.curvatures();
|
||||
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
|
||||
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature)
|
||||
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature);
|
||||
if let Some(transform) = transform {
|
||||
gradient.set_attribute(ATTR_TRANSFORM, transform);
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ fn basic_brush(
|
||||
Ok(List::new_from_item(Item::new_from_element(raster).with_attribute(ATTR_TRANSFORM, transform)))
|
||||
}
|
||||
|
||||
#[node_macro::node(transient, inject_scope)]
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
fn basic_brush_pipeline(
|
||||
_ctx: impl Ctx,
|
||||
#[scope(ProtoNodeIdentifier::new("graphene_std::platform_application_io::WgpuExecutorNode"))] executor: Item<WgpuExecutor>,
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{ATTR_EDITOR_FOOTPRINT_AREAS, ATTR_TRANSFORM, CloneVarArgs, Color, Context, ExtractAll, ExtractVarArgs, InjectFootprint, Interrupt, OwnedContextImpl};
|
||||
use core_types::list::Item;
|
||||
use core_types::{Color, ExtractVarArgs};
|
||||
use core_types::{Ctx, ExtractIndex, ExtractPosition};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
use graphic_types::{Artboard, Generator, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Graphic, Vector};
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ReadContextError {
|
||||
@@ -97,96 +96,6 @@ fn read_index(
|
||||
Ok(Item::new_from_element(at_loop_level(indices, *loop_level.element())? as f64))
|
||||
}
|
||||
|
||||
/// Evaluates the content with a fixed footprint in place of the one requested by the renderer, so the result no longer depends on the view.
|
||||
#[node_macro::node(category("Data: Context"))]
|
||||
fn bake_footprint<T>(
|
||||
ctx: impl Ctx + ExtractAll + CloneVarArgs + InjectFootprint,
|
||||
#[implementations(
|
||||
Context -> Item<bool>,
|
||||
Context -> Item<i64>,
|
||||
Context -> Item<f64>,
|
||||
Context -> Item<String>,
|
||||
Context -> Item<DAffine2>,
|
||||
Context -> Item<Footprint>,
|
||||
Context -> Item<DVec2>,
|
||||
Context -> Item<Vector>,
|
||||
Context -> Item<Graphic>,
|
||||
Context -> Item<Raster<CPU>>,
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> List<String>,
|
||||
Context -> List<f64>,
|
||||
Context -> List<DVec2>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
value: impl Node<Context<'static>, Output = T>,
|
||||
/// The area of the document and the resolution the content is evaluated at.
|
||||
#[default(0., 0., 1000., 1000.)]
|
||||
footprint: Item<Footprint>,
|
||||
#[node_path] node_path: Item<NodeIdPath>,
|
||||
) -> Result<T, Interrupt>
|
||||
where
|
||||
T: RecordFootprintArea,
|
||||
{
|
||||
let area = footprint.into_element();
|
||||
let unit_square_to_pixels = DAffine2::from_scale(area.resolution.as_dvec2());
|
||||
let footprint = Footprint {
|
||||
transform: unit_square_to_pixels * area.transform.inverse(),
|
||||
..area
|
||||
};
|
||||
|
||||
let new_context = OwnedContextImpl::from(ctx).with_footprint(footprint);
|
||||
let mut content = value.eval(&Some(new_context.into()))?;
|
||||
|
||||
content.record_footprint_area(node_path.element(), area.transform);
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
/// Content whose items can record the footprint areas they were evaluated in.
|
||||
pub trait RecordFootprintArea {
|
||||
/// Appends the area of the node at `node_path` to each item. `area` maps the unit square into the space the items are placed in.
|
||||
fn record_footprint_area(&mut self, node_path: &NodeIdPath, area: DAffine2);
|
||||
}
|
||||
|
||||
impl<T> RecordFootprintArea for Item<T> {
|
||||
fn record_footprint_area(&mut self, node_path: &NodeIdPath, area: DAffine2) {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let Some(footprint_area) = footprint_area_row(node_path, item_transform, area) else { return };
|
||||
|
||||
self.attribute_mut_or_insert_default::<List<NodeIdPath>>(ATTR_EDITOR_FOOTPRINT_AREAS).push(footprint_area);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> RecordFootprintArea for List<T> {
|
||||
fn record_footprint_area(&mut self, node_path: &NodeIdPath, area: DAffine2) {
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let Some(footprint_area) = footprint_area_row(node_path, item_transform, area) else { continue };
|
||||
|
||||
self.with_attribute_mut_or_default::<List<NodeIdPath>, _, _>(ATTR_EDITOR_FOOTPRINT_AREAS, index, |footprint_areas| footprint_areas.push(footprint_area));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The row recording the area relative to the item, so it follows the transforms later applied to the item.
|
||||
fn footprint_area_row(node_path: &NodeIdPath, item_transform: DAffine2, area: DAffine2) -> Option<Item<NodeIdPath>> {
|
||||
if item_transform.matrix2.determinant() == 0. {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Item::new_from_element(node_path.clone()).with_attribute(ATTR_TRANSFORM, item_transform.inverse() * area))
|
||||
}
|
||||
|
||||
/// The value of the loop `level` loops out from the innermost one, given the loops' values from the innermost outwards.
|
||||
fn at_loop_level<T>(levels: impl Iterator<Item = T>, level: i64) -> Result<T, ReadContextError> {
|
||||
let levels: Vec<T> = levels.collect();
|
||||
|
||||
@@ -13,19 +13,19 @@ fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T {
|
||||
}
|
||||
|
||||
/// Shifts a whole wire value onto a connector's type through the std `Into` trait, serving the whole-`List` erasure onto `ListDyn` under the input adapter identifier.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty: PhantomData<O>) -> O {
|
||||
value.into()
|
||||
}
|
||||
|
||||
/// Raises an `Item` wire onto a `List` connector as its one-element list.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn item_to_list<'i, T: 'i + Send>(_: impl Ctx, value: Item<T>) -> List<T> {
|
||||
value.into()
|
||||
}
|
||||
|
||||
/// Boxes a ranked wire's element into a type-erased attribute value, carrying the cell's attributes through the wire.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn item_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(
|
||||
_: impl Ctx,
|
||||
value: Item<T>,
|
||||
@@ -36,7 +36,7 @@ fn item_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt:
|
||||
}
|
||||
|
||||
/// Boxes a whole `List` wire as one type-erased attribute value, for attributes whose per-item value is itself a collection.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn list_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(
|
||||
_: impl Ctx,
|
||||
value: T,
|
||||
@@ -46,27 +46,27 @@ fn list_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt:
|
||||
}
|
||||
|
||||
/// Wraps a whole `List` onto the wire as one rank-0 `Item<Bundle<T>>` so an entire collection can feed a connector that carries it as one opaque cell.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn bundle<'i, T: 'i + Send>(_: impl Ctx, value: List<T>) -> Item<Bundle<T>> {
|
||||
Item::new_from_element(Bundle(value))
|
||||
}
|
||||
|
||||
/// Unwraps a `Bundle` wire back into the whole `List` it carries, restoring the collection after it passed through a connector as one opaque cell.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn unbundle<'i, T: 'i + Send>(_: impl Ctx, value: Item<Bundle<T>>) -> List<T> {
|
||||
value.into_element().0
|
||||
}
|
||||
|
||||
/// Converts an `Item` wire's element to a different element type it can produce through the std `Into` trait,
|
||||
/// letting a convertible wire feed an `Item` connector whose element type it does not match by identity.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn into_item<'i, T: 'i + Send + Into<E>, E: 'i + Send>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
Item::from_parts(value.into(), attributes)
|
||||
}
|
||||
|
||||
/// The `List` counterpart of `into_item`, converting every element to a different element type it can produce.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn into_list<'i, T: 'i + Send + Clone + Into<E>, E: 'i + Send>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
|
||||
value
|
||||
.into_iter()
|
||||
@@ -79,19 +79,19 @@ fn into_list<'i, T: 'i + Send + Clone + Into<E>, E: 'i + Send>(_: impl Ctx, valu
|
||||
|
||||
/// Moves a whole `Item` wire inside an element type like `Graphic` that embeds ranked values as its variants.
|
||||
/// The attributes describe the element they arrived with, so they travel inside it and the fresh envelope starts empty.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn embed_item<'i, T: 'i + Send, E: 'i + Send + From<Item<T>>>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
|
||||
Item::new_from_element(value.into())
|
||||
}
|
||||
|
||||
/// The `List` counterpart of `embed_item`, each item moving whole inside its own embedding element.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn embed_list<'i, T: 'i + Send + Clone, E: 'i + Send + From<Item<T>>>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
|
||||
value.into_iter().map(|item| Item::new_from_element(E::from(item))).collect()
|
||||
}
|
||||
|
||||
/// The [`Convert`]-based counterpart of `into_item`, casting an `Item` wire's element to a connector's numeric element type.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn convert_item<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
|
||||
let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT);
|
||||
let (value, attributes) = value.into_parts();
|
||||
@@ -100,7 +100,7 @@ fn convert_item<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx +
|
||||
}
|
||||
|
||||
/// The `List` counterpart of `convert_item`, casting every element to the connector's numeric element type.
|
||||
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
|
||||
#[node_macro::node(category("_Adapters"), skip_impl)]
|
||||
fn convert_list<'i, T: 'i + Send + Clone + Convert<E, ()>, E: 'i + Send + Clone>(ctx: impl Ctx + ExtractFootprint, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
|
||||
let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT);
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ use rand::seq::SliceRandom;
|
||||
use raster_kernels::value_effects;
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use std::cmp::Ordering;
|
||||
use vector_types::gradient::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread};
|
||||
use vector_types::gradient::{GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread};
|
||||
use vector_types::{Gradient, ReferencePoint};
|
||||
|
||||
/// Returns the list with the item at the specified index removed.
|
||||
@@ -649,7 +649,6 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
List<BlendMode>,
|
||||
List<GradientForm>,
|
||||
List<GradientSpread>,
|
||||
)]
|
||||
content: List<T>,
|
||||
@@ -806,24 +805,6 @@ fn read_attribute_blend_mode(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `GradientForm` attribute from the input list, outputting each value as an element of a new `GradientForm[]`.
|
||||
#[node_macro::node(category("Data: Attribute"), icon("NodeReadAttribute"))]
|
||||
fn read_attribute_gradient_form(
|
||||
_: impl Ctx,
|
||||
content: ListDyn,
|
||||
/// The attribute name (key) to read.
|
||||
#[constant]
|
||||
name: Item<String>,
|
||||
) -> List<GradientForm> {
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<GradientForm>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `GradientSpread` attribute from the input list, outputting each value as an element of a new `GradientSpread[]`.
|
||||
#[node_macro::node(category("Data: Attribute"), icon("NodeReadAttribute"))]
|
||||
fn read_attribute_gradient_spread(
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user