mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71e0099edd | ||
|
|
f3dafd9dc2 | ||
|
|
6f4ef1fe3d | ||
|
|
7469ecce35 | ||
|
|
d69b21f035 | ||
|
|
7e2e1fe028 | ||
|
|
12daaf8ab0 | ||
|
|
c465a3ebea | ||
|
|
8bcafc9dec | ||
|
|
0fbc09eabd | ||
|
|
017234b15b | ||
|
|
5f48595604 | ||
|
|
7aba423a2e | ||
|
|
16774db9c2 | ||
|
|
a4c0cb5c31 | ||
|
|
4059949762 | ||
|
|
d684bade6a | ||
|
|
436c943196 | ||
|
|
5add0191f4 | ||
|
|
c7e9aaa016 | ||
|
|
9c9b393420 | ||
|
|
01c5455ecf | ||
|
|
41586d6967 | ||
|
|
7c37cc504b | ||
|
|
e30bf2e987 | ||
|
|
c8e8fbf8d1 | ||
|
|
9517b006fa | ||
|
|
cfb45f2d54 | ||
|
|
e27119b58b |
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 {
|
||||
|
||||
@@ -150,20 +150,14 @@ jobs:
|
||||
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
|
||||
|
||||
- name: 📤 Publish to Cloudflare Pages
|
||||
if: inputs.merge_queue == false
|
||||
if: inputs.merge_queue == false && !github.event.pull_request.head.repo.fork
|
||||
id: cloudflare
|
||||
continue-on-error: ${{ github.event_name != 'push' }}
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
# Passed through the environment so a branch name can't inject shell syntax
|
||||
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
|
||||
run: |
|
||||
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
|
||||
echo "No Cloudflare API token available (fork PR), skipping deploy."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "${{ github.event_name }}" = "push" ]; then
|
||||
DEPLOY_BRANCH="master"
|
||||
else
|
||||
|
||||
@@ -51,6 +51,8 @@ jobs:
|
||||
with:
|
||||
# Cache on Cargo.lock file
|
||||
cache-on-failure: true
|
||||
# Saved only by master pushes, since a PR's saved cache is readable only by that PR yet counts toward the repo's size limit
|
||||
save-if: ${{ github.event_name == 'push' }}
|
||||
|
||||
- name: Install gungraun-runner and valgrind
|
||||
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
|
||||
|
||||
@@ -64,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
+8
-5
@@ -2675,7 +2675,6 @@ dependencies = [
|
||||
"math-nodes",
|
||||
"node-macro",
|
||||
"path-bool-nodes",
|
||||
"raster-kernels",
|
||||
"raster-nodes",
|
||||
"rendering",
|
||||
"repeat-nodes",
|
||||
@@ -5437,9 +5436,11 @@ dependencies = [
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"graphic-types",
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"node-macro",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5772,12 +5773,14 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6021,6 +6024,7 @@ dependencies = [
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
@@ -8075,7 +8079,6 @@ dependencies = [
|
||||
"log",
|
||||
"node-macro",
|
||||
"ollev",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -8083,7 +8086,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=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -8098,7 +8101,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=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -8112,7 +8115,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=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
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 = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
@@ -3,3 +3,4 @@
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
|
||||
rename!("blending_nodes::filters::AddNoiseNode"@1 => "blending_nodes::filters::SpeckleNode"@2);
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Migrations of the nodes in `graphene_core`.
|
||||
|
||||
mod fill_v1;
|
||||
mod passthrough_from_read_attribute_gradient_form_node;
|
||||
mod passthrough_from_upload_texture_node;
|
||||
mod renames;
|
||||
mod vary_colors_from_assign_colors;
|
||||
+36
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -6,5 +6,6 @@ mod mandelbrot_v2;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod noise_pattern_v2;
|
||||
mod passthrough_from_extend_image_to_bounds;
|
||||
mod pattern_square;
|
||||
mod renames;
|
||||
@@ -0,0 +1,36 @@
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// 'Extend Image to Bounds' is gone, and the transparent pixels it padded an image with drew nothing, so it passes its image on and drops its bounds.
|
||||
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
||||
pub fn passthrough_from_extend_image_to_bounds(inputs: &mut Inputs) {
|
||||
inputs.truncate(1);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PassthroughFromExtendImageToBounds, &contract());
|
||||
check_undo(&PassthroughFromExtendImageToBounds, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_image_and_drops_the_bounds() {
|
||||
let (image, bounds) = (literal(1.), literal(2.));
|
||||
|
||||
let mut fixture = Fixture::new(&PassthroughFromExtendImageToBounds);
|
||||
let extend = fixture.add(decl!("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1), vec![image.clone(), bounds]);
|
||||
let migrated = fixture.migrate(&PassthroughFromExtendImageToBounds).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, extend), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, extend), [image]);
|
||||
}
|
||||
}
|
||||
@@ -4,3 +4,12 @@ use migration_core::rename;
|
||||
|
||||
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
|
||||
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
|
||||
|
||||
// 'Image to Channels' became 'Into Channels', taking and giving graphics, whose stored input and channel outputs keep their places
|
||||
rename!("raster_nodes::adjustments::ImageToChannelsNode"@1 => "raster_nodes::channels::IntoChannelsNode"@2);
|
||||
|
||||
// 'Channels to Image' became 'From Channels', taking and giving graphics, whose stored inputs and output keep their places
|
||||
rename!("raster_nodes::std_nodes::ChannelsToImageNode"@1 => "raster_nodes::channels::FromChannelsNode"@2);
|
||||
|
||||
// 'Median Filter' became an effect taking any graphic, whose stored image and radius keep their places
|
||||
rename!("raster_nodes::filter::MedianFilterNode"@1 => @2);
|
||||
@@ -878,6 +878,22 @@ pub struct SliderMarker {
|
||||
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
|
||||
#[serde(rename = "betweenNeighbors")]
|
||||
between_neighbors: bool,
|
||||
/// How this marker and the next may pass each other.
|
||||
#[serde(rename = "overlapNext")]
|
||||
overlap_next: MarkerOverlap,
|
||||
}
|
||||
|
||||
/// How a slider marker and the next may pass each other, as split handles whose ranges may overlap.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MarkerOverlap {
|
||||
/// Neither may pass the other.
|
||||
#[default]
|
||||
Never,
|
||||
/// Each may pass the other but not the marker beyond it, so split handles' inner halves can overlap while the handles can't pass each other.
|
||||
NextOnly,
|
||||
/// The markers up to this one and those after it don't bound each other, so split handles can pass each other entirely.
|
||||
Freely,
|
||||
}
|
||||
|
||||
impl SliderMarker {
|
||||
@@ -890,6 +906,7 @@ impl SliderMarker {
|
||||
paired_with_next: false,
|
||||
dashed_to_next: false,
|
||||
between_neighbors: false,
|
||||
overlap_next: MarkerOverlap::Never,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -907,6 +924,11 @@ impl SliderMarker {
|
||||
self.dashed_to_next = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
||||
self.overlap_next = overlap;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
|
||||
@@ -5,10 +5,14 @@ use crate::test_utils::gpu_executor;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::application_io::Texture;
|
||||
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
|
||||
use graphene_std::graphic::{IntoGraphicList, extend};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::math_nodes::{color_value, gradient_value};
|
||||
use graphene_std::raster_nodes::std_nodes::noise_pattern;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -136,6 +140,111 @@ fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
|
||||
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
|
||||
}
|
||||
|
||||
/// Endless content a layer can hold, which fills the whole canvas unless something clips it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Endless {
|
||||
Color,
|
||||
Gradient,
|
||||
NoisePattern,
|
||||
}
|
||||
|
||||
/// A document viewed in the `render_mode` with a blue rectangle filling (50, 50) to (130, 130).
|
||||
async fn document_with_a_rectangle(render_mode: RenderMode) -> EditorTestUtils {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
|
||||
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
editor.select_primary_color(blue).await;
|
||||
editor.select_secondary_color(blue).await;
|
||||
editor.draw_rect(50., 50., 130., 130.).await;
|
||||
|
||||
editor
|
||||
}
|
||||
|
||||
/// Adds a new layer of `endless` content above the selected layer, clipped to it as by an Alt-click between them.
|
||||
async fn add_clipped_endless_layer(editor: &mut EditorTestUtils, endless: Endless) {
|
||||
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
|
||||
let layer = editor.get_selected_layer().await.expect("the new layer is selected");
|
||||
let node = match endless {
|
||||
Endless::Color => color_value::IDENTIFIER,
|
||||
Endless::Gradient => gradient_value::IDENTIFIER,
|
||||
Endless::NoisePattern => noise_pattern::IDENTIFIER,
|
||||
};
|
||||
let node_type = DefinitionIdentifier::ProtoNode(node);
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||
editor.handle_message(DocumentMessage::ClipLayer { id: layer.to_node() }).await;
|
||||
}
|
||||
|
||||
/// Evaluates the document for a viewport of `size` as the app does, returning what the frontend is sent and the frame the runtime presents.
|
||||
async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<FrontendMessage>, Option<Texture>) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.expect("a document is open");
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).expect("the active document exists");
|
||||
let submitted = executor
|
||||
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.expect("the evaluation is submitted");
|
||||
|
||||
let mut messages = editor.dispatch(submitted);
|
||||
editor.runtime.update();
|
||||
let frame = editor.runtime.run().await;
|
||||
messages.extend(editor.dispatch(Message::Wake));
|
||||
|
||||
(messages, frame)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn endless_layers_clip_to_the_shape_beneath_them() {
|
||||
let size = UVec2::new(256, 256);
|
||||
|
||||
let frame_pixels = async |editor: &mut EditorTestUtils| {
|
||||
let (_, frame) = evaluate_viewport(editor, size).await;
|
||||
let frame = frame.expect("the viewport presents a frame");
|
||||
gpu_executor().read_texture_pixels(&frame).expect("the frame reads back")
|
||||
};
|
||||
let pixel = |pixels: &[u8], x: u32, y: u32| {
|
||||
let index = (y * size.x + x) as usize * 4;
|
||||
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
|
||||
};
|
||||
|
||||
for endless in [Endless::Color, Endless::Gradient, Endless::NoisePattern] {
|
||||
// In the viewport's Vello render, the endless content covers the rectangle but leaves the canvas past it as the rectangle alone left it
|
||||
let mut editor = document_with_a_rectangle(RenderMode::Normal).await;
|
||||
let rectangle_alone = frame_pixels(&mut editor).await;
|
||||
add_clipped_endless_layer(&mut editor, endless).await;
|
||||
let clipped = frame_pixels(&mut editor).await;
|
||||
|
||||
assert_ne!(pixel(&clipped, 90, 90), pixel(&rectangle_alone, 90, 90), "{endless:?}: the content shows within the rectangle");
|
||||
for (x, y) in [(20, 20), (200, 90), (90, 200), (230, 230)] {
|
||||
assert_eq!(
|
||||
pixel(&clipped, x, y),
|
||||
pixel(&rectangle_alone, x, y),
|
||||
"{endless:?}: the content is clipped away at ({x}, {y}), past the rectangle"
|
||||
);
|
||||
}
|
||||
|
||||
// In SVG Preview, the endless content is drawn only within the rectangle's mask
|
||||
let mut editor = document_with_a_rectangle(RenderMode::SvgPreview).await;
|
||||
add_clipped_endless_layer(&mut editor, endless).await;
|
||||
let (messages, _) = evaluate_viewport(&mut editor, size).await;
|
||||
let svg = messages
|
||||
.into_iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the viewport's artwork is sent as SVG");
|
||||
|
||||
let (unmasked, masked) = svg.split_once(r#"mask="url(#mask-"#).unwrap_or_else(|| panic!("{endless:?}: the content is masked: {svg}"));
|
||||
let draws_endless_content = |markup: &str| ["<polyline", "<foreignObject"].iter().any(|tag| markup.contains(tag));
|
||||
assert!(
|
||||
!draws_endless_content(unmasked) && draws_endless_content(masked),
|
||||
"{endless:?}: the content is drawn within the mask: {svg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
|
||||
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
|
||||
|
||||
@@ -31,12 +31,13 @@ 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, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
|
||||
StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
|
||||
MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource,
|
||||
GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||
};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use kurbo::BezPath;
|
||||
@@ -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,7 @@ macro_rules! inspectable_types {
|
||||
Item<DAffine2>,
|
||||
Item<BlendMode>,
|
||||
Item<GradientForm>,
|
||||
Item<GradientModel>,
|
||||
Item<GradientSpread>,
|
||||
Item<GradientSpace>,
|
||||
Item<GradientHueDirection>,
|
||||
@@ -1277,12 +1278,14 @@ impl_table_item_layout_for_choice_enum!(
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -1472,11 +1475,13 @@ macro_rules! known_item_types {
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
|
||||
@@ -4138,7 +4138,7 @@ impl DocumentMessageHandler {
|
||||
})
|
||||
.unwrap_or((None, None, None));
|
||||
|
||||
let blend_mode_menu_entries = BlendMode::list_svg_subset()
|
||||
let blend_mode_menu_entries = BlendMode::list()
|
||||
.iter()
|
||||
.map(|modes| {
|
||||
modes
|
||||
@@ -4155,7 +4155,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
let widgets = vec![
|
||||
DropdownInput::new(blend_mode_menu_entries)
|
||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32))
|
||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32))
|
||||
.disabled(disabled)
|
||||
.draw_icon(false)
|
||||
.sizing(WidgetSizing::default().grow(false))
|
||||
|
||||
@@ -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>,
|
||||
|
||||
+2
-2
@@ -1034,7 +1034,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
||||
space: gradient_info.spaces.get(linear.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
||||
..Default::default()
|
||||
};
|
||||
modify_inputs.fill_gradient_set(gradient, 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 +1062,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
||||
space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
||||
..Default::default()
|
||||
};
|
||||
modify_inputs.fill_gradient_set(gradient, 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,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{
|
||||
ReplaceablePaintChain, 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_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;
|
||||
@@ -450,7 +450,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,11 +491,22 @@ 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
|
||||
let curvatures = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
|
||||
if let Some(gradient_form) = gradient_form
|
||||
&& curvatures.is_some_and(|curvatures| GradientForm::from_curvatures(curvatures) != Some(gradient_form))
|
||||
{
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let [start_curvature, end_curvature] = gradient_form.curvatures();
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, StartCurvatureInput),
|
||||
NodeInput::value(TaggedValue::Number(start_curvature), false),
|
||||
true,
|
||||
);
|
||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end_curvature), false), true);
|
||||
}
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
|
||||
if existing_fill_node_id.is_none() {
|
||||
self.restore_default_stroke_order();
|
||||
@@ -761,20 +773,28 @@ 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) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let 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(curvatures) = gradient_curvature_values(node) else { return };
|
||||
if GradientForm::from_curvatures(curvatures) == Some(gradient_form) {
|
||||
return;
|
||||
}
|
||||
|
||||
let [start, end] = gradient_form.curvatures();
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
}
|
||||
|
||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::application::Environment;
|
||||
use crate::consts::{
|
||||
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
|
||||
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
DOUBLE_CLICK_ALLOWED_TRAVEL, VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX,
|
||||
VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
};
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
|
||||
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{MouseKeys, ViewportPosition};
|
||||
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
|
||||
use crate::messages::portfolio::document::utility_types::misc::PTZ;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
@@ -34,6 +34,8 @@ pub struct NavigationMessageHandler {
|
||||
abortable_pan_start: Option<f64>,
|
||||
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
|
||||
artwork_behind_graph: bool,
|
||||
/// Where a middle press began panning the open node graph, kept until the pointer travels too far for its release to still be a click.
|
||||
graph_middle_click_start: Option<ViewportPosition>,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -99,6 +101,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
return;
|
||||
};
|
||||
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
|
||||
|
||||
// Released before traveling far, a middle press that pans the open graph is instead a click on the node under it
|
||||
let middle_press_in_graph = graph_view_overlay_open && ipp.mouse.mouse_keys == MouseKeys::MIDDLE;
|
||||
self.graph_middle_click_start = middle_press_in_graph.then_some(ipp.mouse.position);
|
||||
}
|
||||
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
|
||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||
@@ -341,6 +347,13 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
responses.add(ToolMessage::UpdateCursor);
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
responses.add(NavigateToolMessage::End);
|
||||
|
||||
// Not a pan after all, but a middle click in the graph
|
||||
let middle_click_start = self.graph_middle_click_start.take();
|
||||
let middle_released = !ipp.mouse.mouse_keys.contains(MouseKeys::MIDDLE);
|
||||
if !abort_transform && middle_released && middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL) {
|
||||
responses.add(NodeGraphMessage::MiddleClick);
|
||||
}
|
||||
}
|
||||
NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
|
||||
self.finish_operation_with_click = false;
|
||||
@@ -417,6 +430,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
}
|
||||
NavigationMessage::PointerMove { snap } => {
|
||||
if self.graph_middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) > DOUBLE_CLICK_ALLOWED_TRAVEL) {
|
||||
self.graph_middle_click_start = None;
|
||||
}
|
||||
|
||||
match self.navigation_operation {
|
||||
NavigationOperation::None => {}
|
||||
NavigationOperation::Pan { .. } => {
|
||||
|
||||
@@ -5,16 +5,19 @@ use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
|
||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
||||
};
|
||||
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
|
||||
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
@@ -37,11 +40,6 @@ impl NodeInspectorContext<'_> {
|
||||
let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
|
||||
let widget_override = input_inspector_row.widget_override.clone()?;
|
||||
|
||||
// Older documents store number and Vec2 widget settings this way, but they come from the definition's parameter
|
||||
if matches!(widget_override.as_str(), "number" | "vec2") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
|
||||
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||
return None;
|
||||
@@ -53,11 +51,11 @@ impl NodeInspectorContext<'_> {
|
||||
}
|
||||
|
||||
/// Input position of the location parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
|
||||
/// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::DimensionsInput::INDEX;
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
|
||||
/// Input position of the control path parameter on the "Blend" network node template.
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = graphene_std::subgraphs::blend::PathInput::INDEX;
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
|
||||
|
||||
/// The key used to access definitions for a network node or proto node.
|
||||
/// For proto nodes, this is their [`ProtoNodeIdentifier`].
|
||||
@@ -109,7 +107,8 @@ pub struct DocumentNodeDefinition {
|
||||
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
|
||||
pub identifier: &'static str,
|
||||
|
||||
/// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
|
||||
/// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly.
|
||||
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
|
||||
pub version: u32,
|
||||
|
||||
/// The default [`NodeTemplate`] this definition instantiates.
|
||||
@@ -137,9 +136,529 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
|
||||
|
||||
/// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry).
|
||||
/// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built.
|
||||
/// A proto node within a definition takes its input and output metadata from the node macro in NODE_METADATA, and its display name too unless the definition gives one.
|
||||
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
||||
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
document_node_derive::derive_definitions()
|
||||
let custom = vec![
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
nodes: [
|
||||
// Primary (bottom) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
// Secondary (left) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of layers below this one, which the content is placed above.").into(),
|
||||
("Content", "The artwork this layer adds to the stack as a single item.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Artboard",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
|
||||
NodeInput::import(item!(TaggedValue), 2),
|
||||
NodeInput::import(item!(TaggedValue), 3),
|
||||
NodeInput::import(item!(TaggedValue), 4),
|
||||
NodeInput::import(item!(TaggedValue), 5),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Artboard), true),
|
||||
NodeInput::type_default(list!(Graphic), true),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
|
||||
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of artboards below this one, which this artboard is placed above.").into(),
|
||||
("Content", "Graphics to include within the artboard.").into(),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Location",
|
||||
"Coordinate of the top-left corner of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "X".to_string(),
|
||||
y: "Y".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Dimensions",
|
||||
"Width and height of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "W".to_string(),
|
||||
y: "H".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())),
|
||||
("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Blend",
|
||||
version: 1,
|
||||
category: "Vector: Deform",
|
||||
icon: Some("NodeBlend"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(16), 0)],
|
||||
nodes: [
|
||||
// 0: Separate Paths (split the vector into its individual paths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::separate_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Count (number of subpaths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::count::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Max (clamp subpath count to at least 1 for empty path case)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Number (the integer count enters the network's decimal math)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(item!(i64), 1)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Multiply (total_instances = count × subpath_count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Subtract (count - 1, open subpath denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Read Index (current repetition index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Divide (index / count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
|
||||
..Default::default()
|
||||
},
|
||||
// 8: Floor (floor(index / count) = subpath index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(7), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 9: Modulo (index % count = local index within subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 10: Path Is Closed (check if current subpath is closed)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::switch::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
|
||||
..Default::default()
|
||||
},
|
||||
// 12: Divide (local_index / denominator = within-subpath fraction)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 14: Add (subpath_index + clamped fraction = progression)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::add::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 15: Morph (content, progression, reverse, distribution, path)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::morph::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::node(NodeId(14), 0),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
|
||||
NodeInput::import(item!(Vector), 4),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
|
||||
..Default::default()
|
||||
},
|
||||
// 16: Repeat
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 17: Max (clamp count to at least 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::Integer(10), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Content", "The vector objects to create intermediate shapes between.").into(),
|
||||
(
|
||||
"Count",
|
||||
"The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.",
|
||||
)
|
||||
.into(),
|
||||
("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(),
|
||||
("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(),
|
||||
(
|
||||
"Path",
|
||||
"An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.",
|
||||
)
|
||||
.into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Origins to Polyline",
|
||||
version: 1,
|
||||
category: "Vector: Path",
|
||||
icon: Some("NodeOriginsToPolyline"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(7), 0)],
|
||||
nodes: [
|
||||
// 0: Read Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Extract Transform
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::extract_transform::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Decompose Translation
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::decompose_translation::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Vector (auto-converts the decomposed translation into a single-anchor List<Vector>)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::as_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Flatten Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Map
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Combine Paths
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Points to Polyline
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::points_to_polyline::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::value(TaggedValue::Bool(false), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Vector), true)],
|
||||
input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()],
|
||||
output_names: vec!["Vector".to_string()],
|
||||
output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Load Image",
|
||||
version: 1,
|
||||
category: "Data: I/O",
|
||||
icon: Some("NodeLoadImage"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
|
||||
input_metadata: vec![
|
||||
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
|
||||
("URL", "The web address or local asset path of the image to load.").into(),
|
||||
],
|
||||
output_names: vec!["Image".to_string()],
|
||||
output_descriptions: vec!["The loaded image.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Loads an image from a given URL."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Regex Find",
|
||||
version: 1,
|
||||
category: "String: Regex",
|
||||
icon: Some("NodeRegexFind"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![
|
||||
// Primary output: the whole match (String)
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
// Secondary output: capture groups (List<String>), each item carries `start`/`end`/`name` attributes from `regex_find`
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
nodes: [
|
||||
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(item!(String), 0),
|
||||
NodeInput::import(item!(String), 1),
|
||||
NodeInput::import(item!(i64), 2),
|
||||
NodeInput::import(item!(bool), 3),
|
||||
NodeInput::import(item!(bool), 4),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::String(String::new()), true),
|
||||
NodeInput::value(TaggedValue::String(String::new()), false),
|
||||
NodeInput::value(TaggedValue::Integer(0), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("String", "The string to search within.").into(),
|
||||
("Pattern", "The regular expression pattern to search for.").into(),
|
||||
(
|
||||
"Match Index",
|
||||
"Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.",
|
||||
)
|
||||
.into(),
|
||||
("Case Insensitive", "Match letters regardless of case.").into(),
|
||||
("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(),
|
||||
],
|
||||
output_names: vec!["Match".to_string(), "Captures".to_string()],
|
||||
output_descriptions: vec![
|
||||
"The whole portion of the string matching the pattern, or empty if there is no match.".to_string(),
|
||||
"The text matched by each capture group in the pattern, in order.".to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed(
|
||||
r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#,
|
||||
),
|
||||
inspector: None,
|
||||
},
|
||||
];
|
||||
|
||||
document_node_derive::post_process_nodes(custom)
|
||||
}
|
||||
|
||||
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
|
||||
@@ -157,6 +676,7 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
|
||||
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
|
||||
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
|
||||
map.insert("blend_if_inspector".to_string(), Box::new(node_inspector::blend_if_inspector));
|
||||
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
|
||||
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
|
||||
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
|
||||
@@ -166,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));
|
||||
@@ -218,10 +739,91 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"number".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
if let Some(unit) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
{
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
if let Some(min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.min(min);
|
||||
}
|
||||
if let Some(max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.max(max);
|
||||
}
|
||||
if let Some(step) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "step", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.step(step);
|
||||
}
|
||||
if let Some(mode) = context.network_interface.input_data(&node_id, index, "mode", context.selection_network_path).map(|value| {
|
||||
let mode: NumberInputMode = serde_json::from_value(value.clone()).unwrap();
|
||||
mode
|
||||
}) {
|
||||
number_input = number_input.mode(mode);
|
||||
}
|
||||
if let Some(range_min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_min(Some(range_min));
|
||||
}
|
||||
if let Some(range_max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_max(Some(range_max));
|
||||
}
|
||||
if let Some(is_integer) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
{
|
||||
number_input = number_input.is_integer(is_integer);
|
||||
}
|
||||
let blank_assist = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "blank_assist", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get blank assist when displaying number input for node {node_id}, index {index}");
|
||||
true
|
||||
});
|
||||
|
||||
Ok(vec![LayoutGroup::row(node_inspector::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context),
|
||||
number_input,
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// The custom number input settings are only available on proto nodes
|
||||
"optional_f64".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) {
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
if let Some(field) = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
{
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
@@ -352,6 +954,57 @@ fn static_input_inspector() -> InputInspector {
|
||||
"type_choice".to_string(),
|
||||
Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
|
||||
);
|
||||
map.insert(
|
||||
"vec2".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let x = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "x", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get x for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let y = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "y", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get y for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let unit = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get unit for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let min = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64());
|
||||
let is_integer = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
&x,
|
||||
&y,
|
||||
&unit,
|
||||
min,
|
||||
is_integer,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_scale".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -524,7 +1177,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
||||
)])
|
||||
@@ -541,7 +1193,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
||||
)])
|
||||
@@ -648,7 +1299,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
" px",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -664,7 +1314,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"H",
|
||||
"x",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -785,7 +1434,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"vec2_uv".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)])
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false, false)])
|
||||
}),
|
||||
);
|
||||
map
|
||||
@@ -1033,18 +1682,6 @@ mod test {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// A `#[graph]` node with an inner node that has no definition is left out of the catalog with only a logged error
|
||||
#[test]
|
||||
fn every_registered_graph_has_a_definition() {
|
||||
// Released before resolving, since building the catalog locks the registry too
|
||||
let identifiers: Vec<&str> = graphene_std::registry::GRAPH_METADATA.lock().unwrap().iter().map(|graph| graph.identifier).collect();
|
||||
assert!(!identifiers.is_empty(), "the `#[graph]` nodes in `graphene_std::subgraphs` should be registered");
|
||||
|
||||
for identifier in identifiers {
|
||||
assert!(resolve_network_node_type(identifier).is_some(), "the '{identifier}' graph should have a definition");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||
use glam::{DAffine2, UVec2};
|
||||
@@ -1185,36 +1822,21 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn every_definition_default_value_satisfies_its_constraint() {
|
||||
// Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too
|
||||
fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec<String>) {
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name);
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
let name = &definition.node_template.display_name;
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name);
|
||||
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() {
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() {
|
||||
if let Some(value) = input.as_value()
|
||||
&& !constraint.accepts_default_value(&value.ty())
|
||||
{
|
||||
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty()));
|
||||
}
|
||||
|
||||
let takes_nothing = matches!(constraint, InputTypeConstraint::Limited(types) if !types.is_empty() && types.iter().all(|ty| ty == "()"));
|
||||
if takes_nothing && matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }) {
|
||||
violations.push(format!("{name} input {index}: a wire feeds it, but it takes nothing"));
|
||||
}
|
||||
}
|
||||
|
||||
if let NodeTemplateImplementation::Network(network) = &node_template.implementation {
|
||||
for (node_id, inner) in &network.nodes {
|
||||
check(inner, &format!("{name}, node {node_id}"), violations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
check(&definition.node_template, &definition.node_template.display_name, &mut violations);
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1231,7 +1853,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(String)));
|
||||
@@ -1245,7 +1867,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode2() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
|
||||
@@ -1254,8 +1876,8 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn network() {
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let inner_network = NodeNetworkTemplate {
|
||||
|
||||
+30
-421
@@ -1,17 +1,11 @@
|
||||
use super::DocumentNodeDefinition;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride,
|
||||
};
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
|
||||
use graphene_std::registry::*;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs.
|
||||
pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let mut definitions_map = HashMap::new();
|
||||
|
||||
// Add the protonodes from the macro.
|
||||
@@ -81,7 +75,16 @@ pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNode
|
||||
inputs,
|
||||
call_argument: input_type.clone(),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
||||
input_metadata: input_metadata(fields),
|
||||
// TODO: Store information for input overrides in the node macro
|
||||
input_metadata: fields
|
||||
.iter()
|
||||
.map(|f| match f.widget_override {
|
||||
RegistryWidgetOverride::None => (f.name, f.description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
|
||||
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
|
||||
})
|
||||
.collect(),
|
||||
output_names,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -93,242 +96,25 @@ pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNode
|
||||
);
|
||||
}
|
||||
|
||||
let graphs = GRAPH_METADATA.lock().unwrap().clone();
|
||||
add_graph_definitions(graphs, &mut definitions_map);
|
||||
// Add the hand-written network nodes to the map and add the metadata for their internal protonodes
|
||||
for mut network_node in custom {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
|
||||
}
|
||||
|
||||
definitions_map
|
||||
}
|
||||
|
||||
/// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports.
|
||||
/// The rest of a parameter's widget settings are read from its field when the Inspector draws it.
|
||||
fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let (name, description) = (field.name, field.description);
|
||||
match field.widget_override {
|
||||
RegistryWidgetOverride::None => (name, description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())),
|
||||
RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Why a `#[graph]` node has no definition yet, or can't have one.
|
||||
enum GraphDefinitionError {
|
||||
/// A node inside it has no definition, which may be another graph not yet added.
|
||||
MissingNode(String),
|
||||
/// The graph's wiring is invalid, so it's left out of the catalog.
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
/// Adds the nodes defined as subgraphs by `#[graph]`, each once the definitions of the nodes inside it exist.
|
||||
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
|
||||
let mut identifier_counts = HashMap::new();
|
||||
for graph in &graphs {
|
||||
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
|
||||
}
|
||||
let mut rejected = HashSet::new();
|
||||
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
|
||||
.into_iter()
|
||||
.filter(|graph| {
|
||||
let taken = identifier_counts[graph.identifier] > 1;
|
||||
if taken {
|
||||
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
}
|
||||
!taken
|
||||
})
|
||||
.map(|graph| (graph, String::new()))
|
||||
.collect();
|
||||
|
||||
loop {
|
||||
let pending_count = pending_graphs.len();
|
||||
|
||||
let mut ready = Vec::new();
|
||||
pending_graphs.retain_mut(|(graph, missing)| {
|
||||
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
|
||||
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
|
||||
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(inner_graph) = rejected_inner_graph {
|
||||
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
return false;
|
||||
}
|
||||
|
||||
match graph_definition(graph, definitions_map) {
|
||||
Ok(definition) => {
|
||||
ready.push(definition);
|
||||
false
|
||||
}
|
||||
Err(GraphDefinitionError::MissingNode(missing_node)) => {
|
||||
*missing = missing_node;
|
||||
true
|
||||
}
|
||||
Err(GraphDefinitionError::Invalid(reason)) => {
|
||||
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
for definition in ready {
|
||||
let definition = prepare_network_definition(definition, definitions_map);
|
||||
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
|
||||
}
|
||||
|
||||
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (graph, missing_node) in pending_graphs {
|
||||
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills a network definition's nested proto node metadata and points its network at the definition.
|
||||
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
network_node
|
||||
}
|
||||
|
||||
/// Builds the catalog definition of a node defined as a subgraph by `#[graph]`.
|
||||
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
|
||||
let mut nodes = HashMap::new();
|
||||
for (index, node) in graph.nodes.iter().enumerate() {
|
||||
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
|
||||
let (identifier, name) = match &node.implementation {
|
||||
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
|
||||
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
|
||||
};
|
||||
let Some(definition) = definitions_map.get(&identifier) else {
|
||||
return Err(GraphDefinitionError::MissingNode(name));
|
||||
};
|
||||
let mut template = definition.default_node_template();
|
||||
|
||||
if let Some(call_argument) = &node.call_argument {
|
||||
template.call_argument = call_argument.clone();
|
||||
}
|
||||
template.visible = !node.hidden;
|
||||
template.locked = node.locked;
|
||||
template.pinned = node.pinned;
|
||||
if let Some(display_name) = node.display_name {
|
||||
template.display_name = display_name.to_string();
|
||||
}
|
||||
|
||||
let position = node.position.map_or(IVec2::ZERO, |(x, y)| IVec2::new(x, y));
|
||||
template.node_type_metadata = if node.layer {
|
||||
NodeTypePersistentMetadata::layer(position)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(position)
|
||||
};
|
||||
|
||||
for (input_index, source) in &node.inputs {
|
||||
let Some(input) = template.inputs.get_mut(*input_index) else {
|
||||
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
|
||||
};
|
||||
|
||||
// An input the compiler fills in can't be set, which the macro already prevents for the graphs it builds
|
||||
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
|
||||
return Err(GraphDefinitionError::Invalid(format!(
|
||||
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
|
||||
)));
|
||||
}
|
||||
|
||||
*input = graph_input(source, input);
|
||||
}
|
||||
|
||||
nodes.insert(NodeId(index as u64), template);
|
||||
}
|
||||
|
||||
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
|
||||
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
|
||||
|
||||
let exports = graph.exports.iter().map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false))).collect();
|
||||
|
||||
Ok(DocumentNodeDefinition {
|
||||
identifier: graph.identifier,
|
||||
version: graph.version,
|
||||
category: graph.category,
|
||||
icon: graph.icon,
|
||||
description: Cow::Borrowed(graph.description),
|
||||
inspector: None,
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
|
||||
inputs,
|
||||
input_metadata: input_metadata(&graph.imports),
|
||||
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
|
||||
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
|
||||
node_type_metadata: if graph.layer {
|
||||
NodeTypePersistentMetadata::layer(IVec2::ZERO)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(IVec2::ZERO)
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
|
||||
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> NodeInput {
|
||||
match source {
|
||||
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
|
||||
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
|
||||
GraphInputSource::Value { value, exposed } => {
|
||||
let ty = match default {
|
||||
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
|
||||
NodeInput::Import { import_type, .. } => import_type.clone(),
|
||||
_ => generic!(T),
|
||||
};
|
||||
NodeInput::value(graph_value(value, &ty), exposed.unwrap_or(default.is_exposed()))
|
||||
}
|
||||
GraphInputSource::Scope(key) => NodeInput::scope(*key),
|
||||
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
|
||||
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
|
||||
fn element_type(ty: &Type) -> &Type {
|
||||
let mut element = ty;
|
||||
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
|
||||
element = inner;
|
||||
}
|
||||
element
|
||||
}
|
||||
|
||||
/// Converts a value written in a graph definition to the type of the input it feeds.
|
||||
fn graph_value(value: &GraphValue, ty: &Type) -> TaggedValue {
|
||||
// An integer literal feeds an integer input as an integer, and any other as a number
|
||||
let is_integer = *element_type(ty) == concrete!(i64);
|
||||
|
||||
match value {
|
||||
GraphValue::Integer(integer) if is_integer => TaggedValue::Integer(*integer),
|
||||
GraphValue::Integer(integer) => TaggedValue::Number(*integer as f64),
|
||||
GraphValue::Number(number) => TaggedValue::Number(*number),
|
||||
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
|
||||
GraphValue::String(string) => TaggedValue::String(string.clone()),
|
||||
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
|
||||
GraphValue::Color(color) => TaggedValue::Color(*color),
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
|
||||
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
|
||||
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
match &mut node_template.implementation {
|
||||
NodeTemplateImplementation::Network(network_template) => {
|
||||
@@ -342,190 +128,13 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
|
||||
return;
|
||||
};
|
||||
|
||||
// A display name, lock, or pin the network's author gave the node is kept
|
||||
let definition_template = &definition.node_template;
|
||||
if node_template.display_name.is_empty() {
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
}
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
node_template.input_metadata = definition_template.input_metadata.clone();
|
||||
node_template.output_names = definition_template.output_names.clone();
|
||||
node_template.locked |= definition_template.locked;
|
||||
node_template.pinned |= definition_template.pinned;
|
||||
node_template.locked = definition_template.locked;
|
||||
node_template.pinned = definition_template.pinned;
|
||||
}
|
||||
NodeTemplateImplementation::Definition(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
|
||||
fn number_import() -> FieldMetadata {
|
||||
FieldMetadata {
|
||||
name: "Value",
|
||||
description: "",
|
||||
internal: false,
|
||||
exposed: true,
|
||||
widget_override: RegistryWidgetOverride::None,
|
||||
value_source: RegistryValueSource::None,
|
||||
default_colors: None,
|
||||
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
number_hard_max: None,
|
||||
number_mode_range: false,
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph exporting one node, which is fed by the given inputs.
|
||||
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
|
||||
GraphMetadata {
|
||||
identifier,
|
||||
category: "Test",
|
||||
icon: None,
|
||||
description: "",
|
||||
version: 1,
|
||||
layer: false,
|
||||
imports: vec![number_import()],
|
||||
exports: vec![GraphExportMetadata {
|
||||
name: "Out",
|
||||
description: "",
|
||||
source: GraphInputSource::Node { node: 0, output: 0 },
|
||||
}],
|
||||
nodes: vec![GraphNodeMetadata {
|
||||
implementation,
|
||||
inputs,
|
||||
position: None,
|
||||
layer: false,
|
||||
display_name: None,
|
||||
hidden: false,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
call_argument: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn from_import() -> Vec<(usize, GraphInputSource)> {
|
||||
let ty = Type::Item(Box::new(concrete!(f64)));
|
||||
vec![(0, GraphInputSource::Import { index: 0, ty })]
|
||||
}
|
||||
|
||||
/// The definitions a test graph builds on: only the As Number proto node.
|
||||
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
|
||||
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
|
||||
HashMap::from([(identifier, definition)])
|
||||
}
|
||||
|
||||
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
|
||||
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
|
||||
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
|
||||
let inner = one_node_graph("Test Inner", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![outer, inner], &mut definitions_map);
|
||||
|
||||
assert!(has_graph(&definitions_map, "Test Inner"));
|
||||
assert!(has_graph(&definitions_map, "Test Outer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
|
||||
let mut inputs = from_import();
|
||||
inputs.push((
|
||||
100,
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Number(1.),
|
||||
exposed: None,
|
||||
},
|
||||
));
|
||||
let graph = one_node_graph("Test Missing Input", math_nodes::as_number::IDENTIFIER.into(), inputs);
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Missing Input"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
|
||||
let first = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let second = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Twin"));
|
||||
assert!(!has_graph(&definitions_map, "Test Dependent"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_integer_value_takes_the_type_of_the_input_it_feeds() {
|
||||
let integer = Type::Item(Box::new(concrete!(i64)));
|
||||
let number = Type::Item(Box::new(concrete!(f64)));
|
||||
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &integer), TaggedValue::Integer(3)));
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &number), TaggedValue::Number(value) if value == 3.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_start_from_their_default_or_type() {
|
||||
let unit_primary = FieldMetadata {
|
||||
default_type: Some(concrete!(())),
|
||||
..number_import()
|
||||
};
|
||||
let with_default = FieldMetadata {
|
||||
value_source: RegistryValueSource::Default("2.5"),
|
||||
..number_import()
|
||||
};
|
||||
let graph = GraphMetadata {
|
||||
imports: vec![unit_primary, with_default],
|
||||
..one_node_graph("Test Defaults", math_nodes::as_number::IDENTIFIER.into(), from_import())
|
||||
};
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
|
||||
|
||||
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
|
||||
assert!(!inputs[0].is_exposed());
|
||||
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
|
||||
assert!(inputs[1].is_exposed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_nodes_widget_settings_come_from_its_import() {
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
|
||||
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
|
||||
|
||||
let location = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
let field = document
|
||||
.network_interface
|
||||
.field_metadata(&node_id, location, &[])
|
||||
.expect("the location input should have its import's settings");
|
||||
assert_eq!(field.labels, Some(("X", "Y")));
|
||||
assert!(field.integer);
|
||||
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
|
||||
}
|
||||
}
|
||||
@@ -170,6 +170,8 @@ pub enum NodeGraphMessage {
|
||||
PointerOutsideViewport {
|
||||
shift: Key,
|
||||
},
|
||||
/// Sent when the middle button is released where it was pressed in the graph, rather than having panned it.
|
||||
MiddleClick,
|
||||
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
|
||||
WireHoverTick,
|
||||
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
|
||||
@@ -437,6 +439,7 @@ impl NodeGraphMessage {
|
||||
| Self::PointerMove { .. }
|
||||
| Self::PointerUp
|
||||
| Self::PointerOutsideViewport { .. }
|
||||
| Self::MiddleClick
|
||||
| Self::WireHoverTick
|
||||
| Self::SendGlide
|
||||
| Self::GlideTick
|
||||
|
||||
@@ -1752,6 +1752,20 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.auto_panning.stop(&messages, responses);
|
||||
}
|
||||
}
|
||||
// Middle-clicking a node toggles its visibility
|
||||
NodeGraphMessage::MiddleClick => {
|
||||
if !graph_view_overlay_open || network_interface.is_read_only(breadcrumb_network_path) {
|
||||
return;
|
||||
}
|
||||
let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, breadcrumb_network_path) else {
|
||||
return;
|
||||
};
|
||||
|
||||
responses.add(NodeGraphMessage::ToggleVisibility {
|
||||
node_id,
|
||||
network_path: breadcrumb_network_path.to_vec(),
|
||||
});
|
||||
}
|
||||
NodeGraphMessage::WireHoverTick => {
|
||||
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
|
||||
}
|
||||
|
||||
@@ -37,11 +37,11 @@ use graphene_std::vector::misc::{
|
||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
build_transform_with_y_preservation,
|
||||
FillChoice, Gradient, 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, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
@@ -240,7 +240,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
||||
}
|
||||
|
||||
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
|
||||
#[derive(Clone, Copy)]
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(crate) struct ParameterOptions {
|
||||
pub soft_min: Option<f64>,
|
||||
pub soft_max: Option<f64>,
|
||||
@@ -252,34 +252,10 @@ pub(crate) struct ParameterOptions {
|
||||
pub unit: Option<&'static str>,
|
||||
pub display_decimal_places: Option<u32>,
|
||||
pub step: Option<f64>,
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
pub integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for ParameterOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
soft_min: None,
|
||||
soft_max: None,
|
||||
hard_min: None,
|
||||
hard_max: None,
|
||||
slider: false,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
unit: None,
|
||||
display_decimal_places: None,
|
||||
step: None,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ParameterOptions {
|
||||
/// The options a proto node's field or a graph's import gives its widget.
|
||||
pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self {
|
||||
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,
|
||||
@@ -291,9 +267,6 @@ impl ParameterOptions {
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
labels: field.labels,
|
||||
integer: field.integer,
|
||||
blank_assist: field.blank_assist,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -349,12 +322,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
unit,
|
||||
display_decimal_places,
|
||||
step,
|
||||
labels,
|
||||
integer,
|
||||
blank_assist,
|
||||
} = options;
|
||||
|
||||
let mut number_input = NumberInput::default().is_integer(integer);
|
||||
let mut number_input = NumberInput::default();
|
||||
if slider {
|
||||
number_input = number_input.mode_range();
|
||||
}
|
||||
@@ -397,7 +367,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
}
|
||||
};
|
||||
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
|
||||
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
|
||||
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
|
||||
@@ -441,10 +411,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
true => text_area_widget(default_info).into(),
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => {
|
||||
let (x_label, y_label) = labels.unwrap_or(("X", "Y"));
|
||||
vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false)
|
||||
}
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
@@ -467,6 +434,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
// AUTO-GENERATED ENUM TYPES
|
||||
// =========================
|
||||
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientModel>(x) => enum_choice::<GradientModel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
|
||||
@@ -514,6 +482,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BlendIfChannel>(x) => enum_choice::<BlendIfChannel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -954,7 +923,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
||||
}
|
||||
}
|
||||
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, max: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
@@ -969,7 +938,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
||||
@@ -980,7 +949,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
||||
@@ -995,7 +964,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
||||
@@ -1006,7 +975,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
||||
@@ -1386,7 +1355,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
||||
return LayoutGroup::row(vec![]);
|
||||
};
|
||||
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
|
||||
let entries = BlendMode::list_svg_subset()
|
||||
let entries = BlendMode::list()
|
||||
.iter()
|
||||
.map(|category| {
|
||||
category
|
||||
@@ -1403,9 +1372,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
||||
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(entries)
|
||||
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
|
||||
.widget_instance(),
|
||||
DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(),
|
||||
]);
|
||||
}
|
||||
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
|
||||
@@ -1966,6 +1933,8 @@ pub(crate) fn levels_inspector(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
enum MarkerScale {
|
||||
/// A 0..100 percentage, placed linearly.
|
||||
Percent,
|
||||
/// A 0..100 percentage of a channel's 256 levels, placed linearly and shown to a tenth, which tells neighboring levels apart.
|
||||
LevelPercent,
|
||||
/// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center.
|
||||
Gamma,
|
||||
/// A hue of 0..360 degrees, placed linearly on a track that wraps around.
|
||||
@@ -1975,7 +1944,7 @@ enum MarkerScale {
|
||||
impl MarkerScale {
|
||||
fn position(self, value: f64) -> f64 {
|
||||
match self {
|
||||
Self::Percent => value / 100.,
|
||||
Self::Percent | Self::LevelPercent => value / 100.,
|
||||
Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(),
|
||||
Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(),
|
||||
Self::Degrees => {
|
||||
@@ -1989,7 +1958,7 @@ impl MarkerScale {
|
||||
|
||||
fn value(self, position: f64) -> f64 {
|
||||
match self {
|
||||
Self::Percent => (position * 100.).clamp(0., 100.),
|
||||
Self::Percent | Self::LevelPercent => (position * 100.).clamp(0., 100.),
|
||||
Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99),
|
||||
Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.),
|
||||
Self::Degrees => (position * 360.).clamp(0., 360.),
|
||||
@@ -1999,6 +1968,7 @@ impl MarkerScale {
|
||||
fn number_input(self) -> NumberInput {
|
||||
match self {
|
||||
Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0),
|
||||
Self::LevelPercent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(1),
|
||||
Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2),
|
||||
Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0),
|
||||
}
|
||||
@@ -2023,6 +1993,8 @@ struct SliderSectionParam {
|
||||
dash_to_next: bool,
|
||||
/// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move.
|
||||
between_neighbors: bool,
|
||||
/// How the marker and the next parameter's marker may pass each other (see [`overlap_bounds`]).
|
||||
overlap_next: MarkerOverlap,
|
||||
}
|
||||
|
||||
impl SliderSectionParam {
|
||||
@@ -2035,6 +2007,7 @@ impl SliderSectionParam {
|
||||
pair_with_next: false,
|
||||
dash_to_next: false,
|
||||
between_neighbors: false,
|
||||
overlap_next: MarkerOverlap::Never,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2052,11 +2025,52 @@ impl SliderSectionParam {
|
||||
self.dash_to_next = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
||||
self.overlap_next = overlap;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The span the marker at `index` may move within where markers may overlap their next (see [`MarkerOverlap`]).
|
||||
fn overlap_bounds(positions: &[f64], overlaps_next: &[MarkerOverlap], index: usize) -> (f64, f64) {
|
||||
let overlap = |i: Option<usize>| i.and_then(|i| overlaps_next.get(i)).copied().unwrap_or_default();
|
||||
let position = |i: Option<usize>| i.and_then(|i| positions.get(i)).copied();
|
||||
let (previous, before_previous, next, after_next) = (index.checked_sub(1), index.checked_sub(2), Some(index + 1), Some(index + 2));
|
||||
let mut lower = 0_f64;
|
||||
let mut upper = 1_f64;
|
||||
|
||||
// A neighbor bounds the marker unless they overlap
|
||||
if overlap(previous) == MarkerOverlap::Never
|
||||
&& let Some(previous) = position(previous)
|
||||
{
|
||||
lower = lower.max(previous);
|
||||
}
|
||||
if overlap(Some(index)) == MarkerOverlap::Never
|
||||
&& let Some(next) = position(next)
|
||||
{
|
||||
upper = upper.min(next);
|
||||
}
|
||||
|
||||
// Past a neighbor overlapping only its next, the marker beyond bounds it too, unless either overlaps freely
|
||||
let bounds_beyond = |near: MarkerOverlap, far: MarkerOverlap| (near == MarkerOverlap::NextOnly || far == MarkerOverlap::NextOnly) && near != MarkerOverlap::Freely && far != MarkerOverlap::Freely;
|
||||
if bounds_beyond(overlap(previous), overlap(before_previous))
|
||||
&& let Some(before_previous) = position(before_previous)
|
||||
{
|
||||
lower = lower.max(before_previous);
|
||||
}
|
||||
if bounds_beyond(overlap(Some(index)), overlap(next))
|
||||
&& let Some(after_next) = position(after_next)
|
||||
{
|
||||
upper = upper.min(after_next);
|
||||
}
|
||||
|
||||
(lower, upper)
|
||||
}
|
||||
|
||||
/// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row
|
||||
/// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display.
|
||||
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do.
|
||||
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do, except where they may overlap.
|
||||
fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) {
|
||||
// Snapshot exposure and values before the mutable-borrow loop
|
||||
let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) {
|
||||
@@ -2084,6 +2098,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let mut marker_scales = Vec::new();
|
||||
let mut marker_positions = Vec::new();
|
||||
let mut marker_between = Vec::new();
|
||||
let mut marker_overlaps = Vec::new();
|
||||
let mut marker_colors_and_links = Vec::new();
|
||||
for (i, param) in params.iter().enumerate() {
|
||||
let (exposed, value) = exposure_and_value[i];
|
||||
@@ -2096,13 +2111,21 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
marker_default_positions.push(param.scale.position(param.default_value));
|
||||
marker_scales.push(param.scale);
|
||||
marker_between.push(param.between_neighbors);
|
||||
marker_overlaps.push(if next_has_marker { param.overlap_next } else { MarkerOverlap::Never });
|
||||
marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker));
|
||||
}
|
||||
|
||||
// Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence.
|
||||
// A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span.
|
||||
let cyclic = params.iter().any(|param| param.scale.cyclic());
|
||||
if !cyclic {
|
||||
let overlapping = marker_overlaps.iter().any(|&overlap| overlap != MarkerOverlap::Never);
|
||||
if overlapping {
|
||||
// Markers allowed to overlap are held only past those they can't pass, each bounded by markers earlier in the list
|
||||
for i in 0..marker_positions.len() {
|
||||
let (lower, _) = overlap_bounds(&marker_positions, &marker_overlaps, i);
|
||||
marker_positions[i] = marker_positions[i].max(lower);
|
||||
}
|
||||
} else if !cyclic {
|
||||
let mut floor = 0.;
|
||||
for (position, &between) in marker_positions.iter_mut().zip(&marker_between) {
|
||||
if between {
|
||||
@@ -2123,8 +2146,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let slider_markers: Vec<SliderMarker> = marker_positions
|
||||
.iter()
|
||||
.zip(&marker_colors_and_links)
|
||||
.zip(&marker_between)
|
||||
.map(|((&position, &(handle_color, paired, dashed)), &between)| {
|
||||
.zip(marker_between.iter().zip(&marker_overlaps))
|
||||
.map(|((&position, &(handle_color, paired, dashed)), (&between, &overlap))| {
|
||||
let mut marker = SliderMarker::new(position, 0.5, handle_color);
|
||||
if paired {
|
||||
marker = marker.pair_with_next();
|
||||
@@ -2135,6 +2158,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
if between {
|
||||
marker = marker.between_neighbors();
|
||||
}
|
||||
marker = marker.overlap_next(overlap);
|
||||
marker
|
||||
})
|
||||
.collect();
|
||||
@@ -2156,6 +2180,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let marker_scales = marker_scales.clone();
|
||||
let marker_positions = marker_positions.clone();
|
||||
let marker_between = marker_between.clone();
|
||||
let marker_overlaps = marker_overlaps.clone();
|
||||
move |update: &SliderInputUpdate| {
|
||||
let i = match update {
|
||||
SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize,
|
||||
@@ -2170,8 +2195,13 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
// The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the
|
||||
// nearest markers that bound it, which a marker placed between its neighbors never does
|
||||
let bounding = |j: usize| between || !marker_between[j];
|
||||
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
||||
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
||||
let (left, right) = if overlapping {
|
||||
overlap_bounds(&marker_positions, &marker_overlaps, i)
|
||||
} else {
|
||||
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
||||
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
||||
(left, right)
|
||||
};
|
||||
|
||||
let scale_position = match update {
|
||||
SliderInputUpdate::MoveMarker { position, .. } if between => {
|
||||
@@ -2596,6 +2626,105 @@ pub(crate) fn threshold_inspector(node_id: NodeId, context: &mut NodeInspectorCo
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn blend_if_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::blending_nodes::blend_if::blend_if::*;
|
||||
|
||||
let channel = enum_choice::<BlendIfChannel>()
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, ChannelInput, true, context))
|
||||
.inspector_row();
|
||||
|
||||
let channel_value = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ChannelInput).cloned()) {
|
||||
Some(TaggedValue::BlendIfChannel(channel)) => channel,
|
||||
_ => BlendIfChannel::Gray,
|
||||
};
|
||||
let ([content, underlying], track_color): ([[ParameterRef; 4]; 2], Color) = match channel_value {
|
||||
BlendIfChannel::Gray => (
|
||||
[
|
||||
[
|
||||
ContentFalloffStartInput.into(),
|
||||
ContentRangeStartInput.into(),
|
||||
ContentRangeEndInput.into(),
|
||||
ContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
UnderlyingFalloffStartInput.into(),
|
||||
UnderlyingRangeStartInput.into(),
|
||||
UnderlyingRangeEndInput.into(),
|
||||
UnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::WHITE,
|
||||
),
|
||||
BlendIfChannel::Red => (
|
||||
[
|
||||
[
|
||||
RedContentFalloffStartInput.into(),
|
||||
RedContentRangeStartInput.into(),
|
||||
RedContentRangeEndInput.into(),
|
||||
RedContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
RedUnderlyingFalloffStartInput.into(),
|
||||
RedUnderlyingRangeStartInput.into(),
|
||||
RedUnderlyingRangeEndInput.into(),
|
||||
RedUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::RED,
|
||||
),
|
||||
BlendIfChannel::Green => (
|
||||
[
|
||||
[
|
||||
GreenContentFalloffStartInput.into(),
|
||||
GreenContentRangeStartInput.into(),
|
||||
GreenContentRangeEndInput.into(),
|
||||
GreenContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
GreenUnderlyingFalloffStartInput.into(),
|
||||
GreenUnderlyingRangeStartInput.into(),
|
||||
GreenUnderlyingRangeEndInput.into(),
|
||||
GreenUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::GREEN,
|
||||
),
|
||||
BlendIfChannel::Blue => (
|
||||
[
|
||||
[
|
||||
BlueContentFalloffStartInput.into(),
|
||||
BlueContentRangeStartInput.into(),
|
||||
BlueContentRangeEndInput.into(),
|
||||
BlueContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
BlueUnderlyingFalloffStartInput.into(),
|
||||
BlueUnderlyingRangeStartInput.into(),
|
||||
BlueUnderlyingRangeEndInput.into(),
|
||||
BlueUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::BLUE,
|
||||
),
|
||||
};
|
||||
|
||||
// Each side's range runs along its channel's levels as a black split handle joined to a white one, with the fully shown range dashed between them
|
||||
let track = Gradient::from(vec![Color::BLACK, track_color]);
|
||||
let mut layout = vec![channel];
|
||||
for [falloff_start, range_start, range_end, falloff_end] in [content, underlying] {
|
||||
let params = [
|
||||
SliderSectionParam::new(falloff_start, Color::BLACK, 0., MarkerScale::LevelPercent).pair_with_next(),
|
||||
SliderSectionParam::new(range_start, Color::BLACK, 0., MarkerScale::LevelPercent)
|
||||
.dash_to_next()
|
||||
.overlap_next(MarkerOverlap::Freely),
|
||||
SliderSectionParam::new(range_end, Color::WHITE, 100., MarkerScale::LevelPercent).pair_with_next(),
|
||||
SliderSectionParam::new(falloff_end, Color::WHITE, 100., MarkerScale::LevelPercent),
|
||||
];
|
||||
build_shared_slider_section(node_id, context, &track, ¶ms, &mut layout);
|
||||
}
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::raster::vibrance::*;
|
||||
|
||||
@@ -2848,10 +2977,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
||||
NumberInput::default().label("H").min(0.).unit(" px"),
|
||||
));
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false);
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false);
|
||||
widgets.extend([spacing, angles]);
|
||||
} else {
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false);
|
||||
widgets.push(spacing);
|
||||
}
|
||||
}
|
||||
@@ -3175,6 +3304,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::*;
|
||||
|
||||
@@ -3314,20 +3517,29 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
}
|
||||
|
||||
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
|
||||
let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path);
|
||||
let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default();
|
||||
|
||||
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
|
||||
log::error!("Could not get implementation for node {node_id}");
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut options = ParameterOptions::default();
|
||||
let input_type = match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||
let proto_node_identifier = proto_node_identifier.clone();
|
||||
|
||||
if let Some(default) = field.and_then(|field| field.default_type) {
|
||||
let mut default_type = None;
|
||||
if let Some(field) = graphene_std::registry::NODE_METADATA
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
options = ParameterOptions::from(field);
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
if let Some(default) = default_type {
|
||||
break 'early_return default;
|
||||
}
|
||||
|
||||
@@ -3343,21 +3555,12 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
let Some(input_type) = input_type else { return Vec::new() };
|
||||
input_type.clone()
|
||||
}
|
||||
_ => {
|
||||
// A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph
|
||||
let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
|
||||
Type::Item(element) => *element,
|
||||
declared_type => declared_type,
|
||||
});
|
||||
|
||||
context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.or(declared_type)
|
||||
.unwrap_or(concrete!(()))
|
||||
}
|
||||
_ => context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.unwrap_or(concrete!(())),
|
||||
};
|
||||
|
||||
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
|
||||
@@ -3721,9 +3924,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();
|
||||
@@ -3862,7 +4081,7 @@ pub(crate) fn displace_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
||||
if !matches!(mode, Some(DisplaceMode::Angle)) {
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, XDisplacementInput, true, context), ColorInput::default()));
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, YDisplacementInput, true, context), ColorInput::default()));
|
||||
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, None, false, false));
|
||||
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, false, false));
|
||||
}
|
||||
|
||||
let edge_mode = enum_choice::<GradientSpread>()
|
||||
|
||||
@@ -37,6 +37,7 @@ impl FrontendGraphDataType {
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
// A generator draws pixels like an image, at whatever resolution is needed
|
||||
"Generator" => Self::Raster,
|
||||
"Pixels" => Self::Raster,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
|
||||
@@ -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(), 8, "the legacy Fill should upgrade to the 8-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(), 8, "the eight-input Fill should come out in the modern shape, which also has eight inputs");
|
||||
let curvatures = [graphene_std::vector::fill::StartCurvatureInput::INDEX, graphene_std::vector::fill::EndCurvatureInput::INDEX].map(|index| fill_node.inputs[index].as_value().cloned());
|
||||
assert_eq!(
|
||||
curvatures,
|
||||
[0., 0.].map(|curvature| Some(TaggedValue::Number(curvature))),
|
||||
"the linear form should become its curvatures"
|
||||
);
|
||||
|
||||
let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
|
||||
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
|
||||
|
||||
@@ -59,6 +59,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::reso
|
||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
|
||||
use deserialization::deserialize_node_persistent_metadata;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::Type;
|
||||
@@ -73,7 +74,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
|
||||
use graphene_std::vector::{Vector, VectorModificationType};
|
||||
use kurbo::BezPath;
|
||||
use memo_network::MemoNetwork;
|
||||
use serde_json::Value;
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::Hash;
|
||||
use std::ops::Deref;
|
||||
|
||||
+58
-1
@@ -2613,7 +2613,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir
|
||||
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
|
||||
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
let shaken = editor
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0)
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0)
|
||||
.await;
|
||||
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
|
||||
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
|
||||
@@ -3399,6 +3399,63 @@ async fn visibility_and_lock_toggles_made_in_an_open_transaction_undo_together()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn middle_clicking_a_node_in_the_graph_toggles_its_visibility_but_middle_dragging_only_pans() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected").to_node();
|
||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
||||
|
||||
let is_visible = |editor: &EditorTestUtils| editor.active_document().network_interface.is_visible(&layer, &[]);
|
||||
let graph_pan = |editor: &EditorTestUtils| {
|
||||
editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.network_metadata(&[])
|
||||
.unwrap()
|
||||
.persistent_metadata
|
||||
.navigation_metadata
|
||||
.node_graph_ptz
|
||||
.pan
|
||||
};
|
||||
let layer_in_viewport = |editor: &EditorTestUtils| {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let [min, max] = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
|
||||
let node_graph_to_viewport = network_interface.network_metadata(&[]).unwrap().persistent_metadata.navigation_metadata.node_graph_to_viewport;
|
||||
|
||||
(0..=(max.x - min.x) as i32)
|
||||
.map(|x| node_graph_to_viewport.transform_point2(DVec2::new(min.x + x as f64, (min.y + max.y) / 2.)))
|
||||
.find(|&point| network_interface.node_from_click(point, &[]) == Some(layer))
|
||||
.expect("the layer should be pressable")
|
||||
};
|
||||
let pointer_state = |position: DVec2, mouse_keys: MouseKeys| EditorPointerState {
|
||||
editor_position: position,
|
||||
mouse_keys,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Pressed and released with a wobble too small to count as a drag
|
||||
let start = layer_in_viewport(&editor);
|
||||
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
|
||||
assert!(is_visible(&editor), "pressing the middle button shouldn't toggle the layer yet");
|
||||
editor.mouseup(pointer_state(start + DVec2::new(2., 0.), MouseKeys::empty()), ModifierKeys::empty()).await;
|
||||
assert!(!is_visible(&editor), "a middle click on the layer should hide it");
|
||||
|
||||
// Dragged away and back before the release
|
||||
let start = layer_in_viewport(&editor);
|
||||
let pan_before = graph_pan(&editor);
|
||||
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
|
||||
editor.move_mouse(start.x + 40., start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
|
||||
assert_ne!(graph_pan(&editor), pan_before, "a middle drag should pan the graph");
|
||||
editor.move_mouse(start.x, start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
|
||||
editor.mouseup(pointer_state(start, MouseKeys::empty()), ModifierKeys::empty()).await;
|
||||
assert!(!is_visible(&editor), "a middle drag shouldn't toggle the layer, even if released where it was pressed");
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert!(is_visible(&editor), "one undo should revert the middle click");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
use super::*;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
|
||||
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
|
||||
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
|
||||
@@ -826,27 +829,17 @@ impl NodeNetworkInterface {
|
||||
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
|
||||
}
|
||||
|
||||
/// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
||||
/// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph.
|
||||
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
|
||||
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
|
||||
}
|
||||
|
||||
/// The metadata the node macro records for a proto node's parameter, or the `#[graph]` macro for a graph node's import.
|
||||
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
|
||||
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
|
||||
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
|
||||
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
|
||||
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
|
||||
}
|
||||
|
||||
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
|
||||
return None;
|
||||
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
|
||||
return false;
|
||||
};
|
||||
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
|
||||
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
|
||||
|
||||
let graphs = graphene_std::registry::GRAPH_METADATA.lock().ok()?;
|
||||
let field = graphs.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
|
||||
(field.name == input_name).then(|| field.clone())
|
||||
node_metadata
|
||||
.get(proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(index))
|
||||
.is_some_and(|field| field.internal)
|
||||
}
|
||||
|
||||
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
|
||||
@@ -1086,7 +1079,7 @@ impl NodeNetworkInterface {
|
||||
/// Whether the artboard layer clips the content inside it to its bounds.
|
||||
fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool {
|
||||
self.document_node(&artboard.to_node(), &[])
|
||||
.and_then(|artboard| artboard.inputs.get(graphene_std::subgraphs::artboard::ClipInput::INDEX))
|
||||
.and_then(|artboard| artboard.inputs.get(ARTBOARD_CLIP_INPUT_INDEX))
|
||||
.is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true)))
|
||||
}
|
||||
|
||||
|
||||
@@ -773,11 +773,51 @@ impl PartialEq for DocumentNodeMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NumberInputSettings {
|
||||
pub unit: Option<String>,
|
||||
pub min: Option<f64>,
|
||||
pub max: Option<f64>,
|
||||
pub step: Option<f64>,
|
||||
pub mode: NumberInputMode,
|
||||
pub range_min: Option<f64>,
|
||||
pub range_max: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for NumberInputSettings {
|
||||
fn default() -> Self {
|
||||
NumberInputSettings {
|
||||
unit: None,
|
||||
min: None,
|
||||
max: None,
|
||||
step: None,
|
||||
mode: NumberInputMode::default(),
|
||||
range_min: None,
|
||||
range_max: None,
|
||||
is_integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Vec2InputSettings {
|
||||
pub x: String,
|
||||
pub y: String,
|
||||
pub unit: String,
|
||||
pub min: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub enum WidgetOverride {
|
||||
None,
|
||||
Hidden,
|
||||
String(String),
|
||||
Number(NumberInputSettings),
|
||||
Vec2(Vec2InputSettings),
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
@@ -814,6 +854,40 @@ impl InputPersistentMetadata {
|
||||
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
|
||||
self.widget_override = Some("string".to_string());
|
||||
}
|
||||
WidgetOverride::Number(mut number_inspector) => {
|
||||
if let Some(unit) = number_inspector.unit.take() {
|
||||
self.input_data.insert("unit".to_string(), json!(unit));
|
||||
}
|
||||
if let Some(min) = number_inspector.min.take() {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
if let Some(max) = number_inspector.max.take() {
|
||||
self.input_data.insert("max".to_string(), json!(max));
|
||||
}
|
||||
if let Some(step) = number_inspector.step.take() {
|
||||
self.input_data.insert("step".to_string(), json!(step));
|
||||
}
|
||||
if let Some(range_min) = number_inspector.range_min.take() {
|
||||
self.input_data.insert("range_min".to_string(), json!(range_min));
|
||||
}
|
||||
if let Some(range_max) = number_inspector.range_max.take() {
|
||||
self.input_data.insert("range_max".to_string(), json!(range_max));
|
||||
}
|
||||
self.input_data.insert("mode".to_string(), json!(number_inspector.mode));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(number_inspector.is_integer));
|
||||
self.input_data.insert("blank_assist".to_string(), Value::Bool(number_inspector.blank_assist));
|
||||
self.widget_override = Some("number".to_string());
|
||||
}
|
||||
WidgetOverride::Vec2(vec2_inspector) => {
|
||||
self.input_data.insert("x".to_string(), json!(vec2_inspector.x));
|
||||
self.input_data.insert("y".to_string(), json!(vec2_inspector.y));
|
||||
self.input_data.insert("unit".to_string(), json!(vec2_inspector.unit));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_inspector.is_integer));
|
||||
if let Some(min) = vec2_inspector.min {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
self.widget_override = Some("vec2".to_string());
|
||||
}
|
||||
WidgetOverride::Custom(lambda_name) => {
|
||||
self.widget_override = Some(lambda_name);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -121,6 +121,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_std::raster::SampleImageNode",
|
||||
"graphene_std::raster::SampleNode",
|
||||
"raster_nodes::std_nodes::SampleImageNode",
|
||||
// The deleted Extend Image to Bounds passes its image through, since the transparent pixels it padded with drew nothing
|
||||
"graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
||||
"graphene_std::raster::ExtendImageToBoundsNode",
|
||||
"raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -181,10 +185,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 +301,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"],
|
||||
@@ -472,9 +468,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
|
||||
// Old references (including these older aliases) are remapped here to `vec2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::vec2_value::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_math_nodes::Vec2ValueNode",
|
||||
"graphene_core::ops::ConstructVector2",
|
||||
@@ -484,7 +480,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
|
||||
aliases: &["math_nodes::CombineVec2Node"],
|
||||
},
|
||||
// ================================
|
||||
@@ -553,8 +549,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::channels::into_channels::IDENTIFIER,
|
||||
aliases: &["raster_nodes::adjustments::ImageToChannelsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::channels::from_channels::IDENTIFIER,
|
||||
aliases: &[
|
||||
"raster_nodes::std_nodes::ChannelsToImageNode",
|
||||
"raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_std::raster::CombineChannelsNode",
|
||||
@@ -572,10 +573,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ExposureNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode", "graphene_std::raster::ExtendImageToBoundsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||
@@ -1572,13 +1569,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `image_to_channels` proto nodes.
|
||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `into_channels` proto nodes.
|
||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||
let split_wrapper_replacements = [
|
||||
("Split Vec2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::channels::into_channels::IDENTIFIER),
|
||||
];
|
||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
@@ -1624,7 +1621,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Image to Channels" nodes.
|
||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Into Channels" nodes.
|
||||
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
||||
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
||||
const EXTRACT_CHANNEL: [&str; 4] = [
|
||||
@@ -1641,9 +1638,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
|
||||
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
|
||||
if EXTRACT_XY.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||
Some((*node_id, path, graphene_std::raster_nodes::channels::into_channels::IDENTIFIER, "Extract Channel"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -1689,6 +1686,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 +2537,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 +2692,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 +2719,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();
|
||||
@@ -2931,8 +3019,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
|
||||
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER);
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER);
|
||||
let mut node_template = resolve_document_node_type(&numbers_to_vec2_reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
@@ -3164,9 +3252,17 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
}
|
||||
|
||||
// Sample Image nodes, now passthroughs, drop their old title
|
||||
// Sample Image and Extend Image to Bounds nodes, now passthroughs, drop their old titles and any inputs past the first, like Extend Image to Bounds's bounds
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) {
|
||||
reset_default_display_name(document, node_id, network_path, "Sample Image");
|
||||
reset_default_display_name(document, node_id, network_path, "Extend Image to Bounds");
|
||||
|
||||
if inputs_count > 1 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize became As String, whose input converts a wired value to text, while a stored value keeps the JSON text Serialize made of it
|
||||
@@ -4116,6 +4212,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 +4988,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() {
|
||||
@@ -5230,11 +5374,7 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let (&count_conversion_id, count_conversion) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. })))
|
||||
.expect("Blend should have a count conversion node");
|
||||
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node");
|
||||
count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
|
||||
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
@@ -5251,7 +5391,7 @@ mod tests {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Blend", count_conversion_id)].implementation,
|
||||
inner.nodes[&shipped_node_id("Blend", NodeId(3))].implementation,
|
||||
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
|
||||
);
|
||||
}
|
||||
@@ -5268,11 +5408,7 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let (&edited_subtract_id, edited_subtract) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER))
|
||||
.expect("Blend should have an open-path denominator node");
|
||||
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
|
||||
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
@@ -5282,7 +5418,7 @@ mod tests {
|
||||
let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
let edited_subtract = derived_node_id(*definition, edited_subtract_id);
|
||||
let edited_subtract = derived_node_id(*definition, NodeId(5));
|
||||
assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
|
||||
}
|
||||
|
||||
@@ -5364,15 +5500,8 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Regex Find should be a network node")
|
||||
};
|
||||
let inner_node_id = |identifier: graphene_std::ProtoNodeIdentifier| {
|
||||
let implementation = NodeTemplateImplementation::ProtoNode(identifier);
|
||||
network_template.nodes.iter().find(|(_, node)| node.implementation == implementation).map(|(&id, _)| id)
|
||||
};
|
||||
let find_id = inner_node_id(graphene_std::text_nodes::regex::regex_find::IDENTIFIER).expect("Regex Find should have a find node");
|
||||
let item_at_index_id = inner_node_id(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Regex Find should have an item-at-index node");
|
||||
|
||||
network_template.nodes.get_mut(&find_id).expect("the find node should exist").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&item_at_index_id).expect("the item-at-index node should exist").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
migrate(&mut document);
|
||||
@@ -5386,9 +5515,9 @@ mod tests {
|
||||
let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else {
|
||||
panic!("Regex Find should stay a network node")
|
||||
};
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", find_id)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", NodeId(0))].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Regex Find", item_at_index_id)].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
inner.nodes[&shipped_node_id("Regex Find", NodeId(1))].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::Integer(0))
|
||||
);
|
||||
}
|
||||
@@ -5455,6 +5584,204 @@ mod tests {
|
||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_form_nodes_become_gradient_curvature_presets() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
|
||||
// Curvatures stay shown in the graph where an exposed form was
|
||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
||||
for (identifier, form, curvatures, exposed) in [
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], false),
|
||||
("math_nodes::GradientTypeNode", GradientForm::Linear, [0., 0.], false),
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], true),
|
||||
] {
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let placeholder = || NodeInput::value(TaggedValue::None, false);
|
||||
document.network_interface.insert_node(
|
||||
source_id,
|
||||
NodeTemplate {
|
||||
inputs: vec![placeholder()],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.insert_node(
|
||||
form_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![placeholder(); 2],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), exposed), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&form_id];
|
||||
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
|
||||
|
||||
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(
|
||||
[curvature(1), curvature(2)],
|
||||
curvatures.map(|curvature| Some(TaggedValue::Number(curvature))),
|
||||
"{form:?} should become its curvature presets"
|
||||
);
|
||||
assert_eq!(
|
||||
[1, 2].map(|index| node.inputs[index].is_exposed()),
|
||||
[exposed; 2],
|
||||
"{form:?} exposed {exposed} should leave its curvatures so"
|
||||
);
|
||||
assert_eq!(node.inputs.len(), 3, "{form:?} should take the curvature node's gradient and two curvatures");
|
||||
}
|
||||
}
|
||||
|
||||
// An eight-input Fill from when the spread was an input of its own, here wired, opens with its form's curvatures and keeps its placement
|
||||
#[test]
|
||||
fn eight_input_fills_with_a_wired_spread_take_their_form_as_curvatures() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use glam::DAffine2;
|
||||
|
||||
let (source_id, fill_id) = (NodeId(1), NodeId(2));
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
|
||||
let ramp = || NodeInput::value(TaggedValue::GradientRamp(GradientRamp::default()), false);
|
||||
let old_inputs = vec![
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
ramp(),
|
||||
NodeInput::value(TaggedValue::Color(Color::BLACK), false),
|
||||
ramp(),
|
||||
NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false),
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
NodeInput::value(TaggedValue::DAffine2(placement), false),
|
||||
];
|
||||
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let source = NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(source_id, source, &[]);
|
||||
let fill = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::vector::fill::IDENTIFIER),
|
||||
inputs: old_inputs,
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(fill_id, fill, &[]);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(fill_id, 5), NodeInput::node(source_id, 0), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&fill_id];
|
||||
let values: Vec<_> = node.inputs[4..].iter().map(|input| input.as_value().cloned()).collect();
|
||||
let expected = [TaggedValue::Number(-1.), TaggedValue::Number(0.5), TaggedValue::Bool(true), TaggedValue::DAffine2(placement)].map(Some);
|
||||
assert_eq!(values, expected, "the form should become its curvatures before the placement");
|
||||
}
|
||||
|
||||
// A Fill that held the radial form in its input before the transform ones opens with that form's curvatures, painting as a Fill given the form now does
|
||||
#[tokio::test]
|
||||
async fn fills_of_the_radial_form_paint_the_same_once_migrated() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graphene_std::graphic::extend;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::vector::fill;
|
||||
use graphene_std::vector::style::Gradient;
|
||||
use graphene_std::vector_types::gradient_standard::GradientShape;
|
||||
use graphene_std::{Appearance, Cover, Graphic};
|
||||
|
||||
// The SVG of the document's one layer, its IDs numbered by their order of appearance, and the shape the CPU samples its fill's gradient as
|
||||
async fn painted(editor: &mut EditorTestUtils) -> (String, Option<GradientShape>) {
|
||||
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
||||
let layer = instrumented
|
||||
.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime)
|
||||
.next()
|
||||
.expect("the layer is extended onto the root");
|
||||
|
||||
let mut render = SvgRender::new();
|
||||
layer.element().render_svg(&mut render, &RenderParams::default());
|
||||
let mut markup = format!("{}{}", render.svg_defs, render.svg.to_svg_string());
|
||||
let mut index = 0;
|
||||
while let Some(found) = markup.find(r#"id=""#) {
|
||||
let start = found + r#"id=""#.len();
|
||||
let id = markup[start..start + markup[start..].find('"').unwrap_or_default()].to_string();
|
||||
markup = markup.replace(&format!(r#"id="{id}""#), &format!(r#"ID="{index}""#)).replace(&format!("#{id}"), &format!("#{index}"));
|
||||
index += 1;
|
||||
}
|
||||
|
||||
let shape = match layer.element() {
|
||||
Graphic::VectorList(vectors) => match vectors
|
||||
.attribute::<Appearance>(graphene_std::list::ATTR_APPEARANCE, 0)
|
||||
.and_then(|appearance| appearance.first_paint_of(Cover::Fill))
|
||||
{
|
||||
Some(Graphic::Gradient(gradient)) => Some(GradientShape::new(
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_START_CURVATURE),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_END_CURVATURE),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_MODEL),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_TRANSFORM),
|
||||
)),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
(markup.replace(r#"ID=""#, r#"id=""#), shape)
|
||||
}
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(10., 20., 110., 70.).await;
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("the rectangle is a layer");
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: Gradient::from(vec![Color::BLACK, Color::WHITE]),
|
||||
gradient_form: Some(GradientForm::Radial),
|
||||
gradient_settings: Default::default(),
|
||||
transform: Some(placement),
|
||||
})
|
||||
.await;
|
||||
|
||||
// The radial form's curvatures draw the unit circle it always drew, and the CPU samples it as the form
|
||||
let (curved_svg, curved_shape) = painted(&mut editor).await;
|
||||
assert!(curved_svg.contains(r#"gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1""#), "{curved_svg}");
|
||||
assert_eq!(curved_shape, Some(GradientShape::Radial));
|
||||
|
||||
// The same document saved with the form, under the name it had before 'Gradient Type' became 'Gradient Form', in place of the curvatures
|
||||
let document = editor.active_document_mut();
|
||||
let fill_id = NodeGraphLayer::new(layer, &document.network_interface)
|
||||
.upstream_node_id_from_protonode(fill::IDENTIFIER)
|
||||
.expect("the layer has a Fill");
|
||||
let inputs = document.network_interface.document_network().nodes[&fill_id].inputs.clone();
|
||||
let curvatures = [4, 5].map(|index| inputs[index].as_value().cloned());
|
||||
assert_eq!(curvatures, GradientForm::Radial.curvatures().map(|curvature| Some(TaggedValue::Number(curvature))));
|
||||
|
||||
let form = NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false);
|
||||
let mut old_inputs = NodeTemplate {
|
||||
inputs: [&inputs[..4], &[form], &inputs[6..]].concat(),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_inputs(&fill_id, &[], &mut old_inputs);
|
||||
let serialized = document.serialize_document();
|
||||
assert_eq!(serialized.matches(r#"{"GradientForm":"Radial"}"#).count(), 1, "the form should be saved once");
|
||||
let serialized = serialized.replace(r#"{"GradientForm":"Radial"}"#, r#"{"GradientType":"Radial"}"#);
|
||||
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
|
||||
document_name: Some("Migrated".into()),
|
||||
document_path: None,
|
||||
document_serialized_content: serialized,
|
||||
})
|
||||
.await;
|
||||
let (migrated_svg, migrated_shape) = painted(&mut editor).await;
|
||||
assert_eq!(migrated_svg, curved_svg);
|
||||
assert_eq!(migrated_shape, curved_shape);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
@@ -6004,6 +6331,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_image_to_bounds_opens_as_a_passthrough_of_its_image() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let (image, extend) = (NodeId(1), NodeId(2));
|
||||
let image_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
||||
.expect("the Image definition should exist")
|
||||
.default_node_template();
|
||||
let extend_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("raster_nodes::std_nodes::ExtendImageToBoundsNode")),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::DAffine2(DAffine2::IDENTITY), false)],
|
||||
display_name: "Extend Image to Bounds".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node(image, image_template, &[]);
|
||||
document.network_interface.insert_node(extend, extend_template, &[]);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(extend, 0), NodeInput::node(image, 0), &[]);
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let node = opened.network_interface.document_node(&extend, &[]).expect("the node should still exist");
|
||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||
assert!(matches!(node.inputs[..], [NodeInput::Node { node_id, output_index: 0, .. }] if node_id == image), "{:?}", node.inputs);
|
||||
assert_ne!(opened.network_interface.display_name(&extend, &[]), "Extend Image to Bounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
|
||||
@@ -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,9 +841,23 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
|
||||
}
|
||||
}
|
||||
|
||||
/// A Fill node's curvatures, unless the graph feeds either or exposes it, read like [`gradient_curvature_values`] reads a 'Gradient Curvature' node's.
|
||||
pub fn fill_node_curvatures(fill_node: &DocumentNode) -> Option<[f64; 2]> {
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
|
||||
&TaggedValue::Number(value) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
Some([value(fill_node.input(StartCurvatureInput))?, value(fill_node.input(EndCurvatureInput))?])
|
||||
}
|
||||
|
||||
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
|
||||
pub struct FillNodeGradient {
|
||||
pub stops: Gradient,
|
||||
/// Its curvatures, unless the graph feeds them, as [`fill_node_curvatures`] reads them.
|
||||
pub curvatures: Option<[f64; 2]>,
|
||||
/// The form its curvatures make, which is linear for any that make neither.
|
||||
pub gradient_form: GradientForm,
|
||||
pub settings: GradientSettings,
|
||||
pub transform: DAffine2,
|
||||
@@ -849,10 +874,8 @@ 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 has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
|
||||
let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
|
||||
let transform = match (has_transform, transform_input) {
|
||||
@@ -863,6 +886,7 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
|
||||
Some(FillNodeGradient {
|
||||
stops,
|
||||
curvatures,
|
||||
gradient_form,
|
||||
settings,
|
||||
transform,
|
||||
@@ -1005,10 +1029,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 +1039,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),
|
||||
});
|
||||
|
||||
@@ -175,6 +175,8 @@ pub struct SnapSession {
|
||||
gesture: Option<Gesture>,
|
||||
/// The targets woken by resting the pointer on them, from the one woken longest ago to the latest.
|
||||
awake: Vec<Awake>,
|
||||
/// Those of them woken during the gesture under way, which go back to sleep when it ends.
|
||||
woken_in_gesture: Vec<Awake>,
|
||||
/// The layers each woken point of its own was found on, by its ID, which it goes back to sleep with.
|
||||
position_sources: HashMap<u64, Vec<LayerId>>,
|
||||
rest: Option<Rest>,
|
||||
@@ -495,13 +497,17 @@ impl SnapSession {
|
||||
landed
|
||||
}
|
||||
|
||||
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to.
|
||||
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to. What the gesture woke goes back to sleep with it.
|
||||
pub fn end_gesture(&mut self) {
|
||||
self.gesture = None;
|
||||
self.constructions = None;
|
||||
self.rest = None;
|
||||
self.crossings.clear();
|
||||
self.forget();
|
||||
|
||||
let woken_in_gesture = std::mem::take(&mut self.woken_in_gesture);
|
||||
self.awake.retain(|target| !woken_in_gesture.contains(target));
|
||||
self.forget_targets_gone_to_sleep();
|
||||
}
|
||||
|
||||
/// Forgets what the pointer was last snapped to, as when the pointer is no longer placing anything.
|
||||
@@ -545,11 +551,14 @@ impl SnapSession {
|
||||
if let Awake::Position { id, .. } = target {
|
||||
self.position_sources.insert(id, sources.clone());
|
||||
}
|
||||
if self.gesture.is_some() {
|
||||
self.woken_in_gesture.push(target);
|
||||
}
|
||||
self.awake.push(target);
|
||||
}
|
||||
let over_the_limit = self.awake.len().saturating_sub(AWAKE_LIMIT);
|
||||
self.awake.drain(..over_the_limit);
|
||||
self.forget_sources_of_sleeping_positions();
|
||||
self.forget_targets_gone_to_sleep();
|
||||
self.constructions = None;
|
||||
|
||||
true
|
||||
@@ -563,6 +572,7 @@ impl SnapSession {
|
||||
/// Puts every woken target back to sleep, and keeps the pointer from waking them again until it moves.
|
||||
pub fn sleep_all(&mut self) {
|
||||
self.awake.clear();
|
||||
self.woken_in_gesture.clear();
|
||||
self.position_sources.clear();
|
||||
self.constructions = None;
|
||||
|
||||
@@ -583,10 +593,12 @@ impl SnapSession {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn forget_sources_of_sleeping_positions(&mut self) {
|
||||
/// Lets go of what is kept about woken targets that have since gone back to sleep.
|
||||
fn forget_targets_gone_to_sleep(&mut self) {
|
||||
let awake = &self.awake;
|
||||
self.position_sources
|
||||
.retain(|id, _| awake.iter().any(|target| matches!(target, Awake::Position { id: awake_id, .. } if awake_id == id)));
|
||||
self.woken_in_gesture.retain(|target| awake.contains(target));
|
||||
}
|
||||
|
||||
/// The woken targets, oldest first.
|
||||
@@ -721,7 +733,7 @@ impl SnapSession {
|
||||
Awake::Anchor { layer, .. } | Awake::Curve { layer, .. } | Awake::Box { layer } => !changed.contains(layer),
|
||||
Awake::Position { id, .. } => position_sources.get(id).is_none_or(|sources| !sources.iter().any(|layer| changed.contains(layer))),
|
||||
});
|
||||
self.forget_sources_of_sleeping_positions();
|
||||
self.forget_targets_gone_to_sleep();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1100,6 +1112,45 @@ mod tests {
|
||||
assert!(session.tick(1000 + WAKE_DWELL_IN_GESTURE));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_gesture_keeps_track_of_only_the_targets_it_woke_that_are_still_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(100., 100., 300., 240.).await;
|
||||
editor.draw_rect(500., 100., 700., 240.).await;
|
||||
let mut session = SnapSession::default();
|
||||
let input = InputPreprocessorMessageHandler::default();
|
||||
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
|
||||
|
||||
// Once the limit has put the first edge back to sleep, resting on it again wakes it a second time
|
||||
let along_edges = [(150., 100.), (300., 140.), (250., 240.), (100., 200.), (550., 100.), (700., 140.), (150., 100.)];
|
||||
for (index, position) in along_edges.into_iter().enumerate() {
|
||||
assert!(rest(&mut session, &editor, position.into(), index as u64 * 2000), "nothing woke at {position:?}");
|
||||
}
|
||||
assert_eq!(session.woken_in_gesture, session.awake);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn what_a_gesture_wakes_goes_back_to_sleep_when_it_ends_while_what_was_woken_before_it_stays_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(100., 100., 300., 240.).await;
|
||||
let mut session = SnapSession::default();
|
||||
|
||||
// The top edge is woken before the gesture, and the right edge during it
|
||||
assert!(rest(&mut session, &editor, DVec2::new(150., 100.), 0));
|
||||
let woken_before = session.awake.clone();
|
||||
|
||||
let input = InputPreprocessorMessageHandler::default();
|
||||
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
|
||||
snap_at_time(&mut session, &editor, DVec2::new(300., 140.), 2000);
|
||||
assert!(session.tick(2000 + WAKE_DWELL_IN_GESTURE));
|
||||
assert_eq!(session.awake.len(), 2);
|
||||
|
||||
session.end_gesture();
|
||||
assert_eq!(session.awake, woken_before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_the_latest_few_woken_targets_stay_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -29,6 +29,8 @@ pub struct GradientTool {
|
||||
#[derive(Default)]
|
||||
pub struct GradientOptions {
|
||||
gradient_form: GradientForm,
|
||||
/// Where the selected gradient's curvatures come from. Unless they make its form, neither form is shown as chosen.
|
||||
curvature_source: CurvatureSource,
|
||||
settings: GradientSettings,
|
||||
}
|
||||
|
||||
@@ -92,12 +94,16 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
||||
ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options {
|
||||
GradientOptionsUpdate::Form(gradient_form) => {
|
||||
self.options.gradient_form = gradient_form;
|
||||
self.options.curvature_source = CurvatureSource::Form;
|
||||
apply_gradient_update(
|
||||
&mut self.data,
|
||||
context,
|
||||
responses,
|
||||
|(_gradient, appearance)| appearance.gradient_form != gradient_form,
|
||||
|(_gradient, appearance)| appearance.gradient_form = gradient_form,
|
||||
|(_gradient, appearance)| appearance.gradient_form != gradient_form || appearance.curvature_source != CurvatureSource::Form,
|
||||
|(_gradient, appearance)| {
|
||||
appearance.gradient_form = gradient_form;
|
||||
appearance.curvature_source = CurvatureSource::Form;
|
||||
},
|
||||
);
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
responses.add(ToolMessage::UpdateCursor);
|
||||
@@ -192,14 +198,19 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
||||
|
||||
let mut needs_refresh = false;
|
||||
if let Some((_gradient, appearance)) = ¤t_gradient {
|
||||
if self.options.gradient_form != appearance.gradient_form {
|
||||
if self.options.gradient_form != appearance.gradient_form || self.options.curvature_source != appearance.curvature_source {
|
||||
self.options.gradient_form = appearance.gradient_form;
|
||||
self.options.curvature_source = appearance.curvature_source;
|
||||
needs_refresh = true;
|
||||
}
|
||||
if self.options.settings != appearance.settings {
|
||||
self.options.settings = appearance.settings;
|
||||
needs_refresh = true;
|
||||
}
|
||||
} else if self.options.curvature_source != CurvatureSource::Form {
|
||||
// With no gradient selected, the Form radio shows the form a new one gets
|
||||
self.options.curvature_source = CurvatureSource::Form;
|
||||
needs_refresh = true;
|
||||
}
|
||||
|
||||
let has_gradient = current_gradient.is_some();
|
||||
@@ -261,7 +272,11 @@ impl LayoutHolder for GradientTool {
|
||||
}
|
||||
.into()
|
||||
});
|
||||
let gradient_form = RadioInput::new(gradient_form_entries).selected_index(Some(self.options.gradient_form as u32)).widget_instance();
|
||||
let selected_form = (self.options.curvature_source == CurvatureSource::Form).then_some(self.options.gradient_form as u32);
|
||||
let gradient_form = RadioInput::new(gradient_form_entries)
|
||||
.selected_index(selected_form)
|
||||
.disabled(self.options.curvature_source == CurvatureSource::Graph)
|
||||
.widget_instance();
|
||||
|
||||
// Display priority: the selected layer's stops, then any user-customized tool default, then the working colors
|
||||
let stops_value = self
|
||||
@@ -381,10 +396,12 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
||||
let fill_node = network_interface.document_network().nodes.get(&fill_id)?;
|
||||
let gradient = graph_modification_utils::read_fill_node_gradient(fill_node, || network_interface.document_metadata().nonzero_bounding_box(layer))?;
|
||||
|
||||
let (gradient_form, curvature_source) = CurvatureSource::of(gradient.curvatures);
|
||||
return Some((
|
||||
gradient.stops,
|
||||
GradientAppearance {
|
||||
gradient_form: gradient.gradient_form,
|
||||
gradient_form,
|
||||
curvature_source,
|
||||
settings: gradient.settings,
|
||||
transform: gradient.transform,
|
||||
},
|
||||
@@ -404,19 +421,48 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
||||
struct GradientAppearance {
|
||||
transform: DAffine2,
|
||||
gradient_form: GradientForm,
|
||||
/// Where the chain's curvatures come from. Unless they make `gradient_form`, the tool draws the linear form's controls.
|
||||
// TODO: Draw the stops and midpoints of custom curvatures where their contours cross the line, since the ramp can then span just part of it
|
||||
curvature_source: CurvatureSource,
|
||||
settings: GradientSettings,
|
||||
}
|
||||
|
||||
/// Where a gradient's curvatures come from, as told by its 'Gradient Curvature' node or the Fill node holding it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum CurvatureSource {
|
||||
/// They make the form, or there's no node and the form's are implied.
|
||||
#[default]
|
||||
Form,
|
||||
/// They're values that make neither form.
|
||||
Custom,
|
||||
/// They're fed from the graph or exposed, so only the graph can change them.
|
||||
Graph,
|
||||
}
|
||||
|
||||
impl CurvatureSource {
|
||||
/// The form some curvatures make (linear if neither) and where they come from, given them unless the graph feeds them.
|
||||
fn of(curvatures: Option<[f64; 2]>) -> (GradientForm, Self) {
|
||||
let form = curvatures.and_then(GradientForm::from_curvatures);
|
||||
let source = match (curvatures, form) {
|
||||
(None, _) => Self::Graph,
|
||||
(Some(_), None) => Self::Custom,
|
||||
(Some(_), Some(_)) => Self::Form,
|
||||
};
|
||||
(form.unwrap_or_default(), source)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the gradient transform, form, and spread by walking the chain feeding the layer.
|
||||
fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance {
|
||||
let target_input = gradient_chain_target_input(layer, network_interface);
|
||||
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
||||
|
||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
|
||||
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
||||
let mut gradient_form: Option<GradientForm> = None;
|
||||
let mut curvature_source = CurvatureSource::Form;
|
||||
|
||||
for node_id in network_interface
|
||||
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
|
||||
@@ -430,11 +476,9 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
|
||||
if reference == transform_reference {
|
||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||
} else if reference == gradient_form_reference
|
||||
&& gradient_form.is_none()
|
||||
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||
{
|
||||
gradient_form = Some(*value);
|
||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
||||
let (form, source) = CurvatureSource::of(graph_modification_utils::gradient_curvature_values(document_node));
|
||||
(gradient_form, curvature_source) = (Some(form), source);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,6 +488,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
GradientAppearance {
|
||||
transform: composed_transform,
|
||||
gradient_form: gradient_form.unwrap_or_default(),
|
||||
curvature_source,
|
||||
settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
@@ -793,12 +838,15 @@ impl SelectedGradient {
|
||||
pub fn render_gradient(&mut self, responses: &mut VecDeque<Message>) {
|
||||
if let Some(layer) = self.layer {
|
||||
if self.is_gradient_chain {
|
||||
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, responses);
|
||||
// Only a new gradient takes its form from the tool, as the Properties panel may have adjusted an existing one after it was selected
|
||||
let write_form = self.dragging == GradientDragTarget::New;
|
||||
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, write_form, responses);
|
||||
} else {
|
||||
// Only a new gradient takes its form from the tool, as with a chain
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: self.gradient.clone(),
|
||||
gradient_form: self.appearance.gradient_form,
|
||||
gradient_form: (self.dragging == GradientDragTarget::New).then_some(self.appearance.gradient_form),
|
||||
gradient_settings: self.appearance.settings,
|
||||
transform: Some(self.appearance.transform),
|
||||
});
|
||||
@@ -829,8 +877,8 @@ impl SelectedGradient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer.
|
||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
|
||||
/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer, including its form's curvatures if `write_form` is set.
|
||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, write_form: bool, responses: &mut VecDeque<Message>) {
|
||||
responses.add(GraphOperationMessage::GradientCyclicSet {
|
||||
layer,
|
||||
gradient_cyclic: appearance.settings.cyclic,
|
||||
@@ -848,10 +896,12 @@ fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradien
|
||||
layer,
|
||||
transform: appearance.transform,
|
||||
});
|
||||
responses.add(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: appearance.gradient_form,
|
||||
});
|
||||
if write_form && appearance.curvature_source == CurvatureSource::Form {
|
||||
responses.add(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: appearance.gradient_form,
|
||||
});
|
||||
}
|
||||
responses.add(GraphOperationMessage::GradientSpreadSet {
|
||||
layer,
|
||||
gradient_spread: appearance.settings.spread,
|
||||
@@ -1522,6 +1572,7 @@ impl Fsm for GradientToolFsmState {
|
||||
GradientAppearance {
|
||||
transform: DAffine2::IDENTITY,
|
||||
gradient_form: tool_options.gradient_form,
|
||||
curvature_source: CurvatureSource::Form,
|
||||
settings: tool_options.settings,
|
||||
},
|
||||
// A blank layer, or one holding only the other tool's paint, starts a whole-expanse gradient chain; a layer with content gets its Fill painted
|
||||
@@ -1940,12 +1991,13 @@ fn apply_gradient_update(
|
||||
|
||||
// Only check for the gradient list once we know we'll write back, since this is a graph traversal per layer
|
||||
if get_upstream_gradient_value_node_id(layer, &context.document.network_interface).is_some() {
|
||||
dispatch_gradient_chain_writes(layer, &gradient, appearance, responses);
|
||||
// Read fresh from the layer, so its form's curvatures change only if the update chose another form
|
||||
dispatch_gradient_chain_writes(layer, &gradient, appearance, true, responses);
|
||||
} else {
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient,
|
||||
gradient_form: appearance.gradient_form,
|
||||
gradient_form: (appearance.curvature_source == CurvatureSource::Form).then_some(appearance.gradient_form),
|
||||
gradient_settings: appearance.settings,
|
||||
transform: Some(appearance.transform),
|
||||
});
|
||||
@@ -2011,7 +2063,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: new_gradient.clone(),
|
||||
gradient_form: appearance.gradient_form,
|
||||
gradient_form: None,
|
||||
gradient_settings: settings,
|
||||
transform: Some(appearance.transform),
|
||||
});
|
||||
@@ -2108,6 +2160,7 @@ mod test_gradient {
|
||||
use super::{GradientHoverTarget, detect_hover_target, gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at};
|
||||
use crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::layout::utility_types::layout_widget::{DiffUpdate, Layout, LayoutTarget, Widget, WidgetInstance};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
@@ -2115,8 +2168,8 @@ mod test_gradient {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id;
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation};
|
||||
@@ -3366,7 +3419,7 @@ mod test_gradient {
|
||||
.await;
|
||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
||||
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
editor
|
||||
@@ -3375,7 +3428,7 @@ mod test_gradient {
|
||||
})
|
||||
.await;
|
||||
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let form_node_id = {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
network_interface
|
||||
@@ -3384,10 +3437,10 @@ mod test_gradient {
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
||||
.expect("Gradient Form node should have been inserted")
|
||||
.expect("Gradient Curvature node should have been inserted")
|
||||
};
|
||||
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
|
||||
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
||||
|
||||
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
||||
@@ -3532,6 +3585,347 @@ mod test_gradient {
|
||||
assert!(matches!(positions_input, NodeInput::Node { .. }), "the wired positions input must survive the baked write");
|
||||
}
|
||||
|
||||
/// Drags the end of a layer's gradient by `offset` in the viewport with the Gradient tool, returning where the end was dragged to.
|
||||
async fn drag_gradient_end(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, offset: DVec2) -> DVec2 {
|
||||
let document = editor.active_document();
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
|
||||
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
|
||||
let dragged_end = end + offset;
|
||||
|
||||
editor.move_mouse(end.x, end.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(end.x, end.y, ModifierKeys::empty()).await;
|
||||
editor.move_mouse(dragged_end.x, dragged_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
editor
|
||||
.mouseup(
|
||||
EditorPointerState {
|
||||
editor_position: dragged_end,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
.await;
|
||||
|
||||
dragged_end
|
||||
}
|
||||
|
||||
/// Makes a layer drawing a gradient list along the line from (10, 50) to (200, 50) and selects it with the Gradient tool, then chooses
|
||||
/// the radial form, which inserts a 'Gradient Curvature' node. Returns the layer and that node.
|
||||
async fn radial_gradient_list_layer(editor: &mut EditorTestUtils) -> (LayerNodeIdentifier, NodeId) {
|
||||
editor.active_document_mut().snapping_state.snapping_enabled = false;
|
||||
let layer = create_gradient_list_layer(editor).await;
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::GradientTransformSet {
|
||||
layer,
|
||||
transform: transform_from_line(DVec2::new(10., 50.), DVec2::new(200., 50.)),
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
|
||||
editor
|
||||
.handle_message(GradientToolMessage::UpdateOptions {
|
||||
options: super::GradientOptionsUpdate::Form(GradientForm::Radial),
|
||||
})
|
||||
.await;
|
||||
let curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let curvature_node_id = network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&curvature_reference))
|
||||
.expect("Gradient Curvature node should have been inserted");
|
||||
assert_eq!(
|
||||
curvature_inputs(editor, curvature_node_id),
|
||||
inputs_holding(GradientForm::Radial.curvatures()),
|
||||
"the inserted node should hold the radial form's curvatures"
|
||||
);
|
||||
|
||||
(layer, curvature_node_id)
|
||||
}
|
||||
|
||||
/// Sets both curvatures of a 'Gradient Curvature' node, as its sliders in the Properties panel do.
|
||||
async fn set_curvatures(editor: &mut EditorTestUtils, curvature_node_id: NodeId, curvatures: [f64; 2]) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
for (input_index, curvature) in [StartCurvatureInput::INDEX, EndCurvatureInput::INDEX].into_iter().zip(curvatures) {
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: curvature_node_id,
|
||||
input_index,
|
||||
value: TaggedValue::Number(curvature).into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The start and end curvature inputs of a 'Gradient Curvature' node.
|
||||
fn curvature_inputs(editor: &EditorTestUtils, curvature_node_id: NodeId) -> [Option<NodeInput>; 2] {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let node = &editor.active_document().network_interface.document_network().nodes[&curvature_node_id];
|
||||
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
|
||||
}
|
||||
|
||||
/// The curvature inputs holding these values.
|
||||
fn inputs_holding(curvatures: [f64; 2]) -> [Option<NodeInput>; 2] {
|
||||
curvatures.map(|curvature| Some(NodeInput::value(TaggedValue::Number(curvature), false)))
|
||||
}
|
||||
|
||||
/// The Form radio's chosen entry and whether it's disabled, as last sent to the control bar among these frontend messages.
|
||||
fn latest_form_radio(frontend_messages: &[FrontendMessage]) -> Option<(Option<u32>, bool)> {
|
||||
let form_radio = |widget: &WidgetInstance| match &*widget.widget {
|
||||
Widget::RadioInput(radio_input) => Some((radio_input.selected_index, radio_input.disabled)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
frontend_messages
|
||||
.iter()
|
||||
.rev()
|
||||
.filter_map(|message| match message {
|
||||
FrontendMessage::UpdateLayout {
|
||||
layout_target: LayoutTarget::ToolOptions,
|
||||
diff,
|
||||
} => Some(diff),
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(|diff| diff.iter().rev())
|
||||
.find_map(|widget_diff| match &widget_diff.new_value {
|
||||
DiffUpdate::Widget(widget) => form_radio(widget),
|
||||
DiffUpdate::Layout(layout) => layout.iter().find_map(form_radio),
|
||||
DiffUpdate::LayoutGroup(group) => Layout(vec![group.clone()]).iter().find_map(form_radio),
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tool_edits_keep_custom_curvatures_until_a_form_is_chosen() {
|
||||
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
|
||||
|
||||
// Dragging the end writes every attribute the tool manages, but leaves the curvatures as they are
|
||||
let dragged_end = drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
|
||||
let document = editor.active_document();
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the gradient should survive the drag");
|
||||
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
|
||||
assert!(end.abs_diff_eq(dragged_end, 1.), "the drag should move the end to {dragged_end:?}, not {end:?}");
|
||||
assert_eq!(curvature_inputs(&editor, curvature_node_id), inputs_holding([0.5, 0.25]), "a drag shouldn't reset custom curvatures");
|
||||
|
||||
// Choosing a form in the control bar is what sets them
|
||||
editor
|
||||
.handle_message(GradientToolMessage::UpdateOptions {
|
||||
options: super::GradientOptionsUpdate::Form(GradientForm::Linear),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding(GradientForm::Linear.curvatures()),
|
||||
"choosing the linear form should set its curvatures"
|
||||
);
|
||||
|
||||
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
|
||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(number_node_id),
|
||||
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
|
||||
})
|
||||
.await;
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: GradientForm::Radial,
|
||||
})
|
||||
.await;
|
||||
let [start_input, end_input] = curvature_inputs(&editor, curvature_node_id);
|
||||
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
|
||||
assert_eq!(
|
||||
end_input,
|
||||
inputs_holding(GradientForm::Linear.curvatures())[1],
|
||||
"the end curvature beside a wired one should stay as it was"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn edits_of_a_fill_gradient_keep_its_curvatures_until_a_form_is_chosen() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_fill_node_id_with_direct_fill_input;
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.active_document_mut().snapping_state.snapping_enabled = false;
|
||||
editor.drag_tool(ToolType::Rectangle, -5., -3., 100., 100., ModifierKeys::empty()).await;
|
||||
editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layer = document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers(document.metadata())
|
||||
.next()
|
||||
.expect("the rectangle is selected");
|
||||
let fill_id = get_fill_node_id_with_direct_fill_input(layer, &document.network_interface).expect("the gradient is held by the Fill");
|
||||
let curvatures = |editor: &EditorTestUtils| {
|
||||
let node = &editor.active_document().network_interface.document_network().nodes[&fill_id];
|
||||
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
|
||||
};
|
||||
|
||||
// Curvatures making neither form survive a drag of the gradient's end
|
||||
for (input_index, curvature) in [(StartCurvatureInput::INDEX, 0.3), (EndCurvatureInput::INDEX, 0.2)] {
|
||||
let value = TaggedValue::Number(curvature).into();
|
||||
editor.handle_message(NodeGraphMessage::SetInputValue { node_id: fill_id, input_index, value }).await;
|
||||
}
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., 20.)).await;
|
||||
assert_eq!(curvatures(&editor), inputs_holding([0.3, 0.2]), "a drag shouldn't reset custom curvatures");
|
||||
|
||||
// Choosing a form in the control bar is what sets them
|
||||
let choose_form = |form| GradientToolMessage::UpdateOptions {
|
||||
options: super::GradientOptionsUpdate::Form(form),
|
||||
};
|
||||
editor.handle_message(choose_form(GradientForm::Radial)).await;
|
||||
assert_eq!(
|
||||
curvatures(&editor),
|
||||
inputs_holding(GradientForm::Radial.curvatures()),
|
||||
"choosing the radial form should set its curvatures"
|
||||
);
|
||||
|
||||
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
|
||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(number_node_id),
|
||||
input_connector: InputConnector::node(fill_id, StartCurvatureInput),
|
||||
})
|
||||
.await;
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
|
||||
editor.handle_message(choose_form(GradientForm::Linear)).await;
|
||||
let [start_input, end_input] = curvatures(&editor);
|
||||
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
|
||||
assert_eq!(
|
||||
end_input,
|
||||
inputs_holding(GradientForm::Radial.curvatures())[1],
|
||||
"the end curvature beside a wired one should stay as it was"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_edits_keep_curvatures_set_while_the_stop_was_selected() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
let stop_count = |editor: &EditorTestUtils| get_gradient_stops(layer, &editor.active_document().network_interface).map(|stops| stops.len());
|
||||
|
||||
// Clicking the line inserts a stop and selects it, and a double-click opens its color picker
|
||||
let document = editor.active_document();
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
|
||||
let stop = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::new(0.3, 0.));
|
||||
editor.move_mouse(stop.x, stop.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(stop.x, stop.y, ModifierKeys::empty()).await;
|
||||
editor.left_mouseup(stop.x, stop.y, ModifierKeys::empty()).await;
|
||||
editor.handle_message(GradientToolMessage::DoubleClick).await;
|
||||
assert_eq!(stop_count(&editor), Some(3), "the click should insert a stop");
|
||||
|
||||
// The Properties panel then adjusts curvatures of neither form while the stop stays selected
|
||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.5]).await;
|
||||
|
||||
editor.handle_message(GradientToolMessage::UpdateStopColor { color: Color::GREEN }).await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([0.5, 0.5]),
|
||||
"recoloring the stop shouldn't reset the curvatures"
|
||||
);
|
||||
|
||||
editor.press(Key::Delete, ModifierKeys::empty()).await;
|
||||
assert_eq!(stop_count(&editor), Some(2), "Delete should remove the selected stop");
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([0.5, 0.5]),
|
||||
"deleting the stop shouldn't reset the curvatures"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn curvatures_already_making_a_form_are_kept_by_writes_of_that_form() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
|
||||
// The start curvature's slider maximum is the same point as -1, so the tool draws these curvatures as the radial form
|
||||
set_curvatures(&mut editor, curvature_node_id, [1., 0.5]).await;
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &editor.active_document().network_interface).expect("the layer should have a gradient");
|
||||
assert_eq!((appearance.gradient_form, appearance.curvature_source), (GradientForm::Radial, super::CurvatureSource::Form));
|
||||
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([1., 0.5]),
|
||||
"a drag shouldn't rewrite curvatures making the form"
|
||||
);
|
||||
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: GradientForm::Radial,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([1., 0.5]),
|
||||
"setting the form they make shouldn't rewrite them"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_form_radio_shows_what_a_new_gradient_gets_once_a_custom_one_is_deselected() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
|
||||
|
||||
// Reselecting the layer has the tool read its curvatures, which make neither form
|
||||
let mut frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
assert_eq!(latest_form_radio(&frontend_messages), Some((None, false)), "custom curvatures should show neither form as chosen");
|
||||
|
||||
frontend_messages.extend(editor.handle_message(DocumentMessage::DeselectAllLayers).await);
|
||||
assert_eq!(
|
||||
latest_form_radio(&frontend_messages),
|
||||
Some((Some(GradientForm::Linear as u32), false)),
|
||||
"with nothing selected, the radio should show the linear form a new gradient gets"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_form_radio_is_disabled_for_curvatures_fed_from_the_graph() {
|
||||
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
|
||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(number_node_id),
|
||||
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
|
||||
})
|
||||
.await;
|
||||
|
||||
let frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
assert_eq!(
|
||||
latest_form_radio(&frontend_messages),
|
||||
Some((None, true)),
|
||||
"a wired curvature should leave no form chosen and the radio disabled"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn drag_on_blank_layer_starts_gradient_chain() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
||||
|
||||
@@ -398,8 +398,7 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeTemplateImplementation, shipped_node_id};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -430,20 +429,8 @@ mod tests {
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
// The node adding Merge's content to the stack
|
||||
let Some(NodeTemplateImplementation::Network(merge_network)) = resolve_network_node_type("Merge").map(|merge| &merge.node_template.implementation) else {
|
||||
panic!("Merge should be a network node")
|
||||
};
|
||||
let Some((&extend_id, _)) = merge_network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER))
|
||||
else {
|
||||
panic!("Merge should extend the stack with its content")
|
||||
};
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", extend_id))]);
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
|
||||
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
|
||||
assert_eq!(
|
||||
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
import { getContext, onMount, onDestroy } from "svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
|
||||
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
|
||||
import type { DragToggleListener } from "/src/managers/drag-toggle";
|
||||
import { inspectorLayout } from "/src/stores/portfolio";
|
||||
import { createAutoScroller } from "/src/utility-functions/auto-scroll";
|
||||
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
@@ -23,7 +25,15 @@
|
||||
let lastDragClientY = 0;
|
||||
const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY));
|
||||
|
||||
// Everything one middle-button drag across the section headers paints is one history step
|
||||
const dragToggleListener: DragToggleListener = {
|
||||
groups: ["inspector-section-visibility"],
|
||||
engagedChanged: (engaged) => (engaged ? editor.startTransaction() : editor.endTransaction()),
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
createDragToggleManager(dragToggleListener);
|
||||
|
||||
addEventListener("pointermove", draggingPointerMove);
|
||||
addEventListener("pointerup", draggingPointerUp);
|
||||
// A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it
|
||||
@@ -36,6 +46,8 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
destroyDragToggleManager(dragToggleListener);
|
||||
|
||||
removeEventListener("pointermove", draggingPointerMove);
|
||||
removeEventListener("pointerup", draggingPointerUp);
|
||||
removeEventListener("pointercancel", abortDrag);
|
||||
|
||||
@@ -331,6 +331,7 @@
|
||||
}
|
||||
|
||||
const dragToggleListener: DragToggleListener = {
|
||||
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
|
||||
activeGroupChanged: (group) => {
|
||||
activeDragToggleGroup = group;
|
||||
},
|
||||
@@ -342,6 +343,15 @@
|
||||
editor.toggleNodeVisibilityLayerPanel(id);
|
||||
}
|
||||
|
||||
// Middle-clicking one of the chain's node buttons toggles that node's visibility
|
||||
function chainIconsAuxClick(e: MouseEvent, listing: LayerListingInfo) {
|
||||
if (e.button !== 1) return;
|
||||
|
||||
const chainNodeButton = e.target instanceof Element ? e.target.closest("[data-chain-node]") : undefined;
|
||||
const chainNode = chainNodeButton ? listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined;
|
||||
if (chainNode) toggleNodeVisibilityLayerPanel(chainNode.id);
|
||||
}
|
||||
|
||||
function toggleLayerLock(id: bigint) {
|
||||
editor.toggleLayerLock(id);
|
||||
}
|
||||
@@ -1194,6 +1204,7 @@
|
||||
on:pointerdown={(e) => layerPointerDown(e, listing)}
|
||||
on:click={(e) => selectLayerWithModifiers(e, listing)}
|
||||
on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
|
||||
on:auxclick={(e) => chainIconsAuxClick(e, listing)}
|
||||
on:pointerenter={() => hoverRow(index)}
|
||||
on:pointerleave={() => (hoveredRowIndex = undefined)}
|
||||
>
|
||||
@@ -1343,6 +1354,8 @@
|
||||
data-chain-node={slot.nodeIndex}
|
||||
data-chain-gap-before={slot.reorderablePosition}
|
||||
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
|
||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
||||
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -1359,12 +1372,17 @@
|
||||
: entry.chainExpanded
|
||||
? "Stop listing this layer's chain one node per row."
|
||||
: "List this layer's chain one node per row, beneath the layer."}
|
||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
||||
data-drag-toggle-state={entry.visible ? "visible" : "hidden"}
|
||||
on:click={(e) => {
|
||||
// Without a chain to expand, a click selects the layer as it does elsewhere in the row
|
||||
if (entry.chainNodes.length === 0) return;
|
||||
e.stopPropagation();
|
||||
editor.toggleLayerChainExpanded(listing.id);
|
||||
}}
|
||||
on:auxclick={(e) => {
|
||||
if (e.button === 1) toggleNodeVisibilityLayerPanel(listing.id);
|
||||
}}
|
||||
>
|
||||
<IconLabel
|
||||
icon={entry.iconName}
|
||||
@@ -1395,10 +1413,15 @@
|
||||
data-chain-row-node={slot.nodeIndex}
|
||||
data-chain-gap-before={slot.reorderablePosition}
|
||||
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
|
||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
||||
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
|
||||
on:pointerdown={(e) => {
|
||||
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
|
||||
}}
|
||||
on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
|
||||
on:auxclick={(e) => {
|
||||
if (e.button === 1) toggleNodeVisibilityLayerPanel(chainNode.id);
|
||||
}}
|
||||
on:dblclick={(e) => {
|
||||
// Only the node's icon opens it in the graph
|
||||
if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id);
|
||||
|
||||
@@ -41,6 +41,12 @@
|
||||
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
|
||||
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
|
||||
}
|
||||
|
||||
function toggleVisibilityWithMiddleClick(e: MouseEvent) {
|
||||
if (e.button !== 1 || widgetData.disabled) return;
|
||||
|
||||
editor.toggleNodeVisibilityInspector(widgetData.id);
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- TODO: Implement collapsable sections with the Inspector system -->
|
||||
@@ -76,7 +82,16 @@
|
||||
{/if}
|
||||
{/each}
|
||||
{:else}
|
||||
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}>
|
||||
<button
|
||||
class="header"
|
||||
class:expanded
|
||||
class:expandable
|
||||
data-inspector-reorder-handle={reorderable ? "" : undefined}
|
||||
data-middle-drag-toggle-group={widgetData.disabled ? undefined : "inspector-section-visibility"}
|
||||
data-drag-toggle-state={widgetData.visible ? "visible" : "hidden"}
|
||||
onclick={toggleExpandedWithModifiers}
|
||||
onauxclick={toggleVisibilityWithMiddleClick}
|
||||
>
|
||||
<div
|
||||
class="icon-slot"
|
||||
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
|
||||
@@ -543,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 {
|
||||
|
||||
@@ -140,7 +140,9 @@
|
||||
const reorder = allowReorder && allowSelect;
|
||||
let held = position;
|
||||
|
||||
if (!reorder && !allowWrap) {
|
||||
if (!reorder && !allowWrap && markers.some((marker) => marker.overlapNext !== "Never")) {
|
||||
held = holdWithOverlaps(first, last, position);
|
||||
} else if (!reorder && !allowWrap) {
|
||||
const lower = neighborBound(first, -1) ?? 0;
|
||||
const upper = (neighborBound(last, 1) ?? 1) - spacing;
|
||||
held = Math.max(lower, Math.min(upper, position));
|
||||
@@ -156,6 +158,33 @@
|
||||
return wrap ? held - Math.floor(held) : Math.max(0, Math.min(1 - spacing, held));
|
||||
}
|
||||
|
||||
// Holds markers `first..=last` moving to `position` within the track and each member's bounds from the markers outside the run, as the backend's `overlap_bounds` gives them
|
||||
function holdWithOverlaps(first: number, last: number, position: number): number {
|
||||
const outsideRun = (i: number) => i >= 0 && i < markers.length && (i < first || i > last);
|
||||
const overlap = (i: number) => (i >= 0 && i < markers.length ? markers[i].overlapNext : "Never");
|
||||
const boundsBeyond = (near: number, far: number) => (overlap(near) === "NextOnly" || overlap(far) === "NextOnly") && overlap(near) !== "Freely" && overlap(far) !== "Freely";
|
||||
|
||||
let lower = 0;
|
||||
let upper = 1;
|
||||
for (let k = first; k <= last; k += 1) {
|
||||
const offset = markers[k].position - markers[first].position;
|
||||
lower = Math.max(lower, -offset);
|
||||
upper = Math.min(upper, 1 - offset);
|
||||
|
||||
// A neighbor bounds the marker unless they overlap, and past a neighbor overlapping only its next, so does the marker beyond it
|
||||
const lowerBounds = [overlap(k - 1) === "Never" ? k - 1 : -1, boundsBeyond(k - 1, k - 2) ? k - 2 : -1];
|
||||
const upperBounds = [overlap(k) === "Never" ? k + 1 : -1, boundsBeyond(k, k + 1) ? k + 2 : -1];
|
||||
lowerBounds.filter(outsideRun).forEach((i) => {
|
||||
lower = Math.max(lower, markers[i].position - offset);
|
||||
});
|
||||
upperBounds.filter(outsideRun).forEach((i) => {
|
||||
upper = Math.min(upper, markers[i].position - offset);
|
||||
});
|
||||
}
|
||||
|
||||
return Math.max(lower, Math.min(upper, position));
|
||||
}
|
||||
|
||||
// The position of the nearest marker past `index` in the direction of `step` that bounds others, skipping any placed between its neighbors since those follow them instead
|
||||
function neighborBound(index: number, step: -1 | 1): number | undefined {
|
||||
for (let i = index + step; i >= 0 && i < markers.length; i += step) {
|
||||
@@ -657,7 +686,10 @@
|
||||
}
|
||||
$: midpointPositions = diamondPositions(markers, showMidpoints, trackCyclic, trackInterpolation);
|
||||
$: strips = markerSpans(markers, allowWrap, (marker) => marker.pairedWithNext);
|
||||
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext);
|
||||
// A dashed link vanishes while the markers it joins have overlapped past each other, leaving no span between them
|
||||
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext).filter(
|
||||
({ index }) => markers[index].overlapNext === "Never" || markers[index + 1].position >= markers[index].position,
|
||||
);
|
||||
|
||||
onMount(() => {
|
||||
document.addEventListener("keydown", deleteShortcut);
|
||||
|
||||
@@ -8,21 +8,30 @@
|
||||
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain
|
||||
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
|
||||
// the pointer enters whose state still matches the source's recorded starting state is also clicked.
|
||||
//
|
||||
// Peers toggled by the middle button declare data-middle-drag-toggle-group instead, and toggle on an `auxclick`
|
||||
// rather than a click. Their gesture engages on the press, which toggles the source at once.
|
||||
|
||||
export type DragToggleListener = {
|
||||
// The groups whose gestures this listener is told about
|
||||
groups: string[];
|
||||
// Given the group of the pressed button, and undefined once the press ends
|
||||
activeGroupChanged?: (activeGroup: string | undefined) => void;
|
||||
// Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step
|
||||
engagedChanged?: (engaged: boolean) => void;
|
||||
};
|
||||
|
||||
const MIDDLE_BUTTON = 1;
|
||||
|
||||
const listeners = new Set<DragToggleListener>();
|
||||
let activeGroup: string | undefined = undefined;
|
||||
let middleButtonGesture = false;
|
||||
let source: HTMLElement | undefined = undefined;
|
||||
let startingState: string | undefined = undefined;
|
||||
let visited = new WeakSet<Element>();
|
||||
let engaged = false;
|
||||
let suppressNextClickFromSource: HTMLElement | undefined = undefined;
|
||||
let suppressNextAuxClick = false;
|
||||
|
||||
export function createDragToggleManager(listener: DragToggleListener) {
|
||||
listeners.add(listener);
|
||||
@@ -38,12 +47,13 @@ export function createDragToggleManager(listener: DragToggleListener) {
|
||||
window.addEventListener("blur", onPointerUp);
|
||||
// Capture phase on click suppresses the natural source-click before the button's handler runs
|
||||
window.addEventListener("click", onClickCapture, true);
|
||||
window.addEventListener("auxclick", onAuxClickCapture, true);
|
||||
}
|
||||
}
|
||||
|
||||
export function destroyDragToggleManager(listener: DragToggleListener) {
|
||||
// A consumer leaving mid-gesture still hears it end
|
||||
if (engaged) listener.engagedChanged?.(false);
|
||||
if (engaged && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false);
|
||||
listeners.delete(listener);
|
||||
|
||||
// Uninstall the window event listeners only once the last consumer leaves
|
||||
@@ -54,83 +64,120 @@ export function destroyDragToggleManager(listener: DragToggleListener) {
|
||||
window.removeEventListener("pointercancel", onPointerUp);
|
||||
window.removeEventListener("blur", onPointerUp);
|
||||
window.removeEventListener("click", onClickCapture, true);
|
||||
window.removeEventListener("auxclick", onAuxClickCapture, true);
|
||||
|
||||
activeGroup = undefined;
|
||||
middleButtonGesture = false;
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
suppressNextClickFromSource = undefined;
|
||||
suppressNextAuxClick = false;
|
||||
}
|
||||
}
|
||||
|
||||
function notifyActiveGroupChange(group: string | undefined) {
|
||||
activeGroup = group;
|
||||
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
|
||||
function listenersOfGroup(group: string): DragToggleListener[] {
|
||||
return Array.from(listeners).filter((listener) => listener.groups.includes(group));
|
||||
}
|
||||
|
||||
function findMember(target: EventTarget | undefined): HTMLElement | undefined {
|
||||
function notifyActiveGroupChange(group: string | undefined) {
|
||||
const previousGroup = activeGroup;
|
||||
activeGroup = group;
|
||||
|
||||
const notifiedGroup = group || previousGroup;
|
||||
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
|
||||
}
|
||||
|
||||
function groupAttribute(middleButton: boolean): string {
|
||||
return middleButton ? "data-middle-drag-toggle-group" : "data-drag-toggle-group";
|
||||
}
|
||||
|
||||
function findMember(target: EventTarget | undefined, middleButton: boolean): HTMLElement | undefined {
|
||||
if (!(target instanceof Element)) return undefined;
|
||||
const found = target.closest("[data-drag-toggle-group]");
|
||||
const found = target.closest(`[${groupAttribute(middleButton)}]`);
|
||||
return found instanceof HTMLElement ? found : undefined;
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (e.button !== 0) return;
|
||||
suppressNextClickFromSource = undefined;
|
||||
function memberState(member: HTMLElement): string | undefined {
|
||||
return member.getAttribute("data-drag-toggle-state") || undefined;
|
||||
}
|
||||
|
||||
const found = findMember(e.target || undefined);
|
||||
function toggle(member: HTMLElement) {
|
||||
if (middleButtonGesture) member.dispatchEvent(new MouseEvent("auxclick", { button: MIDDLE_BUTTON, bubbles: true }));
|
||||
else member.click();
|
||||
}
|
||||
|
||||
function engage() {
|
||||
if (!activeGroup || !source) return;
|
||||
|
||||
engaged = true;
|
||||
visited.add(source);
|
||||
listenersOfGroup(activeGroup).forEach((listener) => listener.engagedChanged?.(true));
|
||||
if (memberState(source) === startingState) toggle(source);
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return;
|
||||
suppressNextClickFromSource = undefined;
|
||||
suppressNextAuxClick = false;
|
||||
|
||||
const middleButton = e.button === MIDDLE_BUTTON;
|
||||
const found = findMember(e.target || undefined, middleButton);
|
||||
if (!found) return;
|
||||
|
||||
// Stop the event so sibling drag/select handlers on ancestors don't also engage
|
||||
e.stopPropagation();
|
||||
|
||||
middleButtonGesture = middleButton;
|
||||
source = found;
|
||||
startingState = found.getAttribute("data-drag-toggle-state") || undefined;
|
||||
startingState = memberState(found);
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined);
|
||||
notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
|
||||
|
||||
if (middleButton) engage();
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent) {
|
||||
if (!activeGroup || !source) return;
|
||||
|
||||
const member = findMember(e.target || undefined);
|
||||
if (!member || member.getAttribute("data-drag-toggle-group") !== activeGroup) return;
|
||||
const member = findMember(e.target || undefined, middleButtonGesture);
|
||||
if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
|
||||
|
||||
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
|
||||
if (member === source || visited.has(member)) return;
|
||||
|
||||
// First crossing engages the drag and toggles the source as part of the operation
|
||||
if (!engaged) {
|
||||
engaged = true;
|
||||
visited.add(source);
|
||||
listeners.forEach((listener) => listener.engagedChanged?.(true));
|
||||
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
|
||||
}
|
||||
if (!engaged) engage();
|
||||
|
||||
// Toggle only peers still in the starting state, so we don't flip ones already at the target state
|
||||
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
|
||||
if (memberState(member) !== startingState) return;
|
||||
|
||||
visited.add(member);
|
||||
member.click();
|
||||
toggle(member);
|
||||
}
|
||||
|
||||
function onPointerUp(e: Event) {
|
||||
if (!activeGroup) return;
|
||||
const endedGroup = activeGroup;
|
||||
|
||||
// An engaged drag already clicked the source, so the click its release sends is suppressed rather than toggling it again
|
||||
if (engaged && source && e.type === "pointerup") suppressNextClickFromSource = source;
|
||||
// An engaged drag already toggled the source, so its release's click won't toggle it again
|
||||
if (engaged && source && e.type === "pointerup") {
|
||||
if (middleButtonGesture) suppressNextAuxClick = true;
|
||||
else suppressNextClickFromSource = source;
|
||||
}
|
||||
const wasEngaged = engaged;
|
||||
|
||||
middleButtonGesture = false;
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(undefined);
|
||||
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false));
|
||||
if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
|
||||
}
|
||||
|
||||
function onClickCapture(e: Event) {
|
||||
@@ -141,6 +188,15 @@ function onClickCapture(e: Event) {
|
||||
suppressNextClickFromSource = undefined;
|
||||
}
|
||||
|
||||
// Unlike a click, this isn't limited to the source, since a drag's auxclick lands on the ancestor shared by its press and release
|
||||
function onAuxClickCapture(e: MouseEvent) {
|
||||
if (!suppressNextAuxClick || e.button !== MIDDLE_BUTTON) return;
|
||||
suppressNextAuxClick = false;
|
||||
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
|
||||
import.meta.hot?.accept((newModule) => {
|
||||
const carried = Array.from(listeners);
|
||||
|
||||
+2
-24
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
|
||||
}
|
||||
```
|
||||
|
||||
None of these definitions are written by hand. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`. A built-in node made from a subgraph has its definition generated from the `graph` macro (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
|
||||
Only the definitions of built-in nodes made from a nested network are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
|
||||
|
||||
## Inspector
|
||||
|
||||
@@ -127,29 +127,7 @@ fn opacity<T>(
|
||||
|
||||
## Additional Macro Options
|
||||
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `step`, `display_decimal_places`, `unit`, `integer`, `labels`, `blank_assist`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, `#[display_decimal_places(2)]` sets how many decimal places a number's widget shows, `#[integer]` makes a number or Vec2 widget take only integers, `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[blank_assist(false)]` drops the space a widget leaves for its assist area. `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
|
||||
## Creating a node from a subgraph
|
||||
|
||||
A node built from other nodes uses the `graph` macro, which registers the subgraph as a catalog definition. It takes `category`, `icon`, `name`, and `version` as `node` does, plus `layer` for a node that starts as a layer. Unlike a proto node's, a graph's name (or the title derived from its function name) is also its catalog identifier, which documents store. The function's parameters are the subgraph's imports, which are parsed like a proto node's parameters and take the same value and widget attributes. On an import, `#[hard]` bounds the Inspector widget without clamping a value wired into it. `out!(...)` names the exports. In the body, `>>` feeds its left side into the primary input of the node on its right, every other parameter is named in the call, and a bare name feeds the binding or import of that name into the parameter of the same name. State methods after a call, each written once, set the node's position in grid units (`.at(x, y)`), its display name (`.named("…")`), its flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`), and its call argument (`.call_argument::<Footprint>()`, or `impl Any` for a generic one). An output's name after the call or a binding, like `.captures`, wires from that output instead of the primary one, and goes after any state methods. The body ends with one value per export, as a final expression or with `return`. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
|
||||
|
||||
```rs
|
||||
/// Loads an image from a given URL.
|
||||
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
|
||||
pub fn load_image(
|
||||
_: (),
|
||||
/// The web address or local asset path of the image to load.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
) -> out!(
|
||||
/// The loaded image.
|
||||
image,
|
||||
) {
|
||||
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
|
||||
}
|
||||
```
|
||||
|
||||
Each node, parameter, and output name resolves through the module the `node` or `graph` macro generates for that node, named after its function, so a misspelled one is reported where it's written. The module's `PARAMETER_COUNT` lets the macro reject `>>` into a node with no parameters. Proto nodes don't name their outputs in that module, so only a graph's outputs can be chosen by name. Every input a call leaves out keeps the default from the node's own definition.
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `unit`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, while `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
|
||||
## Executing a document `NodeNetwork`
|
||||
|
||||
|
||||
@@ -360,15 +360,11 @@ impl NodeNetwork {
|
||||
};
|
||||
let value_node_id = gen_id();
|
||||
let merged_node_id = map_ids(id, value_node_id);
|
||||
let mut original_location = OriginalLocation {
|
||||
path: Some(path.to_vec()),
|
||||
let original_location = OriginalLocation {
|
||||
dependants: vec![vec![id]],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if let Some(path) = &mut original_location.path {
|
||||
path.push(value_node_id);
|
||||
}
|
||||
collection.insert(
|
||||
merged_node_id,
|
||||
DocumentNode {
|
||||
|
||||
@@ -63,7 +63,6 @@ fn flatten_add_expected() -> NodeNetwork {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(4)]),
|
||||
dependants: vec![vec![NodeId(10)]],
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -12,7 +12,7 @@ pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphene_application_io::resource::ResourceHash;
|
||||
use graphene_application_io::resource::ResourceId;
|
||||
use graphic_types::raster_types::{CPU, Image, Raster};
|
||||
use graphic_types::raster_types::{CPU, Image, Pixels, Raster};
|
||||
use graphic_types::vector_types::vector::misc::BoxCorners;
|
||||
use graphic_types::vector_types::vector::style::DashPattern;
|
||||
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
|
||||
@@ -400,6 +400,11 @@ macro_rules! tagged_value {
|
||||
Type::Fn(_, output) => TaggedValue::from_type(output),
|
||||
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
|
||||
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
|
||||
// Pixels are read back from an image, so a `Pixels` input holds the empty image
|
||||
if **element == concrete!(Pixels) {
|
||||
return Some(TaggedValue::TypeDefault(item!(Raster<CPU>)));
|
||||
}
|
||||
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||
@@ -416,6 +421,9 @@ macro_rules! tagged_value {
|
||||
if **element == concrete!(Stroke) {
|
||||
return Some(TaggedValue::Strokes(Vec::new()));
|
||||
}
|
||||
if **element == concrete!(Pixels) {
|
||||
return Some(TaggedValue::TypeDefault(list!(Raster<CPU>)));
|
||||
}
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||
@@ -551,6 +559,7 @@ tagged_value! {
|
||||
WarpStyle(graphic_types::WarpStyle),
|
||||
WaveType(graphic_types::WaveType),
|
||||
DisplaceMode(graphic_types::DisplaceMode),
|
||||
BlendIfChannel(graphic_types::BlendIfChannel),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -569,6 +578,7 @@ tagged_value! {
|
||||
StrokeAlign(vector::style::StrokeAlign),
|
||||
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
||||
GradientForm(vector::style::GradientForm),
|
||||
GradientModel(vector::style::GradientModel),
|
||||
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
|
||||
GradientSpread(vector::style::GradientSpread),
|
||||
GradientSpace(vector::style::GradientSpace),
|
||||
|
||||
@@ -26,10 +26,10 @@ 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, 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, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
@@ -68,7 +68,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>]),
|
||||
@@ -271,6 +270,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -303,6 +303,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
@@ -380,7 +381,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
DVec2,
|
||||
DAffine2,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -440,6 +440,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
node_types.extend(ranked_value_types!(cache_chain_nodes));
|
||||
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
|
||||
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
|
||||
// Context nullification can wrap the read-back adapter's output
|
||||
node_types.extend(cache_chain_nodes!(Pixels));
|
||||
// A position wire may feed a ranked vector connector, each position becoming a single-anchor vector
|
||||
node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector));
|
||||
// A string wire may feed the ranked `Item<DashPattern>` dash connector by parsing each element into a dash pattern
|
||||
@@ -496,6 +498,20 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
|
||||
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
|
||||
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
|
||||
// An image wire feeds a `Pixels` connector through its GPU readback, an async node taking the executor, runtime, and source ID after the wire.
|
||||
// These rows have no one-input passthrough siblings, which type resolution would match by their first input alone.
|
||||
macro_rules! read_back_node {
|
||||
($node:ty, wire: $wire:ty) => {
|
||||
async_node!(
|
||||
identifier: graphene_std::read_back::INPUT_ADAPTER,
|
||||
$node,
|
||||
input: Context,
|
||||
fn_params: [Context => $wire, Context => Item<wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::RuntimeHandle>, Context => Item<graphene_std::SourceId>]
|
||||
)
|
||||
};
|
||||
}
|
||||
node_types.push(read_back_node!(graphene_std::read_back::ReadBackNode<_, _, _, _>, wire: Item<Raster<CPU>>));
|
||||
node_types.push(read_back_node!(graphene_std::read_back::ReadBackListNode<_, _, _, _>, wire: List<Raster<CPU>>));
|
||||
// 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>) => {
|
||||
@@ -515,6 +531,7 @@ 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<GradientSpread>),
|
||||
attribute_value_node!(Item<GradientSpace>),
|
||||
attribute_value_node!(Item<GradientHueDirection>),
|
||||
|
||||
@@ -72,31 +72,32 @@ impl BlendMode {
|
||||
]
|
||||
}
|
||||
|
||||
/// The subset of [`BlendMode::list()`] that is supported by SVG.
|
||||
pub fn list_svg_subset() -> [&'static [BlendMode]; 6] {
|
||||
use BlendMode::*;
|
||||
[
|
||||
// Normal group
|
||||
&[Normal],
|
||||
// Darken group
|
||||
&[Darken, Multiply, ColorBurn],
|
||||
// Lighten group
|
||||
&[Lighten, Screen, ColorDodge],
|
||||
// Contrast group
|
||||
&[Overlay, SoftLight, HardLight],
|
||||
// Inversion group
|
||||
&[Difference, Exclusion],
|
||||
// Component group
|
||||
&[Hue, Saturation, Color, Luminosity],
|
||||
]
|
||||
}
|
||||
|
||||
pub fn index_in_list(&self) -> Option<usize> {
|
||||
Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
|
||||
}
|
||||
|
||||
pub fn index_in_list_svg_subset(&self) -> Option<usize> {
|
||||
Self::list_svg_subset().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
|
||||
/// Whether a layer in this mode reads what lies beneath it to blend, since neither SVG's `mix-blend-mode` nor Vello's layers have the mode.
|
||||
/// The alpha-only utility modes, hidden from the list, draw layers normally.
|
||||
pub fn reads_backdrop(&self) -> bool {
|
||||
self.to_svg_style_name().is_none() && !matches!(self, BlendMode::Erase | BlendMode::Restore | BlendMode::MultiplyAlpha)
|
||||
}
|
||||
|
||||
/// Whether a paint's strength (an effect's opacity, or a layer's fill) moves its color toward the mode's neutral color, which then blends at full strength, rather than fading the blend, for PSD interop.
|
||||
pub fn strength_moves_toward_neutral(&self) -> bool {
|
||||
use BlendMode::*;
|
||||
matches!(self, ColorDodge | LinearDodge | ColorBurn | LinearBurn | VividLight | LinearLight | HardMix)
|
||||
}
|
||||
|
||||
/// Whether a layer's fill moves its content toward the mode's neutral color (see [`Self::strength_moves_toward_neutral`]) rather than fading it, for PSD interop.
|
||||
/// The layer then reads what lies beneath it to blend (see [`Self::layer_reads_backdrop`]).
|
||||
pub fn fill_moves_layer_toward_neutral(&self) -> bool {
|
||||
self.strength_moves_toward_neutral()
|
||||
}
|
||||
|
||||
/// Whether a layer in this mode at this `fill` reads what lies beneath it to blend: in a mode neither SVG's `mix-blend-mode` nor Vello's layers have,
|
||||
/// or below a full fill moving it toward the mode's neutral color, which Color Dodge and Color Burn layers otherwise blend natively without.
|
||||
pub fn layer_reads_backdrop(&self, fill: f32) -> bool {
|
||||
self.reads_backdrop() || (fill < 1. && self.fill_moves_layer_toward_neutral())
|
||||
}
|
||||
|
||||
/// Convert the enum to the CSS string for the blend mode.
|
||||
@@ -130,11 +131,14 @@ impl BlendMode {
|
||||
}
|
||||
|
||||
/// Renders the blend mode CSS style declaration.
|
||||
/// A mode CSS lacks, which layers read what lies beneath to blend by, draws normally where nothing beneath can be read, as for content without bounds.
|
||||
pub fn render(&self) -> String {
|
||||
format!(
|
||||
r#" mix-blend-mode: {};"#,
|
||||
self.to_svg_style_name().unwrap_or_else(|| {
|
||||
log::warn!("Unsupported blend mode {self:?}");
|
||||
if !self.reads_backdrop() {
|
||||
log::warn!("Unsupported blend mode {self:?}");
|
||||
}
|
||||
"normal"
|
||||
})
|
||||
)
|
||||
@@ -156,7 +160,7 @@ impl Display for BlendMode {
|
||||
BlendMode::Lighten => write!(f, "Lighten"),
|
||||
BlendMode::Screen => write!(f, "Screen"),
|
||||
BlendMode::ColorDodge => write!(f, "Color Dodge"),
|
||||
BlendMode::LinearDodge => write!(f, "Linear Dodge"),
|
||||
BlendMode::LinearDodge => write!(f, "Linear Dodge (Add)"),
|
||||
BlendMode::LighterColor => write!(f, "Lighter Color"),
|
||||
// Contrast group
|
||||
BlendMode::Overlay => write!(f, "Overlay"),
|
||||
@@ -247,6 +251,30 @@ pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendM
|
||||
}
|
||||
}
|
||||
|
||||
/// How strongly a layer whose fill moves it toward neutral (see [`BlendMode::fill_moves_layer_toward_neutral`]) shows over a backdrop of `backdrop_alpha`: fully over an opaque one,
|
||||
/// by its `fill` over nothing, and between, the harmonic mean of the two weighted by that alpha, which shows nothing at no fill.
|
||||
pub fn layer_fill_shown(backdrop_alpha: f32, fill: f32) -> f32 {
|
||||
let weighted = (1. - backdrop_alpha) + backdrop_alpha * fill;
|
||||
if weighted <= 0. { 0. } else { (fill / weighted).min(1.) }
|
||||
}
|
||||
|
||||
/// Like [`apply_blend_mode`], with the foreground at `strength` (from 0 to 1) moved toward the mode's neutral color where it does that (see [`BlendMode::strength_moves_toward_neutral`]),
|
||||
/// for the caller to composite at full strength. Other modes take the foreground as it is, for the caller to fade the blend by the strength.
|
||||
pub fn apply_blend_mode_at_strength(foreground: Color, background: Color, blend_mode: BlendMode, strength: f32) -> Color {
|
||||
let toward = |neutral: f32| {
|
||||
let moved = |channel: f32| neutral + strength * (channel - neutral);
|
||||
Color::from_rgbaf32_unchecked(moved(foreground.r()), moved(foreground.g()), moved(foreground.b()), foreground.a())
|
||||
};
|
||||
|
||||
match blend_mode {
|
||||
BlendMode::ColorDodge | BlendMode::LinearDodge => apply_blend_mode(toward(0.), background, blend_mode),
|
||||
BlendMode::ColorBurn | BlendMode::LinearBurn => apply_blend_mode(toward(1.), background, blend_mode),
|
||||
BlendMode::VividLight | BlendMode::LinearLight => apply_blend_mode(toward(0.5), background, blend_mode),
|
||||
BlendMode::HardMix => background.blend_rgb(foreground, |backdrop, source| Color::blend_hard_mix_at_strength(backdrop, source, strength)),
|
||||
_ => apply_blend_mode(foreground, background, blend_mode),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -261,9 +289,13 @@ mod tests {
|
||||
assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}");
|
||||
}
|
||||
|
||||
// Color Dodge gives white for a white source, and Divide keeps a black backdrop black and turns any other white under a black source
|
||||
// Color Dodge, like Divide, keeps a black backdrop black under any source, even white, and turns any other white under a white source.
|
||||
// Divide also turns any other white under a black source.
|
||||
for backdrop in [0., 1e-7, -1e-7] {
|
||||
assert_eq!(Color::blend_color_dodge(backdrop, 1.), 0., "a backdrop of {backdrop}");
|
||||
}
|
||||
for source in [1., 1. - 1e-7, 1. + 2e-7] {
|
||||
assert_eq!(Color::blend_color_dodge(0., source), 1., "a source of {source}");
|
||||
assert_eq!(Color::blend_color_dodge(0.5, source), 1., "a source of {source}");
|
||||
}
|
||||
for backdrop in [0., 1e-7, -1e-7] {
|
||||
assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}");
|
||||
@@ -339,6 +371,65 @@ mod tests {
|
||||
assert!((blended.a() - 1.).abs() < 1e-5, "alpha was {}", blended.a());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn darker_and_lighter_color_pick_the_whole_color_by_luma() {
|
||||
// Blue's luma (0.11) is below the gray's (0.3), though its mean channel (a third) is above it
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
let gray = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 1.);
|
||||
|
||||
assert_eq!(apply_blend_mode(gray, blue, BlendMode::DarkerColor), blue);
|
||||
assert_eq!(apply_blend_mode(gray, blue, BlendMode::LighterColor), gray);
|
||||
assert_eq!(apply_blend_mode(blue, gray, BlendMode::DarkerColor), blue);
|
||||
|
||||
// Where the lumas tie, the backdrop stays, with the paint's alpha
|
||||
let tied = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 0.5);
|
||||
assert_eq!(apply_blend_mode(tied, gray, BlendMode::DarkerColor), gray.with_alpha(0.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_mix_ramps_steeper_with_strength_to_a_256th_wide_where_the_channels_sum_to_one() {
|
||||
let hard_mix = |backdrop: f32, source: f32, strength: f32| Color::blend_hard_mix_at_strength(backdrop, source, strength).clamp(0., 1.);
|
||||
|
||||
// At full strength, white past a sum of 1 and black short of it, even a level away
|
||||
assert_eq!(hard_mix(0.6, 0.5, 1.), 1.);
|
||||
assert_eq!(hard_mix(0.5, 0.49, 1.), 0.);
|
||||
assert_eq!(hard_mix(0.5, 0.51, 1.), 1.);
|
||||
|
||||
// For PSD interop, half a fill gives clamp(2b - 1 + s), and no strength leaves the backdrop as it is
|
||||
for (backdrop, source) in [(0.5, 0.3), (0.4, 0.4), (0.7, 0.1)] {
|
||||
let half = hard_mix(backdrop, source, 128. / 255.);
|
||||
assert!((half - (2. * backdrop - 1. + source).clamp(0., 1.)).abs() < 0.01, "{backdrop}, {source}: {half}");
|
||||
assert_eq!(hard_mix(backdrop, source, 0.), backdrop);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strength_moves_a_paint_toward_the_modes_neutral_color() {
|
||||
let backdrop = Color::from_rgbaf32_unchecked(0.4, 0.4, 0.4, 1.);
|
||||
let paint = Color::from_rgbaf32_unchecked(0.8, 0.8, 0.8, 1.);
|
||||
let at_half = |blend_mode: BlendMode| apply_blend_mode_at_strength(paint, backdrop, blend_mode, 0.5).r();
|
||||
|
||||
// Half the paint added, the paint halfway to white burned in, and the paint halfway to middle gray lighting
|
||||
assert!((at_half(BlendMode::LinearDodge) - 0.8).abs() < 1e-6, "{}", at_half(BlendMode::LinearDodge));
|
||||
assert!((at_half(BlendMode::LinearBurn) - 0.3).abs() < 1e-6, "{}", at_half(BlendMode::LinearBurn));
|
||||
assert!((at_half(BlendMode::LinearLight) - 0.7).abs() < 1e-6, "{}", at_half(BlendMode::LinearLight));
|
||||
|
||||
// The modes whose strength fades their blend take the paint as it is
|
||||
assert_eq!(at_half(BlendMode::Subtract), apply_blend_mode(paint, backdrop, BlendMode::Subtract).r());
|
||||
|
||||
// Layers read what lies beneath for the ten modes CSS lacks, of which five move their content toward neutral by their fill
|
||||
let reading: Vec<BlendMode> = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop).collect();
|
||||
assert_eq!(reading.len(), 10);
|
||||
assert_eq!(reading.iter().filter(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()).count(), 5);
|
||||
assert!(!BlendMode::Erase.reads_backdrop());
|
||||
|
||||
// Color Dodge and Color Burn do too below a full fill, which they otherwise blend natively at
|
||||
for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] {
|
||||
assert!(!blend_mode.reads_backdrop() && !blend_mode.layer_reads_backdrop(1.) && blend_mode.layer_reads_backdrop(0.5) && blend_mode.layer_reads_backdrop(0.));
|
||||
}
|
||||
assert!(!BlendMode::Multiply.layer_reads_backdrop(0.5) && BlendMode::LinearBurn.layer_reads_backdrop(1.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_over_weights_straight_colors_by_alpha() {
|
||||
let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5);
|
||||
|
||||
@@ -633,14 +633,20 @@ impl Color {
|
||||
c_b + c_s - 1.
|
||||
}
|
||||
|
||||
/// Whole-color "Darker Color" blend: keeps whichever color has the lower mean RGB, with `other`'s alpha.
|
||||
/// Whole-color "Darker Color" blend: keeps whichever color has the lower luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
|
||||
#[inline(always)]
|
||||
pub fn blend_darker_color(&self, other: Color) -> Color {
|
||||
let darker = if self.average_rgb_channels() <= other.average_rgb_channels() { *self } else { other };
|
||||
let darker = if self.blend_luma() <= other.blend_luma() { *self } else { other };
|
||||
|
||||
darker.with_alpha(other.alpha)
|
||||
}
|
||||
|
||||
/// The luma that Darker Color and Lighter Color compare, as the component blend modes measure it.
|
||||
#[inline(always)]
|
||||
fn blend_luma(&self) -> f32 {
|
||||
luma_rec_601_rounded(self.red, self.green, self.blue)
|
||||
}
|
||||
|
||||
/// Per-channel "Screen" blend.
|
||||
#[inline(always)]
|
||||
pub fn blend_screen(c_b: f32, c_s: f32) -> f32 {
|
||||
@@ -653,10 +659,16 @@ impl Color {
|
||||
c_s.max(c_b)
|
||||
}
|
||||
|
||||
/// Per-channel "Color Dodge" blend.
|
||||
/// Per-channel "Color Dodge" blend, where a black backdrop stays black and any other turns white under a white source, as the W3C formula orders them.
|
||||
#[inline(always)]
|
||||
pub fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
|
||||
if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE { 1. } else { (c_b / (1. - c_s)).min(1.) }
|
||||
if c_b.abs() <= BLEND_EDGE_TOLERANCE {
|
||||
0.
|
||||
} else if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE {
|
||||
1.
|
||||
} else {
|
||||
(c_b / (1. - c_s)).min(1.)
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-channel "Linear Dodge" (Add) blend.
|
||||
@@ -665,10 +677,10 @@ impl Color {
|
||||
c_b + c_s
|
||||
}
|
||||
|
||||
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher mean RGB, with `other`'s alpha.
|
||||
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
|
||||
#[inline(always)]
|
||||
pub fn blend_lighter_color(&self, other: Color) -> Color {
|
||||
let lighter = if self.average_rgb_channels() >= other.average_rgb_channels() { *self } else { other };
|
||||
let lighter = if self.blend_luma() >= other.blend_luma() { *self } else { other };
|
||||
|
||||
lighter.with_alpha(other.alpha)
|
||||
}
|
||||
@@ -724,9 +736,15 @@ impl Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-channel "Hard Mix" blend: thresholds Linear Light at 0.5.
|
||||
/// Per-channel "Hard Mix" blend: white where the channels sum to at least 1 and black below, along a ramp a 256th wide at full strength, for PSD interop.
|
||||
pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 {
|
||||
if Color::blend_linear_light(c_b, c_s) < 0.5 { 0. } else { 1. }
|
||||
Color::blend_hard_mix_at_strength(c_b, c_s, 1.)
|
||||
}
|
||||
|
||||
/// Per-channel "Hard Mix" blend of a paint at `strength` (from 0 to 1), unclamped, whose ramp steepens from none (the backdrop as it is) to a 256th wide at full strength, for PSD interop.
|
||||
pub fn blend_hard_mix_at_strength(c_b: f32, c_s: f32, strength: f32) -> f32 {
|
||||
let steepness = 255. * strength / 256.;
|
||||
(c_b - steepness * (1. - c_s)) / (1. - steepness)
|
||||
}
|
||||
|
||||
/// Per-channel "Difference" blend.
|
||||
|
||||
@@ -33,9 +33,9 @@ pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_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_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, 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;
|
||||
|
||||
@@ -59,8 +59,14 @@ 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 `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
|
||||
@@ -1714,7 +1720,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,12 +60,6 @@ pub struct FieldMetadata {
|
||||
pub progression: bool,
|
||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||
pub constant: bool,
|
||||
/// The X and Y labels of a Vec2 parameter's widget, from `#[labels("W", "H")]`.
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
/// Whether a number or Vec2 parameter's widget only takes integers, from `#[integer]`. Integer types always do.
|
||||
pub integer: bool,
|
||||
/// Whether the widget leaves room for the assist area beside it, which `#[blank_assist(false)]` turns off.
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -228,167 +222,6 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne
|
||||
|
||||
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// Every node defined as a subgraph by the `#[graph]` macro, in registration order.
|
||||
pub static GRAPH_METADATA: LazyLock<Mutex<Vec<GraphMetadata>>> = LazyLock::new(|| Mutex::new(Vec::new()));
|
||||
|
||||
/// A node defined as a subgraph by `#[graph]`, which the editor turns into a catalog definition alongside the proto nodes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphMetadata {
|
||||
/// The definition's identifier and display name.
|
||||
pub identifier: &'static str,
|
||||
pub category: &'static str,
|
||||
pub icon: Option<&'static str>,
|
||||
pub description: &'static str,
|
||||
/// The declaration version from `#[graph(version(N))]`, starting at 1.
|
||||
pub version: u32,
|
||||
/// Whether a new instance starts as a layer, from `#[graph(layer)]`.
|
||||
pub layer: bool,
|
||||
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
|
||||
/// Each one's `default_type` is the type it was declared with.
|
||||
pub imports: Vec<FieldMetadata>,
|
||||
pub exports: Vec<GraphExportMetadata>,
|
||||
/// The nodes inside the subgraph, where each node's position in this list is its ID.
|
||||
pub nodes: Vec<GraphNodeMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphExportMetadata {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub source: GraphInputSource,
|
||||
}
|
||||
|
||||
/// A node inside a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphNodeMetadata {
|
||||
pub implementation: GraphNodeImplementation,
|
||||
/// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition.
|
||||
pub inputs: Vec<(usize, GraphInputSource)>,
|
||||
/// The absolute position in grid units, from `.at(x, y)`.
|
||||
pub position: Option<(i32, i32)>,
|
||||
/// From `.layer()`.
|
||||
pub layer: bool,
|
||||
/// From `.named("…")`.
|
||||
pub display_name: Option<&'static str>,
|
||||
/// From `.hidden()`.
|
||||
pub hidden: bool,
|
||||
/// From `.locked()`.
|
||||
pub locked: bool,
|
||||
/// From `.pinned()`.
|
||||
pub pinned: bool,
|
||||
/// From `.call_argument::<T>()`.
|
||||
pub call_argument: Option<Type>,
|
||||
}
|
||||
|
||||
/// What a node inside a subgraph is an instance of.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GraphNodeImplementation {
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
/// Another node defined by `#[graph]`, named by its identifier.
|
||||
Graph(&'static str),
|
||||
}
|
||||
|
||||
impl From<ProtoNodeIdentifier> for GraphNodeImplementation {
|
||||
fn from(identifier: ProtoNodeIdentifier) -> Self {
|
||||
Self::ProtoNode(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for GraphNodeImplementation {
|
||||
fn from(identifier: &'static str) -> Self {
|
||||
Self::Graph(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// What feeds an input, or an export, of a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum GraphInputSource {
|
||||
/// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`].
|
||||
Node { node: usize, output: usize },
|
||||
/// One of the subgraph's imports, with the type its wire records.
|
||||
Import { index: usize, ty: Type },
|
||||
/// A value. Without an exposure, the input keeps the one from the node's own definition.
|
||||
Value { value: GraphValue, exposed: Option<bool> },
|
||||
/// A scope input, from `scope("…")`.
|
||||
Scope(&'static str),
|
||||
/// The document path of the node, from `reflect(NodePath)`.
|
||||
NodePath,
|
||||
/// The source ID of the node, from `reflect(SourceId)`.
|
||||
SourceId,
|
||||
}
|
||||
|
||||
/// A value written in a subgraph definition. The editor converts it to the type of the input it feeds.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GraphValue {
|
||||
/// A number written without a fractional part, which feeds an integer input as an integer and any other as a number.
|
||||
Integer(i64),
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
Vec2(glam::DVec2),
|
||||
Color(Color),
|
||||
}
|
||||
|
||||
impl GraphValue {
|
||||
pub fn vec2(x: f64, y: f64) -> Self {
|
||||
Self::Vec2(glam::DVec2::new(x, y))
|
||||
}
|
||||
|
||||
/// An opaque color from `rgb(0xRRGGBB)`.
|
||||
pub fn rgb(hex: u32) -> Self {
|
||||
let [_, red, green, blue] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, 255).into())
|
||||
}
|
||||
|
||||
/// A color with alpha from `rgba(0xRRGGBBAA)`.
|
||||
pub fn rgba(hex: u32) -> Self {
|
||||
let [red, green, blue, alpha] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, alpha).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for GraphValue {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::String(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for GraphValue {
|
||||
fn from(value: String) -> Self {
|
||||
Self::String(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> for GraphValue {
|
||||
fn from(value: bool) -> Self {
|
||||
Self::Bool(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f64> for GraphValue {
|
||||
fn from(value: f64) -> Self {
|
||||
Self::Number(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<i64> for GraphValue {
|
||||
fn from(value: i64) -> Self {
|
||||
Self::Integer(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<glam::DVec2> for GraphValue {
|
||||
fn from(value: glam::DVec2) -> Self {
|
||||
Self::Vec2(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Color> for GraphValue {
|
||||
fn from(value: Color) -> Self {
|
||||
Self::Color(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier.
|
||||
/// Snapshotted on first access, which must happen after startup registration of the node metadata completes.
|
||||
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
|
||||
|
||||
@@ -86,6 +86,8 @@ pub enum Adjustment {
|
||||
opacity: f64,
|
||||
},
|
||||
Solarize,
|
||||
/// Shows the alpha as a gray of the same gamma-encoded level, keeping the alpha, so a luminance mask of the gray shows as much as the alpha.
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl Adjustment {
|
||||
@@ -112,6 +114,17 @@ impl Adjustment {
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Solarize => EffectKind::Solarize,
|
||||
Self::AlphaToGray => EffectKind::AlphaToGray,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the adjustment might change a color's alpha, which only Make Opaque and the alpha records of Levels and Curves do.
|
||||
pub fn may_change_alpha(&self) -> bool {
|
||||
match self {
|
||||
Self::MakeOpaque { .. } => true,
|
||||
Self::Levels(settings) => !settings.alpha.is_identity(),
|
||||
Self::Curves(settings) => settings.alpha != TransferCurve::default(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,7 +154,7 @@ impl Adjustment {
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
||||
Self::Invert | Self::Solarize => {}
|
||||
Self::Invert | Self::Solarize | Self::AlphaToGray => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
@@ -300,7 +313,7 @@ impl Adjustment {
|
||||
pub enum DesaturateMethod {
|
||||
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
|
||||
///
|
||||
/// Accessibility contrast ratios and SVG luminance masks use this.
|
||||
/// Accessibility contrast ratios use this.
|
||||
#[default]
|
||||
#[label("Luminance (Rec. 709)")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
|
||||
@@ -486,6 +499,20 @@ fn grouped_key(group: &str, parameter: &str) -> String {
|
||||
}
|
||||
|
||||
impl LevelsRecord {
|
||||
/// The record leaving every value as it is, as its node's defaults do.
|
||||
pub const IDENTITY: Self = Self {
|
||||
shadows: 0.,
|
||||
midtones: 1.,
|
||||
highlights: 100.,
|
||||
output_minimums: 0.,
|
||||
output_maximums: 100.,
|
||||
};
|
||||
|
||||
/// Whether the record leaves every value as it is.
|
||||
pub fn is_identity(&self) -> bool {
|
||||
*self == Self::IDENTITY
|
||||
}
|
||||
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
||||
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
//! Blend If, shaped for PSD interop as its blending ranges: the content shows only where its own colors, and the colors of what lies beneath it, fall within a range of each channel's levels.
|
||||
//! The content's own range fades it like its fill does, leaving the shadows and glows cast from it as they are, and the range beneath fades everything the content draws like its opacity does.
|
||||
|
||||
use crate::effect_layers::is_pixel_filter;
|
||||
use crate::effects::EffectOperation;
|
||||
use crate::parameters::ParameterVisitor;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use dyn_any::DynAny;
|
||||
|
||||
/// For PSD interop, the gray channel weighs the levels of the gamma-encoded red, green, and blue channels by these percentages.
|
||||
pub const GRAY_PERCENTAGES: [usize; 3] = [30, 59, 11];
|
||||
|
||||
/// How many levels each renderer reads a channel at before weighing it, the 8 bits browsers filter with, so every renderer cuts off the same pixels.
|
||||
pub const CHANNEL_LEVELS: usize = 256;
|
||||
|
||||
/// How near a cutoff a channel may lie, as a fraction of its full scale, and still count as reaching it: a quarter of a level, so a cutoff given in percent lands on the level it names.
|
||||
const CUTOFF_TOLERANCE: f64 = 1. / 1024.;
|
||||
|
||||
/// Which channel of the colors a Blend If range reads.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum BlendIfChannel {
|
||||
/// The lightness of the colors, weighing red, green, and blue by 30%, 59%, and 11%.
|
||||
#[default]
|
||||
Gray,
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
}
|
||||
|
||||
/// A range of one channel's levels, in percent, which shows the content fully from its range start to its end and fades it out linearly to nothing at its falloff start and end.
|
||||
/// A falloff that meets its end of the range is a sharp cutoff, which shows the content at the level it lies on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
pub struct BlendRange {
|
||||
pub falloff_start: f64,
|
||||
pub range_start: f64,
|
||||
pub range_end: f64,
|
||||
pub falloff_end: f64,
|
||||
}
|
||||
|
||||
impl Default for BlendRange {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
falloff_start: 0.,
|
||||
range_start: 0.,
|
||||
range_end: 100.,
|
||||
falloff_end: 100.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BlendRange {
|
||||
/// How strongly the content shows where the channel is `value`, from 0 to 1.
|
||||
pub fn weight(&self, value: f64) -> f64 {
|
||||
let value = value * 100.;
|
||||
let tolerance = CUTOFF_TOLERANCE * 100.;
|
||||
|
||||
// Each side rises (or falls) across its falloff, with its ends taken in either order
|
||||
let side = |falloff: f64, range: f64, rising: bool| {
|
||||
let (low, high) = (falloff.min(range), falloff.max(range));
|
||||
match (high - low > tolerance, rising) {
|
||||
(true, true) => ((value - low) / (high - low)).clamp(0., 1.),
|
||||
(true, false) => ((high - value) / (high - low)).clamp(0., 1.),
|
||||
(false, true) => f64::from(value >= low - tolerance),
|
||||
(false, false) => f64::from(value <= high + tolerance),
|
||||
}
|
||||
};
|
||||
|
||||
side(self.falloff_start, self.range_start, true) * side(self.falloff_end, self.range_end, false)
|
||||
}
|
||||
|
||||
/// Whether the range shows every level fully, so it changes nothing.
|
||||
pub fn shows_everything(&self) -> bool {
|
||||
// Rising then falling, it's full everywhere once it's full at both ends
|
||||
self.weight(0.) >= 1. && self.weight(1.) >= 1.
|
||||
}
|
||||
|
||||
/// The weight at each of the [`CHANNEL_LEVELS`] levels, from black to white.
|
||||
pub fn level_weights(&self) -> Vec<f64> {
|
||||
(0..CHANNEL_LEVELS).map(|level| self.weight(level as f64 / (CHANNEL_LEVELS - 1) as f64)).collect()
|
||||
}
|
||||
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
let key = |parameter: &str| format!("{group}_{parameter}");
|
||||
visitor.parameter(&key("falloff_start"), &mut self.falloff_start, 0.);
|
||||
visitor.parameter(&key("range_start"), &mut self.range_start, 0.);
|
||||
visitor.parameter(&key("range_end"), &mut self.range_end, 100.);
|
||||
visitor.parameter(&key("falloff_end"), &mut self.falloff_end, 100.);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ranges each channel's levels must fall within for the content to show, which multiply.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelRanges {
|
||||
pub gray: BlendRange,
|
||||
pub red: BlendRange,
|
||||
pub green: BlendRange,
|
||||
pub blue: BlendRange,
|
||||
}
|
||||
|
||||
impl ChannelRanges {
|
||||
/// Each channel with its range, in the order the GPU takes them.
|
||||
pub fn channels(&self) -> [(BlendIfChannel, &BlendRange); 4] {
|
||||
[
|
||||
(BlendIfChannel::Gray, &self.gray),
|
||||
(BlendIfChannel::Red, &self.red),
|
||||
(BlendIfChannel::Green, &self.green),
|
||||
(BlendIfChannel::Blue, &self.blue),
|
||||
]
|
||||
}
|
||||
|
||||
/// The channels with ranges that hide some levels.
|
||||
pub fn limiting(&self) -> impl Iterator<Item = (BlendIfChannel, &BlendRange)> {
|
||||
self.channels().into_iter().filter(|(_, range)| !range.shows_everything())
|
||||
}
|
||||
|
||||
/// Whether every channel's range shows every level fully, so they change nothing.
|
||||
pub fn show_everything(&self) -> bool {
|
||||
self.limiting().next().is_none()
|
||||
}
|
||||
|
||||
/// How strongly the content shows for a straight gamma-encoded `color`, each channel (and the gray from them) read at its nearest level.
|
||||
pub fn weight(&self, color: [f64; 3]) -> f64 {
|
||||
self.channel_weights(color).into_iter().product()
|
||||
}
|
||||
|
||||
/// The weight each channel's range gives a straight gamma-encoded `color`, in the order of [`Self::channels`], which multiply to its [`Self::weight`].
|
||||
pub fn channel_weights(&self, color: [f64; 3]) -> [f64; 4] {
|
||||
let levels = color.map(channel_level);
|
||||
let value = |level: usize| level as f64 / (CHANNEL_LEVELS - 1) as f64;
|
||||
let [red, green, blue] = levels.map(value);
|
||||
|
||||
[self.gray.weight(value(gray_level(levels))), self.red.weight(red), self.green.weight(green), self.blue.weight(blue)]
|
||||
}
|
||||
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, side: &str) {
|
||||
self.gray.visit_parameters(visitor, side);
|
||||
self.red.visit_parameters(visitor, &format!("red_{side}"));
|
||||
self.green.visit_parameters(visitor, &format!("green_{side}"));
|
||||
self.blue.visit_parameters(visitor, &format!("blue_{side}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The level from 0 to 255 nearest a channel's `value` from 0 to 1, with halves rounding up as the browsers' 8-bit filters round them.
|
||||
pub fn channel_level(value: f64) -> usize {
|
||||
((value.clamp(0., 1.) * (CHANNEL_LEVELS - 1) as f64 + 0.5).floor() as usize).min(CHANNEL_LEVELS - 1)
|
||||
}
|
||||
|
||||
/// The gray level of red, green, and blue levels, worked out in whole numbers so a gray exactly between two levels rounds up in every renderer.
|
||||
pub fn gray_level(levels: [usize; 3]) -> usize {
|
||||
let weighed: usize = levels.iter().zip(GRAY_PERCENTAGES).map(|(level, percentage)| level * percentage).sum();
|
||||
(weighed + 50) / 100
|
||||
}
|
||||
|
||||
/// The ranges of Blend If's two sides: those of the content's own colors, which fade the content like its fill, and those of what lies beneath it, which fade all it draws like its opacity.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct BlendIfRanges {
|
||||
pub content: ChannelRanges,
|
||||
pub underlying: ChannelRanges,
|
||||
}
|
||||
|
||||
impl BlendIfRanges {
|
||||
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
self.content.visit_parameters(visitor, "content");
|
||||
self.underlying.visit_parameters(visitor, "underlying");
|
||||
}
|
||||
}
|
||||
|
||||
/// How strongly all the content draws shows over a backdrop pixel with the straight gamma-encoded `color` and `alpha`, by the `underlying` ranges.
|
||||
/// Where nothing lies beneath, nothing is hidden, so the weight eases to full as the backdrop turns transparent.
|
||||
pub fn underlying_weight(underlying: &ChannelRanges, color: [f64; 3], alpha: f64) -> f64 {
|
||||
1. - alpha.clamp(0., 1.) * (1. - underlying.weight(color))
|
||||
}
|
||||
|
||||
/// The Blend If rows that act just before the row at `index` among `rows`: once `index` is the first row (or follows a pixel filter, like a blur or adjustment), those from it up to the next pixel filter.
|
||||
/// So each Blend If reads and fades the content as the pixel filters before it leave it, ahead of the shadows and glows around it, which are knocked out by the content as it then shows.
|
||||
pub fn blend_ifs_acting_before(rows: &[EffectOperation], index: usize) -> Vec<&BlendIfRanges> {
|
||||
let follows_pixel_filter = index.checked_sub(1).is_none_or(|previous| processes_pixels(&rows[previous]));
|
||||
if !follows_pixel_filter {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
(rows[index..].iter())
|
||||
.take_while(|operation| !processes_pixels(operation))
|
||||
.filter_map(|operation| match operation {
|
||||
EffectOperation::BlendIf(ranges) => Some(ranges.as_ref()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a solid paint overlay at `index` among `rows` may mix into the content's own colors ahead of the other effects.
|
||||
/// Not where a Blend If reading those colors acts in the same stretch between pixel filters, since it reads them before the overlay paints.
|
||||
pub fn paint_overlay_folds(rows: &[EffectOperation], index: usize) -> bool {
|
||||
let start = rows[..index].iter().rposition(processes_pixels).map_or(0, |previous| previous + 1);
|
||||
let end = rows[index..].iter().position(processes_pixels).map_or(rows.len(), |next| index + next);
|
||||
!fades_content(&rows[start..end])
|
||||
}
|
||||
|
||||
/// Whether a Blend If among the `operations` fades the content by its own colors, as a fill varying across it does.
|
||||
pub fn fades_content(operations: &[EffectOperation]) -> bool {
|
||||
operations
|
||||
.iter()
|
||||
.any(|operation| matches!(operation, EffectOperation::BlendIf(ranges) if !ranges.content.show_everything()))
|
||||
}
|
||||
|
||||
/// Whether a row processes the pixels of everything before it, as a pixel filter (like a blur or adjustment) that changes something does, which ends a stretch of rows that Blend Ifs act at the start of.
|
||||
fn processes_pixels(operation: &EffectOperation) -> bool {
|
||||
is_pixel_filter(operation) && !operation.changes_nothing()
|
||||
}
|
||||
|
||||
/// The ranges beneath of each Blend If row among the `operations` that hides anything by what lies beneath, which multiply.
|
||||
pub fn underlying_ranges<'a>(operations: impl IntoIterator<Item = &'a EffectOperation>) -> Vec<ChannelRanges> {
|
||||
(operations.into_iter())
|
||||
.filter_map(|operation| match operation {
|
||||
EffectOperation::BlendIf(ranges) if !ranges.underlying.show_everything() => Some(ranges.underlying),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn range(falloff_start: f64, range_start: f64, range_end: f64, falloff_end: f64) -> BlendRange {
|
||||
BlendRange {
|
||||
falloff_start,
|
||||
range_start,
|
||||
range_end,
|
||||
falloff_end,
|
||||
}
|
||||
}
|
||||
|
||||
/// A level from 0 to 255 as a channel value.
|
||||
fn level(level: f64) -> f64 {
|
||||
level / 255.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_fade_linearly_across_their_falloffs() {
|
||||
let percent = |level: f64| level / 255. * 100.;
|
||||
let soft = range(percent(64.), percent(128.), percent(192.), percent(224.));
|
||||
|
||||
assert_eq!(soft.weight(level(32.)), 0.);
|
||||
assert!((soft.weight(level(96.)) - 0.5).abs() < 1e-12);
|
||||
assert_eq!(soft.weight(level(160.)), 1.);
|
||||
assert!((soft.weight(level(208.)) - 0.5).abs() < 1e-12);
|
||||
assert_eq!(soft.weight(level(240.)), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsplit_cutoffs_keep_the_level_they_lie_on() {
|
||||
// For PSD interop, black at 64 keeps 64 and white at 192 keeps 192, given in percent as they'd be imported
|
||||
let percent = |level: f64| level / 255. * 100.;
|
||||
let hard = range(percent(64.), percent(64.), percent(192.), percent(192.));
|
||||
|
||||
assert_eq!(hard.weight(level(63.)), 0.);
|
||||
assert_eq!(hard.weight(level(64.)), 1.);
|
||||
assert_eq!(hard.weight(level(192.)), 1.);
|
||||
assert_eq!(hard.weight(level(193.)), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_range_shows_everything() {
|
||||
assert!(BlendRange::default().shows_everything());
|
||||
assert!(ChannelRanges::default().show_everything());
|
||||
assert!(!range(0., 10., 100., 100.).shows_everything());
|
||||
assert!(!range(0., 0., 100., 99.).shows_everything());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channels_multiply_with_gray_weighing_the_color() {
|
||||
let ranges = ChannelRanges {
|
||||
gray: range(0., 50., 100., 100.),
|
||||
red: range(0., 0., 50., 100.),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// The gray of a light pink shows fully, but its red at full strength fades it to nothing
|
||||
assert_eq!(ranges.weight([1., 0.5, 0.5]), 0.);
|
||||
// A dark red's gray, read at its own level, lies partway up its falloff, while its red lies within its range
|
||||
let red = level(77.);
|
||||
let gray = gray_level([77, 0, 0]) as f64 / 255.;
|
||||
let expected = (gray * 100. / 50.) * ((100. - red * 100.) / 50.).min(1.);
|
||||
assert!((ranges.weight([red, 0., 0.]) - expected).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_beneath_hides_nothing() {
|
||||
let underlying = ChannelRanges {
|
||||
gray: range(50., 50., 100., 100.),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(underlying_weight(&underlying, [0.; 3], 0.), 1.);
|
||||
assert_eq!(underlying_weight(&underlying, [0.; 3], 1.), 0.);
|
||||
assert!((underlying_weight(&underlying, [0.; 3], 0.25) - 0.75).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_act_after_the_blurs_and_adjustments_before_them() {
|
||||
let blend_if = EffectOperation::BlendIf(Box::default());
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let shadow = EffectOperation::default_for(crate::EffectKind::DropShadow);
|
||||
let rows = [shadow.clone(), blend_if.clone(), blur, shadow, blend_if];
|
||||
|
||||
// The first acts ahead of the shadow before it, and the second just after the blur, ahead of the shadow between them
|
||||
let acting: Vec<usize> = (0..rows.len()).map(|index| blend_ifs_acting_before(&rows, index).len()).collect();
|
||||
assert_eq!(acting, [1, 0, 0, 1, 0]);
|
||||
|
||||
// A blur of no radius changes nothing, so it starts no stretch of its own
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let rows = [EffectOperation::default_for(crate::EffectKind::DropShadow), no_blur, EffectOperation::BlendIf(Box::default())];
|
||||
assert_eq!(blend_ifs_acting_before(&rows, 0).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grays_between_two_levels_round_up() {
|
||||
// Blue at 250 weighs 27.5 levels of gray, and 249 weighs 27.39
|
||||
assert_eq!(gray_level([0, 0, 250]), 28);
|
||||
assert_eq!(gray_level([0, 0, 249]), 27);
|
||||
assert_eq!(gray_level([5, 0, 0]), 2);
|
||||
assert_eq!(gray_level([255, 255, 255]), 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlays_keep_their_strength_where_a_blend_if_reads_the_content_beside_them() {
|
||||
let overlay = EffectOperation::Adjustment(crate::Adjustment::ColorOverlay {
|
||||
color: core_types::Color::RED,
|
||||
blend_mode: core_types::blending::BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 40.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
assert!(!paint_overlay_folds(&[overlay.clone(), blend_if.clone(), blur.clone()], 0));
|
||||
assert!(paint_overlay_folds(&[overlay.clone(), blur.clone(), blend_if.clone()], 0));
|
||||
assert!(paint_overlay_folds(&[blend_if, blur, overlay.clone()], 2));
|
||||
assert!(paint_overlay_folds(&[overlay, EffectOperation::BlendIf(Box::default())], 0));
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ pub enum PiecePlace {
|
||||
IntoContent { over: bool },
|
||||
/// The part of an interior piece blending with what shows through the content's fill, in a layer of its mode beneath the content's, or with `over`, over it.
|
||||
Through { over: bool },
|
||||
/// What lies beneath the content, filtered and cut to its silhouette, at the bottom of the content's own layer.
|
||||
Backdrop,
|
||||
}
|
||||
|
||||
/// One coverage of an effect that draws as a piece of its own, named like the map of it.
|
||||
@@ -63,20 +65,28 @@ pub struct EffectLayers {
|
||||
/// How many of the effects, from the first, are carried out within the content's image.
|
||||
pub flattened: usize,
|
||||
pub layers: Vec<EffectLayer>,
|
||||
/// The rows from the first mask after every other effect to the end, which fade each finished layer at each pixel like the item's opacity. Empty where those masks flatten what's before them instead.
|
||||
/// The rows from the first mask after every other effect to the end: masks, and Blend Ifs reading only what lies beneath, which fade each finished layer at each pixel like the item's opacity.
|
||||
/// Empty where those masks flatten what's before them instead.
|
||||
pub trailing_masks: Range<usize>,
|
||||
/// Whether a Blend If fades every layer by the colors of what lies beneath.
|
||||
pub fades_by_underlying: bool,
|
||||
}
|
||||
|
||||
impl EffectLayers {
|
||||
/// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask.
|
||||
/// Content in a mode CSS lacks is drawn normally, so it's planned that way.
|
||||
/// Content in a mode CSS lacks reads what lies beneath to blend by it (see [`BlendMode::reads_backdrop`]), but the alpha-only utility modes are planned as normal.
|
||||
pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal };
|
||||
let blend_mode = if blend_mode.to_svg_style_name().is_some() || blend_mode.reads_backdrop() {
|
||||
blend_mode
|
||||
} else {
|
||||
BlendMode::Normal
|
||||
};
|
||||
|
||||
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer
|
||||
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer.
|
||||
// A Blend If fading the content by its colors acts as a fill below full wherever it hides any.
|
||||
let shares_content = blend_mode == BlendMode::Normal;
|
||||
let blends_into_content = shares_content && fill >= 1.;
|
||||
let blends_into_content = shares_content && fill >= 1. && !crate::blend_if::fades_content(&operations);
|
||||
|
||||
// The masks after every other effect fade the layers rather than the content's image, so they flatten nothing before them
|
||||
let no_rows = operations.len()..operations.len();
|
||||
@@ -115,10 +125,16 @@ impl EffectLayers {
|
||||
.chain([(LayerPart::Content, blend_mode)])
|
||||
.collect();
|
||||
|
||||
// A shadow not knocked out in the content's layer, flattened or layered, would hide a part placed beneath that layer
|
||||
// A blurred backdrop, or a shadow not knocked out (flattened or layered), in the content's layer would hide a part placed beneath that layer
|
||||
let backdrop: Vec<LayerPart> = pieces_from(0, operations.len())
|
||||
.into_iter()
|
||||
.filter(|(piece, _)| piece.place == PiecePlace::Backdrop)
|
||||
.map(|(piece, _)| LayerPart::Piece(piece))
|
||||
.collect();
|
||||
let shows_through = |piece: &EffectPiece| piece.place == PiecePlace::Beneath && !piece.knocks_out;
|
||||
let mut content_run = parts.iter().rev().skip(1).take_while(|(_, mode)| *mode == BlendMode::Normal);
|
||||
let covered_beneath = content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
|
||||
let covered_beneath =
|
||||
!backdrop.is_empty() || content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
|
||||
|
||||
// Interior pieces of normal content blend within its share, in its layer. Below a full fill, a blended one splits off its part through the fill into a layer beneath
|
||||
// the content's, or over it when its mode isn't straight along what lies beneath or a shadow covers that, as every later piece then does to keep their order.
|
||||
@@ -166,8 +182,10 @@ impl EffectLayers {
|
||||
layers.splice(content_layer..content_layer, through);
|
||||
}
|
||||
|
||||
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes
|
||||
if blends_into_content && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
|
||||
let fades_by_underlying = !crate::blend_if::underlying_ranges(&operations).is_empty();
|
||||
|
||||
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes, unless it reads what lies beneath
|
||||
if blends_into_content && backdrop.is_empty() && !fades_by_underlying && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
|
||||
let content = EffectLayer {
|
||||
blend_mode: BlendMode::Normal,
|
||||
parts: vec![LayerPart::Content],
|
||||
@@ -176,10 +194,21 @@ impl EffectLayers {
|
||||
flattened: operations.len(),
|
||||
layers: vec![content],
|
||||
trailing_masks: no_rows,
|
||||
fades_by_underlying,
|
||||
};
|
||||
}
|
||||
|
||||
Self { flattened, layers, trailing_masks }
|
||||
// What lies beneath, filtered, goes at the bottom of the content's own layer, which fades and blends it with the content, even from a row flattened into the content
|
||||
if let Some(content_layer) = layers.iter_mut().find(|layer| layer.holds_content()) {
|
||||
content_layer.parts.splice(0..0, backdrop);
|
||||
}
|
||||
|
||||
Self {
|
||||
flattened,
|
||||
layers,
|
||||
trailing_masks,
|
||||
fades_by_underlying,
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`Self::plan`], for effects stamped in more than one space (see [`Effects::runs`]), as renderers draw them.
|
||||
@@ -201,6 +230,27 @@ impl EffectLayers {
|
||||
planned
|
||||
}
|
||||
|
||||
/// Whether a layered piece, a Blend If fading the layers, or a layer's blend mode reads what lies beneath the content.
|
||||
pub fn reads_backdrop(&self) -> bool {
|
||||
self.fades_by_underlying || self.reads_around_backdrop() || self.layers.iter().any(|layer| layer.blend_mode.reads_backdrop())
|
||||
}
|
||||
|
||||
/// Whether the content's layer reads what lies beneath it to blend at the content's `fill` (see [`BlendMode::layer_reads_backdrop`]).
|
||||
/// Color Dodge and Color Burn blend natively instead over a piece beneath the content it doesn't knock out, which what lies beneath the item leaves out.
|
||||
pub fn content_reads_backdrop(&self, fill: f32) -> bool {
|
||||
let Some(content_layer) = self.content_layer() else { return false };
|
||||
let blend_mode = self.layers[content_layer].blend_mode;
|
||||
|
||||
let shown_beneath = |part: &LayerPart| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Beneath && !piece.knocks_out);
|
||||
let pieces_show_beneath = self.layers[..content_layer].iter().flat_map(|layer| &layer.parts).any(shown_beneath);
|
||||
blend_mode.reads_backdrop() || (blend_mode.layer_reads_backdrop(fill) && !pieces_show_beneath)
|
||||
}
|
||||
|
||||
/// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself.
|
||||
pub fn reads_around_backdrop(&self) -> bool {
|
||||
(self.layers.iter().flat_map(|layer| &layer.parts)).any(|part| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Backdrop))
|
||||
}
|
||||
|
||||
/// The index of the layer holding the content.
|
||||
pub fn content_layer(&self) -> Option<usize> {
|
||||
self.layers.iter().position(EffectLayer::holds_content)
|
||||
@@ -263,11 +313,30 @@ impl EffectLayers {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any of the effects reads what lies beneath the content, like a background blur, or may, like a shadow in a mode CSS lacks.
|
||||
pub fn effects_read_backdrop(effects: &Effects) -> bool {
|
||||
effects.operations().any(|operation| match &operation {
|
||||
EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(),
|
||||
EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(),
|
||||
_ => {
|
||||
!operation.changes_nothing()
|
||||
&& pieces(0, &operation)
|
||||
.iter()
|
||||
.any(|(piece, blend_mode)| piece.place == PiecePlace::Beneath && blend_mode.reads_backdrop())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
|
||||
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer,
|
||||
/// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
|
||||
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them. A piece in a mode CSS lacks reads what lies beneath the item to blend, so only one beneath the content
|
||||
/// can, though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
|
||||
fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool {
|
||||
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| blend_mode.to_svg_style_name().is_some() || (blend_into_content && piece.place == PiecePlace::Within);
|
||||
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| match piece.place {
|
||||
_ if blend_mode.to_svg_style_name().is_some() => true,
|
||||
PiecePlace::Beneath => blend_mode.reads_backdrop(),
|
||||
PiecePlace::Within => blend_into_content,
|
||||
_ => false,
|
||||
};
|
||||
!is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in)
|
||||
}
|
||||
|
||||
@@ -310,31 +379,39 @@ fn merged_into_content(operations: &[EffectOperation]) -> usize {
|
||||
.map_or(0, |index| index + 1)
|
||||
}
|
||||
|
||||
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it.
|
||||
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it, leaving out each Blend If that reads only what lies beneath.
|
||||
/// The other pieces are cast from or laid over the content, so for PSD interop they don't shape a clip. Borrowed if nothing is left out.
|
||||
pub fn content_image_effects(effects: &Effects) -> Cow<'_, Effects> {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
let trailing_masks = trailing_masks(&operations);
|
||||
let merged = merged_into_content(&operations[..trailing_masks.start]);
|
||||
if merged == trailing_masks.start {
|
||||
|
||||
// A Blend If reading only what lies beneath fades the finished layers wherever it sits, so it shapes no clip (and it's the only kind the trailing masks can hold)
|
||||
let kept: Vec<usize> = (0..merged).chain(trailing_masks).filter(|&index| !reads_only_beneath(&operations[index])).collect();
|
||||
if kept.len() == operations.len() {
|
||||
return Cow::Borrowed(effects);
|
||||
}
|
||||
|
||||
Cow::Owned(Effects((0..merged).chain(trailing_masks).filter_map(|index| effects.0.clone_item(index)).collect()))
|
||||
Cow::Owned(Effects(kept.into_iter().filter_map(|index| effects.0.clone_item(index)).collect()))
|
||||
}
|
||||
|
||||
/// The rows from the first mask after every other effect that changes something to the end, or none without such a mask or an effect before it.
|
||||
/// A Blend If reading only what lies beneath is passed over, since it fades the finished layers as the masks do, but one reading the content's colors counts as another effect.
|
||||
fn trailing_masks(operations: &[EffectOperation]) -> Range<usize> {
|
||||
let no_rows = operations.len()..operations.len();
|
||||
let is_mask = |operation: &EffectOperation| matches!(operation, EffectOperation::Mask { .. });
|
||||
let is_other = |operation: &EffectOperation| !operation.changes_nothing() && !is_mask(operation) && !reads_only_beneath(operation);
|
||||
|
||||
let Some(last_other) = operations.iter().rposition(|operation| !operation.changes_nothing() && !is_mask(operation)) else {
|
||||
return no_rows;
|
||||
};
|
||||
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing());
|
||||
let Some(last_other) = operations.iter().rposition(is_other) else { return no_rows };
|
||||
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing() && is_mask(operation));
|
||||
first_mask.map_or(no_rows, |offset| last_other + 1 + offset..operations.len())
|
||||
}
|
||||
|
||||
/// Whether the effect is a Blend If without ranges of the content's own colors, so it reads only what lies beneath (or changes nothing).
|
||||
fn reads_only_beneath(operation: &EffectOperation) -> bool {
|
||||
matches!(operation, EffectOperation::BlendIf(ranges) if ranges.content.show_everything())
|
||||
}
|
||||
|
||||
/// The pieces the effect at `index` draws, each with the mode it blends by, leaving out those painting no color.
|
||||
fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendMode)> {
|
||||
// Only a drop shadow can show through the content
|
||||
@@ -392,6 +469,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
inside.into_iter().chain(outside).flatten().collect()
|
||||
}
|
||||
EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)],
|
||||
EffectOperation::BackgroundBlur { .. } => vec![piece(0, Backdrop, None, BlendMode::Normal)],
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)],
|
||||
EffectOperation::Blur { .. }
|
||||
| EffectOperation::MotionBlur { .. }
|
||||
@@ -412,10 +490,12 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Median { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
| EffectOperation::BlendIf(_)
|
||||
| EffectOperation::Adjustment(_) => Vec::new(),
|
||||
};
|
||||
pieces.into_iter().flatten().collect()
|
||||
@@ -508,9 +588,11 @@ mod tests {
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]);
|
||||
|
||||
// A mode CSS lacks is drawn normally, so it's planned that way, and an interior piece blending within the content's layer may take one too
|
||||
// Content in a mode CSS lacks reads what lies beneath to blend by it, and an interior piece blending within the content's layer may take one too
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::LinearBurn, BlendMode::Screen, BlendMode::Normal]);
|
||||
assert!(layers.reads_backdrop() && !layers.reads_around_backdrop());
|
||||
assert!(!EffectLayers::plan(&effects, BlendMode::Overlay, 1., true).reads_backdrop());
|
||||
let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]);
|
||||
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0);
|
||||
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2);
|
||||
@@ -568,6 +650,11 @@ mod tests {
|
||||
fn interior_pieces_go_over_the_content_where_its_layer_covers_what_lies_beneath_it() {
|
||||
let red = RED.with_alpha(0.75);
|
||||
let through_over = PiecePlace::Through { over: true };
|
||||
let background_blur = EffectOperation::BackgroundBlur {
|
||||
radius: 4.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
let with_knockout = |knocks_out: bool| {
|
||||
let mut shadow = drop_shadow(Color::BLACK.with_alpha(0.75), BlendMode::Multiply);
|
||||
@@ -577,23 +664,22 @@ mod tests {
|
||||
shadow
|
||||
};
|
||||
|
||||
// A shadow not knocked out beneath the content in its layer would hide even a straight piece's part beneath that layer
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(false), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen]);
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
|
||||
// A blurred backdrop, or a shadow not knocked out, beneath the content in its layer would hide even a straight piece's part beneath that layer
|
||||
for beneath in [background_blur, with_knockout(false)] {
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([beneath.clone(), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen], "{beneath:?}");
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))], "{beneath:?}");
|
||||
}
|
||||
|
||||
// A knocked-out shadow doesn't cover it there
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]);
|
||||
|
||||
// One flattened for a mode CSS lacks covers it too
|
||||
let mut flattened_shadow = with_knockout(false);
|
||||
if let EffectOperation::DropShadow { blend_mode, .. } = &mut flattened_shadow {
|
||||
*blend_mode = BlendMode::LinearBurn;
|
||||
}
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([flattened_shadow, inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 1);
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
|
||||
// One flattened before an interior piece in a mode CSS lacks covers it too
|
||||
let flattening = [with_knockout(false), inner_shadow(red, BlendMode::LinearBurn), inner_shadow(red, BlendMode::Screen)];
|
||||
let layers = EffectLayers::plan(&Effects::from_operations(flattening), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(parts(&layers)[1], [Some((2, 0, through_over))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -700,9 +786,14 @@ mod tests {
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2));
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5));
|
||||
let unmerged = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply), mask()]);
|
||||
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 1., true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (3, 3..3));
|
||||
let unmerged = Effects::from_operations([
|
||||
drop_shadow(RED, BlendMode::Multiply),
|
||||
inner_shadow(RED, BlendMode::LinearBurn),
|
||||
drop_shadow(RED, BlendMode::Multiply),
|
||||
mask(),
|
||||
]);
|
||||
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (4, 4..4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -719,19 +810,23 @@ mod tests {
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
|
||||
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), drop_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
|
||||
// An interior piece in a mode CSS lacks, which would read the content beneath it, flattens what's before it, where one beneath the content takes a layer of its own
|
||||
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), inner_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!((layers.flattened, modes(&layers)), (0, vec![BlendMode::LinearBurn, BlendMode::Normal]));
|
||||
assert!(layers.reads_backdrop());
|
||||
|
||||
// A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), inner_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 3);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal]);
|
||||
|
||||
// Clipped content flattens everything
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, false);
|
||||
assert_eq!(layers.flattened, 3);
|
||||
assert_eq!(parts(&layers), [[None]]);
|
||||
}
|
||||
|
||||
@@ -758,6 +853,95 @@ mod tests {
|
||||
assert_eq!(kinds(filtered), [EffectKind::Mask, EffectKind::InnerShadow, EffectKind::Blur, EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_background_blur_lies_at_the_bottom_of_the_contents_layer() {
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
let background_blur = EffectOperation::BackgroundBlur {
|
||||
radius: 4.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
// Even beside a blended shadow, and flattened by a later blur, it fades and blends with the content
|
||||
let effects = Effects::from_operations([drop_shadow(blue, BlendMode::Multiply), background_blur, blur]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Screen, 1., true);
|
||||
assert!(layers.reads_backdrop());
|
||||
let content_layer = layers.content_layer().unwrap();
|
||||
assert_eq!(layers.layers[content_layer].blend_mode, BlendMode::Screen);
|
||||
assert_eq!(parts(&layers)[content_layer], [Some((1, 0, PiecePlace::Backdrop)), None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_draw_no_pieces_and_read_the_backdrop_only_by_their_ranges_beneath() {
|
||||
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 50.;
|
||||
let content_only = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
|
||||
let layers = EffectLayers::plan(&content_only, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.layers.len(), 1);
|
||||
assert!(!layers.reads_backdrop() && !effects_read_backdrop(&content_only));
|
||||
|
||||
ranges.underlying.blue.falloff_end = 50.;
|
||||
let beneath = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
|
||||
let layers = EffectLayers::plan(&beneath, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.layers[0].parts, [LayerPart::Content]);
|
||||
assert!(layers.reads_backdrop() && effects_read_backdrop(&beneath));
|
||||
|
||||
// Fading the content by its colors, it splits a blended interior piece as a partial fill does, even at a full fill
|
||||
let screen = Effects::from_operations([inner_shadow(RED.with_alpha(0.75), BlendMode::Screen), EffectOperation::BlendIf(Box::new(ranges))]);
|
||||
let layers = EffectLayers::plan(&screen, BlendMode::Normal, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Screen, BlendMode::Normal]);
|
||||
assert!(layers.reads_through_share());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_after_trailing_masks_leave_them_trailing() {
|
||||
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||
ranges.underlying.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||
let kinds = |effects: &Effects| -> Vec<EffectKind> { content_image_effects(effects).operations().map(|operation| operation.kind()).collect() };
|
||||
|
||||
// After the mask as before it, the shadow keeps its layer and mode while the mask fades each layer, and a clipping base takes the mask alone
|
||||
for operations in [
|
||||
[drop_shadow(RED, BlendMode::Multiply), mask(), blend_if.clone()],
|
||||
[drop_shadow(RED, BlendMode::Multiply), blend_if.clone(), mask()],
|
||||
] {
|
||||
let effects = Effects::from_operations(operations);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 0, "{:?}", effects.operations().map(|operation| operation.kind()).collect::<Vec<_>>());
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
assert!(layers.fades_layers());
|
||||
assert_eq!(kinds(&effects), [EffectKind::Mask]);
|
||||
}
|
||||
|
||||
// With nothing else to trail, a clipping base still takes the mask alone in either order
|
||||
assert_eq!(kinds(&Effects::from_operations([blend_if.clone(), mask()])), [EffectKind::Mask]);
|
||||
assert_eq!(kinds(&Effects::from_operations([mask(), blend_if])), [EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_reading_the_content_after_masks_keep_them_from_trailing() {
|
||||
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||
let kinds = |operations: Vec<EffectOperation>| -> Vec<EffectKind> { content_image_effects(&Effects::from_operations(operations)).operations().map(|operation| operation.kind()).collect() };
|
||||
|
||||
// The mask merges the shadow flattened before it into the content's image, which the Blend If then reads
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), mask(), blend_if.clone()]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert!(!layers.fades_layers());
|
||||
|
||||
// A clipping base takes the mask alone, with the Blend If before it or after it
|
||||
assert_eq!(kinds(vec![blend_if.clone(), mask()]), [EffectKind::Mask]);
|
||||
assert_eq!(kinds(vec![mask(), blend_if]), [EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knocked_out_pieces_hide_behind_however_the_content_covers_them() {
|
||||
let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use crate::blend_if::BlendIfRanges;
|
||||
use crate::filters::{Convolution, NoiseDistribution};
|
||||
use crate::masks::{MaskMode, mask_feather_sigma};
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
|
||||
@@ -14,7 +15,7 @@ use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, List};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, ItemAttributeValues, List};
|
||||
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
@@ -59,12 +60,14 @@ pub enum EffectKind {
|
||||
FindEdges,
|
||||
/// Spreads each pixel's darkest or lightest neighboring colors.
|
||||
MinimumMaximum,
|
||||
/// Gives each pixel the middle value of each channel among those around it, removing specks while keeping edges.
|
||||
Median,
|
||||
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
||||
Sharpen,
|
||||
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
||||
HighPass,
|
||||
/// Scatters random offsets across the colors, fixed in place on the content.
|
||||
AddNoise,
|
||||
Speckle,
|
||||
/// Shows a random scattering of the content fully opaque and hides the rest, more where it's more opaque.
|
||||
Dissolve,
|
||||
/// Smears the content along a line, as if it moved while being captured.
|
||||
@@ -91,6 +94,10 @@ pub enum EffectKind {
|
||||
Pixelate,
|
||||
/// Prints each color channel of the content as dots on its own turned screen, as a press prints ink.
|
||||
ColorHalftone,
|
||||
/// Blurs what lies beneath the content within its silhouette, as if seen through frosted glass.
|
||||
BackgroundBlur,
|
||||
/// Shows the content only where its own colors, and those of what lies beneath it, fall within ranges of their channels.
|
||||
BlendIf,
|
||||
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
@@ -112,6 +119,8 @@ pub enum EffectKind {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
/// Shows the content's alpha as a gray, as 'Into Channels' does for its alpha output.
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
@@ -132,9 +141,10 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::Emboss => "Emboss",
|
||||
Self::FindEdges => "Find Edges",
|
||||
Self::MinimumMaximum => "Minimum/Maximum",
|
||||
Self::Median => "Median",
|
||||
Self::Sharpen => "Sharpen",
|
||||
Self::HighPass => "High Pass",
|
||||
Self::AddNoise => "Add Noise",
|
||||
Self::Speckle => "Speckle",
|
||||
Self::Dissolve => "Dissolve",
|
||||
Self::MotionBlur => "Motion Blur",
|
||||
Self::RadialBlur => "Radial Blur",
|
||||
@@ -148,6 +158,8 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::Displace => "Displace",
|
||||
Self::Pixelate => "Pixelate",
|
||||
Self::ColorHalftone => "Color Halftone",
|
||||
Self::BackgroundBlur => "Background Blur",
|
||||
Self::BlendIf => "Blend If",
|
||||
Self::Desaturate => "Desaturate",
|
||||
Self::GammaCorrection => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
@@ -168,6 +180,7 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
Self::Solarize => "Solarize",
|
||||
Self::AlphaToGray => "Alpha to Gray",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -211,6 +224,9 @@ pub enum MinimumMaximumMode {
|
||||
Maximum,
|
||||
}
|
||||
|
||||
/// The most pixels a median's square reaches out from its center on its grid, whose cost grows with the square's area. Past it, the grid coarsens instead.
|
||||
pub const MAX_MEDIAN_GRID_RADIUS: f64 = 16.;
|
||||
|
||||
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct EffectCapture {
|
||||
@@ -447,12 +463,23 @@ impl Effects {
|
||||
self.operations().all(|operation| operation.changes_nothing())
|
||||
}
|
||||
|
||||
/// Whether the effects might change the content's alpha, as any but an adjustment keeping it (see [`Adjustment::may_change_alpha`]) can unless it changes nothing.
|
||||
pub fn may_change_alpha(&self) -> bool {
|
||||
self.operations().any(|operation| {
|
||||
!operation.changes_nothing()
|
||||
&& match &operation {
|
||||
EffectOperation::Adjustment(adjustment) => adjustment.may_change_alpha(),
|
||||
_ => true,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The effects of the given range of rows decoded into operations, in order.
|
||||
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
|
||||
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint, in the effect space of a run of them.
|
||||
/// How far past the content the effects together can paint, or a background blur among them reads what lies beneath, in the effect space of a run of them.
|
||||
/// It leaves out what [`Effects::reach_around`] adds from the content's bounds and what it paints past its frame, for the effects relative to its extent.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.painted_reach()).sum()
|
||||
@@ -468,17 +495,30 @@ impl Effects {
|
||||
self.operations().map(|operation| operation.required_reach()).sum()
|
||||
}
|
||||
|
||||
/// How many pixels per unit of their effect space a run of these effects renders at, at most, if any of them works on the content's own grid (see [`EffectOperation::works_on_content_grid`]).
|
||||
/// It's one, except that a median reaching past [`MAX_MEDIAN_GRID_RADIUS`] whole units coarsens the grid to bound its cost.
|
||||
pub fn content_grid_resolution(&self) -> Option<f64> {
|
||||
let grid_resolution = |operation: EffectOperation| match operation {
|
||||
EffectOperation::Median { radius } => (MAX_MEDIAN_GRID_RADIUS / radius.floor()).min(1.),
|
||||
_ => 1.,
|
||||
};
|
||||
self.operations().filter(EffectOperation::works_on_content_grid).map(grid_resolution).reduce(f64::min)
|
||||
}
|
||||
|
||||
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
||||
/// A transform applied between two effects starts a new run, which renders around the result of those before it.
|
||||
/// A transform applied between two effects, or an effect on the content's own grid (which runs alone at its grid's resolution), starts a new run around the result of those before it.
|
||||
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
||||
pub fn runs(&self) -> Vec<(DAffine2, Range<usize>)> {
|
||||
let mut runs: Vec<(DAffine2, Range<usize>)> = Vec::new();
|
||||
let mut run_changes_something = false;
|
||||
let (mut run_changes_something, mut run_on_content_grid) = (false, false);
|
||||
for (index, effect) in self.effects().enumerate() {
|
||||
let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let changes_something = !effect.operation().changes_nothing();
|
||||
let operation = effect.operation();
|
||||
let (changes_something, on_content_grid) = (!operation.changes_nothing(), operation.works_on_content_grid());
|
||||
|
||||
let shares_grid = !(on_content_grid && run_changes_something) && !(run_on_content_grid && changes_something);
|
||||
if let Some((transform, rows)) = runs.last_mut()
|
||||
&& shares_grid
|
||||
&& (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2))
|
||||
{
|
||||
if changes_something && !run_changes_something {
|
||||
@@ -486,9 +526,10 @@ impl Effects {
|
||||
}
|
||||
rows.end = index + 1;
|
||||
run_changes_something |= changes_something;
|
||||
run_on_content_grid |= on_content_grid;
|
||||
} else {
|
||||
runs.push((stamped_transform, index..index + 1));
|
||||
run_changes_something = changes_something;
|
||||
(run_changes_something, run_on_content_grid) = (changes_something, on_content_grid);
|
||||
}
|
||||
}
|
||||
runs
|
||||
@@ -828,8 +869,14 @@ pub fn contour_gradient_position(distance: f32, start: f32, span: f32) -> f32 {
|
||||
/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point.
|
||||
/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect.
|
||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||
let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS)
|
||||
stamp_effect_on(item.attributes_mut(), effect);
|
||||
}
|
||||
|
||||
/// Like [`stamp_effect`], given the item's attributes.
|
||||
pub fn stamp_effect_on(attributes: &mut ItemAttributeValues, effect: Effect) {
|
||||
let transform = stamped_transform(attributes.get::<DAffine2>(ATTR_TRANSFORM).copied().unwrap_or_default());
|
||||
attributes
|
||||
.get_or_insert_default_mut::<Effects>(ATTR_EFFECTS)
|
||||
.0
|
||||
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
||||
}
|
||||
@@ -1079,6 +1126,11 @@ pub enum EffectOperation {
|
||||
radius: f64,
|
||||
mode: MinimumMaximumMode,
|
||||
},
|
||||
/// Carried out on the content's own grid of pixels (see [`Self::works_on_content_grid`]), then resampled to the view.
|
||||
Median {
|
||||
/// How many pixels the square neighborhood reaches out from its center, of which the whole pixels count.
|
||||
radius: f64,
|
||||
},
|
||||
Sharpen {
|
||||
/// Percent.
|
||||
amount: f64,
|
||||
@@ -1092,7 +1144,7 @@ pub enum EffectOperation {
|
||||
HighPass {
|
||||
radius: f64,
|
||||
},
|
||||
AddNoise {
|
||||
Speckle {
|
||||
/// Percent of full brightness.
|
||||
amount: f64,
|
||||
distribution: NoiseDistribution,
|
||||
@@ -1228,6 +1280,17 @@ pub enum EffectOperation {
|
||||
/// Percent of the spacing between dots that each screen's dots lie past the `offset` along both of its axes.
|
||||
phase: f64,
|
||||
},
|
||||
/// Blurs the backdrop beneath the content within the content's silhouette, beneath the content and its effects.
|
||||
BackgroundBlur {
|
||||
/// The standard deviation of the Gaussian, or the half width of the box.
|
||||
radius: f64,
|
||||
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
|
||||
box_blur: bool,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
/// Fades the content by how its own colors fall within ranges, as its fill does, and everything it draws by how the colors beneath fall within others, as its opacity does.
|
||||
BlendIf(Box<BlendIfRanges>),
|
||||
Adjustment(Adjustment),
|
||||
}
|
||||
|
||||
@@ -1269,9 +1332,10 @@ impl EffectOperation {
|
||||
Self::Emboss { .. } => EffectKind::Emboss,
|
||||
Self::FindEdges => EffectKind::FindEdges,
|
||||
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
||||
Self::Median { .. } => EffectKind::Median,
|
||||
Self::Sharpen { .. } => EffectKind::Sharpen,
|
||||
Self::HighPass { .. } => EffectKind::HighPass,
|
||||
Self::AddNoise { .. } => EffectKind::AddNoise,
|
||||
Self::Speckle { .. } => EffectKind::Speckle,
|
||||
Self::Dissolve { .. } => EffectKind::Dissolve,
|
||||
Self::MotionBlur { .. } => EffectKind::MotionBlur,
|
||||
Self::RadialBlur { .. } => EffectKind::RadialBlur,
|
||||
@@ -1285,6 +1349,8 @@ impl EffectOperation {
|
||||
Self::Displace { .. } => EffectKind::Displace,
|
||||
Self::Pixelate { .. } => EffectKind::Pixelate,
|
||||
Self::ColorHalftone { .. } => EffectKind::ColorHalftone,
|
||||
Self::BackgroundBlur { .. } => EffectKind::BackgroundBlur,
|
||||
Self::BlendIf(_) => EffectKind::BlendIf,
|
||||
Self::Adjustment(adjustment) => adjustment.kind(),
|
||||
}
|
||||
}
|
||||
@@ -1315,7 +1381,7 @@ impl EffectOperation {
|
||||
/// Whether this operation leaves the content as it is, like a blur of no radius or a shadow of no opacity.
|
||||
pub fn changes_nothing(&self) -> bool {
|
||||
match self {
|
||||
Self::Blur { radius, .. } => *radius <= 0.,
|
||||
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => *radius <= 0.,
|
||||
Self::DropShadow { color, .. } | Self::InnerShadow { color, .. } | Self::Satin { color, .. } => color.a() <= 0.,
|
||||
Self::OuterGlow { color, noise, .. } | Self::InnerGlow { color, noise, .. } => GlowFill::of(color).is_none_or(|fill| fill.is_invisible(*noise)),
|
||||
Self::Outline { paint, weight, contour_gradient, .. } => *weight <= 0. || OutlineFill::of(paint, *contour_gradient).is_none_or(|fill| fill.is_invisible()),
|
||||
@@ -1363,10 +1429,13 @@ impl EffectOperation {
|
||||
Self::Feather { distance } => *distance <= 0.,
|
||||
Self::ConvolutionKernel { .. } => self.convolution().is_none(),
|
||||
Self::Emboss { .. } | Self::FindEdges | Self::HighPass { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
|
||||
Self::AddNoise { amount, .. } => *amount <= 0.,
|
||||
Self::Speckle { amount, .. } => *amount <= 0.,
|
||||
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
||||
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
||||
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
||||
// Only whole pixels count, so one of less than a pixel reads the pixel alone
|
||||
Self::Median { radius } => *radius < 1.,
|
||||
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1375,6 +1444,16 @@ impl EffectOperation {
|
||||
matches!(self, Self::Blur { radius_mask, .. } if !radius_mask.draws_nothing())
|
||||
}
|
||||
|
||||
/// Whether this operation paints nothing past the content, whatever it reads there, like an inner shadow finding the edges it casts from.
|
||||
pub fn paints_only_within_content(&self) -> bool {
|
||||
match self {
|
||||
Self::InnerShadow { .. } | Self::InnerGlow { .. } | Self::Satin { .. } | Self::Mask { .. } | Self::Feather { .. } | Self::BackgroundBlur { .. } => true,
|
||||
Self::Outline { align, .. } => *align == StrokeAlign::Inside,
|
||||
Self::BevelAndEmboss { style, .. } => *style == BevelStyle::InnerBevel,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this operation reads the pixels around each one of the image the effects before it leave, like a blur or a warp, rather than casting from the content's shape or changing each pixel alone.
|
||||
pub fn reads_pixels_around(&self) -> bool {
|
||||
match self {
|
||||
@@ -1382,8 +1461,8 @@ impl EffectOperation {
|
||||
Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => {
|
||||
true
|
||||
}
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||
// Cast from the content's shape, reading a mask's own image or a feather's map, or changing each pixel alone
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Median { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
|
||||
Self::DropShadow { .. }
|
||||
| Self::InnerShadow { .. }
|
||||
| Self::OuterGlow { .. }
|
||||
@@ -1392,10 +1471,16 @@ impl EffectOperation {
|
||||
| Self::Outline { .. }
|
||||
| Self::BevelAndEmboss { .. }
|
||||
| Self::Feather { .. } => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::Speckle { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this operation is carried out on the content's own grid of pixels, one to each unit of its effect space, and the result resampled to the view, since it doesn't commute with resampling.
|
||||
/// So it looks the same at every zoom, and on an image at its own size when stamped, it reads the image's pixels.
|
||||
pub fn works_on_content_grid(&self) -> bool {
|
||||
matches!(self, Self::Median { .. }) && !self.changes_nothing()
|
||||
}
|
||||
|
||||
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
||||
pub fn painted_reach(&self) -> f64 {
|
||||
let keeps_coverage = matches!(
|
||||
@@ -1409,6 +1494,8 @@ impl EffectOperation {
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
..
|
||||
}
|
||||
// Its coverage is the window's middle one, which past the content's bounds comes from a window at least half beyond them
|
||||
| Self::Median { .. }
|
||||
| Self::Sharpen { .. }
|
||||
| Self::HighPass { .. }
|
||||
);
|
||||
@@ -1429,8 +1516,9 @@ impl EffectOperation {
|
||||
pub fn reach(&self) -> f64 {
|
||||
match self {
|
||||
// A box reaches its half width, and the pixel past it for a fractional one, while a Gaussian fades out over three standard deviations
|
||||
Self::Blur { radius, box_blur: true, .. } => radius.max(0.) + 1.,
|
||||
Self::Blur { radius, .. } => 3. * radius.max(0.),
|
||||
Self::Blur { radius, box_blur: true, .. } | Self::BackgroundBlur { radius, box_blur: true, .. } => radius.max(0.) + 1.,
|
||||
// A background blur reads as far past the content as its Gaussian reaches
|
||||
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => 3. * radius.max(0.),
|
||||
// An inner shadow paints within the content but reads this far out to find the edges it casts from.
|
||||
// Shadows and glows end within their size, past which a precise glow fades over one more unit.
|
||||
Self::DropShadow { distance, size, .. } | Self::InnerShadow { distance, size, .. } => distance.abs() + size.max(0.) + 1.,
|
||||
@@ -1450,6 +1538,7 @@ impl EffectOperation {
|
||||
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
||||
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
||||
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
||||
Self::Median { radius } => radius.max(0.).floor() + 1.,
|
||||
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
||||
Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3.,
|
||||
// They reach as far as `Effects::reach_around` measures from where the content lies
|
||||
@@ -1459,7 +1548,7 @@ impl EffectOperation {
|
||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => self.displacement_reach() + 1.,
|
||||
// Within the frame they paint the content's own cells or dots, reading a cell's or a dot's area around each point there, which `Effects::source_region` finds
|
||||
Self::Pixelate { .. } | Self::ColorHalftone { .. } => 0.,
|
||||
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => 0.,
|
||||
Self::PaintOverlay { .. } | Self::Speckle { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1516,7 +1605,7 @@ impl EffectOperation {
|
||||
};
|
||||
|
||||
match &mut self {
|
||||
Self::Blur { radius, .. } => finite(radius),
|
||||
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => finite(radius),
|
||||
Self::DropShadow { angle, distance, spread, size, .. }
|
||||
| Self::InnerShadow {
|
||||
angle, distance, choke: spread, size, ..
|
||||
@@ -1544,9 +1633,9 @@ impl EffectOperation {
|
||||
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
||||
Self::Feather { distance } => finite(distance),
|
||||
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
||||
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
|
||||
Self::MinimumMaximum { radius, .. } | Self::Median { radius } | Self::HighPass { radius } => finite(radius),
|
||||
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
||||
Self::AddNoise { amount, .. } => finite(amount),
|
||||
Self::Speckle { amount, .. } => finite(amount),
|
||||
Self::Dissolve { opacity, .. } => finite(opacity),
|
||||
Self::MotionBlur { angle, distance, .. } => [angle, distance].into_iter().for_each(finite),
|
||||
Self::RadialBlur { amount, transform, .. } => {
|
||||
@@ -1594,7 +1683,7 @@ impl EffectOperation {
|
||||
offset,
|
||||
phase,
|
||||
} => [radius, red_angle, green_angle, blue_angle, &mut offset.x, &mut offset.y, phase].into_iter().for_each(finite),
|
||||
Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::Adjustment(_) => {}
|
||||
Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::BlendIf(_) | Self::Adjustment(_) => {}
|
||||
}
|
||||
self
|
||||
}
|
||||
@@ -1715,6 +1804,7 @@ impl EffectOperation {
|
||||
radius: 0.,
|
||||
mode: MinimumMaximumMode::default(),
|
||||
},
|
||||
EffectKind::Median => Self::Median { radius: 0. },
|
||||
EffectKind::Sharpen => Self::Sharpen {
|
||||
amount: 0.,
|
||||
radius: 0.,
|
||||
@@ -1722,7 +1812,7 @@ impl EffectOperation {
|
||||
edges_only: false,
|
||||
},
|
||||
EffectKind::HighPass => Self::HighPass { radius: 0. },
|
||||
EffectKind::AddNoise => Self::AddNoise {
|
||||
EffectKind::Speckle => Self::Speckle {
|
||||
amount: 0.,
|
||||
distribution: NoiseDistribution::default(),
|
||||
monochromatic: false,
|
||||
@@ -1801,6 +1891,12 @@ impl EffectOperation {
|
||||
offset: DVec2::ZERO,
|
||||
phase: 0.,
|
||||
},
|
||||
EffectKind::BackgroundBlur => Self::BackgroundBlur {
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
},
|
||||
EffectKind::BlendIf => Self::BlendIf(Box::default()),
|
||||
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
|
||||
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
|
||||
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque { strength: 0. }),
|
||||
@@ -1837,6 +1933,7 @@ impl EffectOperation {
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
||||
EffectKind::AlphaToGray => Self::Adjustment(Adjustment::AlphaToGray),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1853,6 +1950,11 @@ impl EffectOperation {
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::BackgroundBlur { radius, box_blur, gamma } => {
|
||||
visitor.parameter("radius", radius, 10.);
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::DropShadow {
|
||||
color,
|
||||
blend_mode,
|
||||
@@ -2045,6 +2147,7 @@ impl EffectOperation {
|
||||
visitor.parameter("radius", radius, 1.);
|
||||
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
||||
}
|
||||
Self::Median { radius } => visitor.parameter("radius", radius, 0.),
|
||||
Self::Sharpen {
|
||||
amount,
|
||||
radius,
|
||||
@@ -2057,7 +2160,7 @@ impl EffectOperation {
|
||||
visitor.parameter("edges_only", edges_only, false);
|
||||
}
|
||||
Self::HighPass { radius } => visitor.parameter("radius", radius, 10.),
|
||||
Self::AddNoise {
|
||||
Self::Speckle {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
@@ -2183,6 +2286,7 @@ impl EffectOperation {
|
||||
visitor.parameter("offset", offset, DVec2::ZERO);
|
||||
visitor.parameter("phase", phase, 0.);
|
||||
}
|
||||
Self::BlendIf(ranges) => ranges.visit_parameters(visitor),
|
||||
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
|
||||
}
|
||||
}
|
||||
@@ -2193,6 +2297,23 @@ mod tests {
|
||||
use super::*;
|
||||
use vector_types::{Gradient, GradientStop};
|
||||
|
||||
#[test]
|
||||
fn box_blurs_reach_their_half_width_and_a_pixel_while_gaussians_reach_three_radii() {
|
||||
let blur = |box_blur| EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 6.,
|
||||
box_blur,
|
||||
gamma: false,
|
||||
};
|
||||
let background_blur = |box_blur| EffectOperation::BackgroundBlur { radius: 6., box_blur, gamma: false };
|
||||
|
||||
// Whether it blurs the content or what lies beneath it, a blur reaches as far as its kernel reads
|
||||
for (box_blur, reach) in [(true, 7.), (false, 18.)] {
|
||||
assert_eq!(blur(box_blur).reach(), reach, "box: {box_blur}");
|
||||
assert_eq!(background_blur(box_blur).reach(), reach, "box: {box_blur}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_round_trip_their_operations_eliding_defaults() {
|
||||
let operations = [
|
||||
@@ -2329,6 +2450,7 @@ mod tests {
|
||||
radius: 7.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Median { radius: 3.5 },
|
||||
EffectOperation::Adjustment(Adjustment::Solarize),
|
||||
EffectOperation::Sharpen {
|
||||
amount: 180.,
|
||||
@@ -2343,7 +2465,7 @@ mod tests {
|
||||
threshold: 0.,
|
||||
edges_only: true,
|
||||
},
|
||||
EffectOperation::AddNoise {
|
||||
EffectOperation::Speckle {
|
||||
amount: 40.,
|
||||
distribution: NoiseDistribution::Gaussian,
|
||||
monochromatic: true,
|
||||
@@ -2436,10 +2558,16 @@ mod tests {
|
||||
offset: DVec2::new(-4., 6.),
|
||||
phase: 25.,
|
||||
},
|
||||
EffectOperation::BlendIf(Box::new({
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 25.;
|
||||
ranges.underlying.red.falloff_end = 80.;
|
||||
ranges
|
||||
})),
|
||||
];
|
||||
|
||||
for operation in operations {
|
||||
assert_eq!(Effect::new(&operation).operation(), operation);
|
||||
for operation in &operations {
|
||||
assert_eq!(Effect::new(operation).operation(), *operation);
|
||||
}
|
||||
|
||||
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
|
||||
@@ -2461,6 +2589,13 @@ mod tests {
|
||||
|
||||
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
|
||||
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
|
||||
|
||||
// Blend If's ranges ride attributes named like its node's inputs
|
||||
let blend_if = operations.iter().find(|operation| operation.kind() == EffectKind::BlendIf).unwrap();
|
||||
let row = Effect::new(blend_if);
|
||||
assert_eq!(row.0.attribute::<f64>("content_range_start"), Some(&25.));
|
||||
assert_eq!(row.0.attribute::<f64>("red_underlying_falloff_end"), Some(&80.));
|
||||
assert_eq!(row.0.attributes().iter_any().count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2780,6 +2915,16 @@ mod tests {
|
||||
assert_eq!(runs, vec![0..3, 3..4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_painting_only_within_the_content_paint_nothing_past_it() {
|
||||
// An inner shadow reads past the content to find the edges it casts from, but paints only within it
|
||||
let (inner_shadow, drop_shadow) = (EffectOperation::default_for(EffectKind::InnerShadow), EffectOperation::default_for(EffectKind::DropShadow));
|
||||
let painted = |effects: Effects| effects.reach_around_by(DAffine2::IDENTITY, [DVec2::ZERO; 2], 0., |operation| !operation.paints_only_within_content());
|
||||
assert!(Effects::from_operations([inner_shadow.clone()]).reach() > 0.);
|
||||
assert_eq!(painted(Effects::from_operations([inner_shadow.clone()])), DVec2::ZERO);
|
||||
assert_eq!(painted(Effects::from_operations([inner_shadow, drop_shadow.clone()])), DVec2::splat(drop_shadow.reach()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() {
|
||||
use EffectKind::*;
|
||||
@@ -2804,6 +2949,7 @@ mod tests {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
AlphaToGray,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
@@ -2903,6 +3049,7 @@ mod tests {
|
||||
radius: 3.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Median { radius: 3.5 },
|
||||
EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 3.,
|
||||
@@ -2926,6 +3073,28 @@ mod tests {
|
||||
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_median_works_on_the_content_grid_coarsened_past_its_largest_radius() {
|
||||
let median = |radius| Effects::from_operations([EffectOperation::Median { radius }]);
|
||||
assert_eq!(median(0.5).content_grid_resolution(), None, "less than a whole pixel changes nothing");
|
||||
assert_eq!(median(5.9).content_grid_resolution(), Some(1.));
|
||||
assert_eq!(median(64.).content_grid_resolution(), Some(MAX_MEDIAN_GRID_RADIUS / 64.));
|
||||
assert_eq!(Effects::from_operations([EffectOperation::FindEdges]).content_grid_resolution(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_median_runs_alone_at_its_own_grid_resolution() {
|
||||
let median = |radius| EffectOperation::Median { radius };
|
||||
let nothing = median(0.);
|
||||
let effects = Effects::from_operations([nothing.clone(), median(1.), median(64.), nothing, EffectOperation::FindEdges, median(2.)]);
|
||||
|
||||
// Effects changing nothing join a median's run, but nothing else does
|
||||
let runs: Vec<_> = effects.runs().into_iter().map(|(_, rows)| rows).collect();
|
||||
assert_eq!(runs, vec![0..2, 2..4, 4..5, 5..6]);
|
||||
let resolutions: Vec<_> = runs.into_iter().map(|rows| effects.run(rows).content_grid_resolution()).collect();
|
||||
assert_eq!(resolutions, [Some(1.), Some(MAX_MEDIAN_GRID_RADIUS / 64.), None, Some(1.)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baking_the_content_placement_into_its_geometry_keeps_its_mask_in_place() {
|
||||
fn nested_placement(graphic: &Graphic) -> DAffine2 {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the CPU, GPU, and SVG each carry out.
|
||||
|
||||
use crate::effects::{EffectOperation, Effects};
|
||||
use crate::effects::EffectOperation;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
||||
@@ -164,9 +164,10 @@ pub fn is_filter(operation: &EffectOperation) -> bool {
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Median { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
)
|
||||
}
|
||||
@@ -178,13 +179,7 @@ pub fn reads_neighbors(operation: &EffectOperation) -> bool {
|
||||
|
||||
/// Whether the operation is a pixel filter combining each pixel with a random field fixed to the content, which changes endless content as much as any other.
|
||||
pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
|
||||
matches!(operation, EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. })
|
||||
}
|
||||
|
||||
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
|
||||
/// The random field filters change endless content without its neighbors (see [`is_random_field_filter`]).
|
||||
pub fn has_filters(effects: &Effects) -> bool {
|
||||
effects.operations().any(|operation| reads_neighbors(&operation) && !operation.changes_nothing())
|
||||
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
||||
}
|
||||
|
||||
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
|
||||
@@ -277,7 +272,7 @@ pub fn fill_shifts(reach: i32) -> Vec<[i32; 2]> {
|
||||
shifts
|
||||
}
|
||||
|
||||
/// How the random offsets Add Noise gives the colors are spread.
|
||||
/// How the random offsets Speckle gives the colors are spread.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
@@ -296,7 +291,7 @@ pub const GAUSSIAN_NOISE_LIMIT: f32 = 3.5;
|
||||
/// The random fields a seed gives, each hashed apart so the fields of one seed are unrelated.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RandomField {
|
||||
/// Add Noise's offset for each color, or for Gaussian noise its first uniform value.
|
||||
/// Speckle's offset for each color, or for Gaussian noise its first uniform value.
|
||||
NoiseOffsets,
|
||||
/// Gaussian noise's second uniform value for each color, its angle.
|
||||
NoiseAngles,
|
||||
@@ -320,7 +315,7 @@ impl RandomField {
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest offset Add Noise of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
|
||||
/// The largest offset Speckle of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
|
||||
pub fn noise_extent(amount: f64, distribution: NoiseDistribution) -> f64 {
|
||||
let deviations = match distribution {
|
||||
NoiseDistribution::Uniform => 1.,
|
||||
|
||||
@@ -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_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, 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)]
|
||||
@@ -626,16 +630,17 @@ impl Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_reduce_to_clip_path(&self) -> bool {
|
||||
/// Whether this graphic clips as its outline would, with `inherited_appearance` cascading from an ancestor to vectors lacking their own.
|
||||
pub fn can_reduce_to_clip_path(&self, inherited_appearance: Option<&Appearance>) -> bool {
|
||||
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
||||
match self {
|
||||
Graphic::Vector(item) => {
|
||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing)
|
||||
&& vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
|
||||
let appearance = Appearance::cascade(item.attribute(ATTR_APPEARANCE), inherited_appearance);
|
||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), appearance)
|
||||
}
|
||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing)
|
||||
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
||||
let appearance = Appearance::cascade(list.attribute(ATTR_APPEARANCE, index), inherited_appearance);
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), appearance)
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
@@ -644,16 +649,22 @@ impl Graphic {
|
||||
pub fn is_guaranteed_fully_opaque(&self) -> bool {
|
||||
match self {
|
||||
Graphic::None(_) | Graphic::NoneList(_) => false,
|
||||
// The group's own opacity scales whatever it wraps, so full alpha there is a precondition
|
||||
Graphic::Graphic(item) => item_opacity_is_full(item) && item.element().is_guaranteed_fully_opaque(),
|
||||
Graphic::GraphicList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque),
|
||||
Graphic::Vector(item) => vector_is_guaranteed_fully_opaque(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
),
|
||||
// The group's own opacity and effects act on whatever it wraps, so they must keep it at full alpha
|
||||
Graphic::Graphic(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_opaque(),
|
||||
Graphic::GraphicList(list) => {
|
||||
!list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque)
|
||||
}
|
||||
Graphic::Vector(item) => {
|
||||
!item_effects_may_change_alpha(item)
|
||||
&& vector_is_guaranteed_fully_opaque(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
)
|
||||
}
|
||||
Graphic::VectorList(list) => {
|
||||
!list.is_empty()
|
||||
&& !list_effects_may_change_alpha(list)
|
||||
&& (0..list.len()).all(|index| {
|
||||
vector_is_guaranteed_fully_opaque(
|
||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||
@@ -665,19 +676,23 @@ impl Graphic {
|
||||
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
||||
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
||||
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
|
||||
Graphic::Color(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_opaque(),
|
||||
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
||||
// 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_effects_may_change_alpha(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) => {
|
||||
!list.is_empty()
|
||||
&& every_item_has_full_opacity(list)
|
||||
&& !list_effects_may_change_alpha(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()))
|
||||
})
|
||||
}
|
||||
@@ -687,27 +702,41 @@ impl Graphic {
|
||||
}
|
||||
|
||||
pub fn is_guaranteed_fully_transparent(&self) -> bool {
|
||||
// An effect that might change alpha, like Make Opaque or a shadow, can show content its paints leave transparent, so only its opacity can hide it
|
||||
match self {
|
||||
Graphic::None(_) | Graphic::NoneList(_) => true,
|
||||
Graphic::Graphic(item) => item_opacity_is_zero(item) || item.element().is_guaranteed_fully_transparent(),
|
||||
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent),
|
||||
Graphic::Vector(item) => vector_is_guaranteed_fully_transparent(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
),
|
||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||
vector_is_guaranteed_fully_transparent(
|
||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
||||
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
||||
)
|
||||
}),
|
||||
Graphic::Color(item) => item_opacity_is_zero(item) || item.element().a() == 0.,
|
||||
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|color| color.a() == 0.),
|
||||
Graphic::Graphic(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_transparent()),
|
||||
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent)),
|
||||
Graphic::Vector(item) => {
|
||||
item_opacity_is_zero(item)
|
||||
|| (!item_effects_may_change_alpha(item)
|
||||
&& vector_is_guaranteed_fully_transparent(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
item.attribute::<Effects>(ATTR_EFFECTS),
|
||||
))
|
||||
}
|
||||
Graphic::VectorList(list) => {
|
||||
every_item_has_zero_opacity(list)
|
||||
|| (!list_effects_may_change_alpha(list)
|
||||
&& (0..list.len()).all(|index| {
|
||||
vector_is_guaranteed_fully_transparent(
|
||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
||||
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index),
|
||||
)
|
||||
}))
|
||||
}
|
||||
Graphic::Color(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().a() == 0.),
|
||||
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.a() == 0.)),
|
||||
// A stopless ramp paints as solid black, matching `Gradient::evaluate`, so it counts as transparent only once it has stops
|
||||
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
||||
Graphic::GradientList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)),
|
||||
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && !item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
||||
Graphic::GradientList(list) => {
|
||||
every_item_has_zero_opacity(list)
|
||||
|| (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)))
|
||||
}
|
||||
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
||||
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
||||
@@ -800,12 +829,13 @@ fn vector_is_guaranteed_fully_opaque(opacity: f64, opacity_fill: f64, appearance
|
||||
}
|
||||
|
||||
/// Whether a vector object draws nothing visible, either through its opacity or through its paint.
|
||||
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>) -> bool {
|
||||
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>, effects: Option<&Effects>) -> bool {
|
||||
if opacity <= f64::EPSILON {
|
||||
return true;
|
||||
}
|
||||
|
||||
let fills_invisible = opacity_fill <= f64::EPSILON
|
||||
// Fill opacity fades the paints but not what effects paint at full strength, like overlays and shadows
|
||||
let fills_invisible = (opacity_fill <= f64::EPSILON && effects.is_none_or(Effects::change_nothing))
|
||||
|| appearance.is_none_or(|appearance| {
|
||||
appearance
|
||||
.covers_with_paints()
|
||||
@@ -823,6 +853,16 @@ fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appea
|
||||
fills_invisible && strokes_invisible
|
||||
}
|
||||
|
||||
/// Whether a lone item's effects might change its alpha, so its element's own alpha can't vouch for it being opaque or transparent.
|
||||
fn item_effects_may_change_alpha<T>(item: &Item<T>) -> bool {
|
||||
item.attribute::<Effects>(ATTR_EFFECTS).is_some_and(Effects::may_change_alpha)
|
||||
}
|
||||
|
||||
/// Whether the effects of any item of a list might change its alpha (see [`item_effects_may_change_alpha`]).
|
||||
fn list_effects_may_change_alpha<T>(list: &List<T>) -> bool {
|
||||
(0..list.len()).any(|index| list.attribute::<Effects>(ATTR_EFFECTS, index).is_some_and(Effects::may_change_alpha))
|
||||
}
|
||||
|
||||
/// Whether a lone item's opacity zeroes it out, independent of what its element holds.
|
||||
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
|
||||
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) <= f64::EPSILON
|
||||
@@ -843,6 +883,21 @@ 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::<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]> {
|
||||
@@ -1287,4 +1342,64 @@ mod graphic_is_opaque_tests {
|
||||
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
|
||||
assert!(!Graphic::Graphic(Box::new(reduced)).is_guaranteed_fully_opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_that_might_change_alpha_leave_content_neither_known_opaque_nor_known_transparent() {
|
||||
use crate::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
|
||||
use crate::effects::EffectOperation;
|
||||
use crate::vector_types::vector::style::Stroke;
|
||||
|
||||
let effected = |graphic: Graphic, operation: EffectOperation| Item::new_from_element(graphic).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]));
|
||||
let colors = |alpha: f64, operation: EffectOperation| {
|
||||
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
|
||||
Graphic::ColorList(List::new_from_item(Item::new_from_element(color).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]))))
|
||||
};
|
||||
let make_opaque = || EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
|
||||
let dissolve = || EffectOperation::Dissolve { opacity: 50., seed: 0 };
|
||||
let levels = |record: LevelsRecord, alpha: LevelsRecord| {
|
||||
EffectOperation::Adjustment(Adjustment::Levels(Box::new(LevelsSettings {
|
||||
composite: record,
|
||||
red: LevelsRecord::IDENTITY,
|
||||
green: LevelsRecord::IDENTITY,
|
||||
blue: LevelsRecord::IDENTITY,
|
||||
alpha,
|
||||
})))
|
||||
};
|
||||
let identity = LevelsRecord::IDENTITY;
|
||||
let darkened = LevelsRecord { output_maximums: 50., ..identity };
|
||||
|
||||
// Adjustments keeping alpha leave paints as opaque or transparent as their colors
|
||||
assert!(colors(1., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_opaque());
|
||||
assert!(colors(0., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_transparent());
|
||||
assert!(colors(1., levels(darkened, identity)).is_guaranteed_fully_opaque());
|
||||
|
||||
// Effects that might fade a paint, or show a transparent one, leave it unknown
|
||||
assert!(!colors(1., dissolve()).is_guaranteed_fully_opaque());
|
||||
assert!(!colors(1., levels(identity, darkened)).is_guaranteed_fully_opaque());
|
||||
assert!(!colors(0., make_opaque()).is_guaranteed_fully_transparent());
|
||||
assert!(!colors(0., make_opaque()).is_guaranteed_to_cover_opaquely());
|
||||
|
||||
// A group's own effects act on all it wraps, though its zero opacity still hides it
|
||||
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(1.), dissolve()))).is_guaranteed_fully_opaque());
|
||||
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()))).is_guaranteed_fully_transparent());
|
||||
assert!(Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()).with_attribute(ATTR_OPACITY, 0.))).is_guaranteed_fully_transparent());
|
||||
|
||||
// A vector's own effects, like a shadow cast by a shape with no visible paint, do too
|
||||
let mut shape = Item::new_from_element(Vector::default());
|
||||
shape.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_stroke(&Stroke::new(4.)), color_graphic(0.)));
|
||||
assert!(Graphic::Vector(Box::new(shape.clone())).is_guaranteed_fully_transparent());
|
||||
let shadowed = shape
|
||||
.clone()
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::default_for(crate::effects::EffectKind::DropShadow)]));
|
||||
assert!(!Graphic::Vector(Box::new(shadowed)).is_guaranteed_fully_transparent());
|
||||
|
||||
// Zero fill opacity hides a vector's paints but not an overlay its effects paint over them, though that keeps alpha
|
||||
let mut filled = Item::new_from_element(Vector::default()).with_attribute(ATTR_OPACITY_FILL, 0.);
|
||||
filled.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), color_graphic(1.)));
|
||||
assert!(Graphic::Vector(Box::new(filled.clone())).is_guaranteed_fully_transparent());
|
||||
let overlay = EffectOperation::default_for(crate::effects::EffectKind::PaintOverlay);
|
||||
assert!(matches!(overlay, EffectOperation::Adjustment(Adjustment::ColorOverlay { .. })), "{overlay:?}");
|
||||
let overlaid = filled.with_attribute(ATTR_EFFECTS, Effects::from_operations([overlay]));
|
||||
assert!(!Graphic::Vector(Box::new(overlaid)).is_guaranteed_fully_transparent());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod adjustment;
|
||||
pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod blend_if;
|
||||
pub mod effect_layers;
|
||||
pub mod effects;
|
||||
pub mod filters;
|
||||
@@ -20,9 +21,10 @@ pub use vector_types;
|
||||
pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use blend_if::BlendIfChannel;
|
||||
pub use effects::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||
stamp_effect, stamped_transform,
|
||||
stamp_effect, stamp_effect_on, stamped_transform,
|
||||
};
|
||||
pub use filters::NoiseDistribution;
|
||||
pub use generator::Generator;
|
||||
|
||||
@@ -7,26 +7,45 @@ use dyn_any::DynAny;
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum MaskMode {
|
||||
/// White shows the content and black hides it, with transparent areas also hiding it.
|
||||
/// White shows the content and black hides it, with transparent areas also hiding it. Brightness is judged by weighting the gamma-encoded RGB channels by `0.3, 0.59, 0.11`.
|
||||
///
|
||||
/// This matches the Luminosity family of blend modes.
|
||||
#[default]
|
||||
Luminance,
|
||||
/// Like Luminance, but brightness is judged by weighting the gamma-encoded RGB channels by `0.2125, 0.7154, 0.0721`, so greens show more of the content, and reds and blues less.
|
||||
///
|
||||
/// SVG luminance masks use this, so masks brought in from SVG keep their look.
|
||||
#[label("Luminance (SVG)")]
|
||||
LuminanceSvg,
|
||||
/// Opaque areas show the content and transparent areas hide it, whatever their colors.
|
||||
Alpha,
|
||||
}
|
||||
|
||||
/// The weights of the red, green, and blue channels in a mask's luminance, those of SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
|
||||
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
|
||||
/// The weights of the red, green, and blue channels in the luminance of a mask in the `Luminance` mode, taken on gamma-encoded channels, those the Luminosity family of blend modes uses.
|
||||
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.3, 0.59, 0.11];
|
||||
|
||||
/// The weights of the red, green, and blue channels in SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
|
||||
/// They weigh the luminance of a mask in the `LuminanceSvg` mode and of the maps that vary other effects, which SVG reads by `luminanceToAlpha`.
|
||||
pub const SVG_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
|
||||
|
||||
impl MaskMode {
|
||||
/// The weights of a mask graphic's premultiplied gamma-encoded red, green, blue, and alpha channels that sum to how much it shows the content.
|
||||
pub fn channel_weights(self) -> [f32; 4] {
|
||||
let ([red, green, blue], alpha) = match self {
|
||||
Self::Luminance => (MASK_LUMINANCE_WEIGHTS, 0.),
|
||||
Self::LuminanceSvg => (SVG_LUMINANCE_WEIGHTS, 0.),
|
||||
Self::Alpha => ([0.; 3], 1.),
|
||||
};
|
||||
[red, green, blue, alpha]
|
||||
}
|
||||
}
|
||||
|
||||
/// How much a pixel of the mask graphic, given as premultiplied gamma-encoded channels, shows the content, from 0 to 1.
|
||||
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in either mode.
|
||||
pub fn mask_coverage([red, green, blue, alpha]: [f32; 4], mode: MaskMode) -> f32 {
|
||||
let [red_weight, green_weight, blue_weight] = MASK_LUMINANCE_WEIGHTS;
|
||||
let coverage = match mode {
|
||||
MaskMode::Luminance => red * red_weight + green * green_weight + blue * blue_weight,
|
||||
MaskMode::Alpha => alpha,
|
||||
};
|
||||
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in every mode.
|
||||
pub fn mask_coverage(channels: [f32; 4], mode: MaskMode) -> f32 {
|
||||
let coverage: f32 = channels.into_iter().zip(mode.channel_weights()).map(|(channel, weight)| channel * weight).sum();
|
||||
coverage.clamp(0., 1.)
|
||||
}
|
||||
|
||||
@@ -89,7 +108,7 @@ pub fn masked_radius_blur_levels(radius: f64, pixels_per_length: f64) -> Vec<f64
|
||||
|
||||
/// The 8-bit code of a masked radius blur map's luminance at a pixel, given as premultiplied gamma-encoded channels, which picks the pixel's interpolation between blurs.
|
||||
pub fn masked_radius_blur_code(channels: [f32; 4]) -> u8 {
|
||||
(mask_coverage(channels, MaskMode::Luminance) * 255.).round() as u8
|
||||
(mask_coverage(channels, MaskMode::LuminanceSvg) * 255.).round() as u8
|
||||
}
|
||||
|
||||
/// For a masked radius blur map's luminance as an 8-bit `code`, the level below it among the `levels` (from [`masked_radius_blur_levels`]) and how many of 255 parts of the interpolation the level above takes, the rest going to the level below.
|
||||
@@ -120,3 +139,21 @@ pub fn masked_radius_blur_weight(level: usize, code: u8, levels: &[f64]) -> u32
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn luminance_modes_weigh_pure_red_green_and_blue_by_their_own_weights() {
|
||||
let level = |channels: [f32; 4], mode| (mask_coverage(channels, mode) * 255.).round() as u8;
|
||||
let primaries = [[1., 0., 0., 1.], [0., 1., 0., 1.], [0., 0., 1., 1.]];
|
||||
|
||||
assert_eq!(primaries.map(|primary| level(primary, MaskMode::Luminance)), [77, 150, 28]);
|
||||
assert_eq!(primaries.map(|primary| level(primary, MaskMode::LuminanceSvg)), [54, 182, 18]);
|
||||
assert_eq!(primaries.map(|primary| level(primary, MaskMode::Alpha)), [255; 3]);
|
||||
|
||||
// Premultiplied channels count the color by its alpha
|
||||
assert_eq!(level([0., 0.5, 0., 0.5], MaskMode::Luminance), 75);
|
||||
}
|
||||
}
|
||||
@@ -1076,10 +1076,10 @@ pub enum DisplaceMode {
|
||||
/// For PSD interop, the 8-bit level of a displacement map's luminance that moves nothing, which black lies the farthest from.
|
||||
pub const DISPLACEMENT_NEUTRAL_LEVEL: f64 = 128.;
|
||||
|
||||
/// The share of its distance that a displacement map's premultiplied gamma-encoded `color` moves the content, by its luminance as a mask reads it:
|
||||
/// The share of its distance that a displacement map's premultiplied gamma-encoded `color` moves the content, by its luminance as an SVG luminance mask reads it:
|
||||
/// -1 at black, none at the neutral level, and 127/128 at white. Where the map is translucent it's seen over the neutral level.
|
||||
pub fn displacement_amount(color: [f32; 4]) -> f64 {
|
||||
let luminance = mask_coverage(color, MaskMode::Luminance) as f64;
|
||||
let luminance = mask_coverage(color, MaskMode::LuminanceSvg) as f64;
|
||||
let level = luminance * 255. + DISPLACEMENT_NEUTRAL_LEVEL * (1. - color[3] as f64);
|
||||
(level - DISPLACEMENT_NEUTRAL_LEVEL) / DISPLACEMENT_NEUTRAL_LEVEL
|
||||
}
|
||||
@@ -1715,10 +1715,10 @@ impl EffectOperation {
|
||||
FrameWarp::of(self).is_some() || warp_of(self).is_some()
|
||||
}
|
||||
|
||||
/// Whether this operation takes the content's frame, which displacements and lattices measure from, unless it changes nothing.
|
||||
/// Whether this operation takes the content's frame, which displacements and lattices measure from and a median reads within, unless it changes nothing.
|
||||
pub fn takes_frame(&self) -> bool {
|
||||
match self {
|
||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } => !self.changes_nothing(),
|
||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } | Self::Median { .. } => !self.changes_nothing(),
|
||||
Self::Twirl { .. }
|
||||
| Self::Pinch { .. }
|
||||
| Self::Spherize { .. }
|
||||
@@ -1743,8 +1743,10 @@ impl EffectOperation {
|
||||
| Self::MinimumMaximum { .. }
|
||||
| Self::Sharpen { .. }
|
||||
| Self::HighPass { .. }
|
||||
| Self::AddNoise { .. }
|
||||
| Self::Speckle { .. }
|
||||
| Self::Dissolve { .. }
|
||||
| Self::BackgroundBlur { .. }
|
||||
| Self::BlendIf(_)
|
||||
| Self::Adjustment(_) => false,
|
||||
}
|
||||
}
|
||||
@@ -2849,7 +2851,7 @@ mod tests {
|
||||
assert!((displacement_amount([0., 0., 0., 1.]) + 1.).abs() < 1e-5);
|
||||
assert_eq!(displacement_amount([0., 0., 0., 0.]), 0.);
|
||||
|
||||
// A color moves the content by its luminance, as a mask reads it, and a pixel reads from the opposite way
|
||||
// A color moves the content by its luminance, as an SVG luminance mask reads it, and a pixel reads from the opposite way
|
||||
let red = displacement_amount([1., 0., 0., 1.]);
|
||||
assert!((red - (0.2125 * 255. - DISPLACEMENT_NEUTRAL_LEVEL) / DISPLACEMENT_NEUTRAL_LEVEL).abs() < 1e-5);
|
||||
assert_eq!(map_displacement([1., 0., 0., 1.], DVec2::new(10., -4.)), DVec2::new(10., -4.) * -red);
|
||||
|
||||
@@ -30,11 +30,12 @@ pub enum StepKind {
|
||||
ColorLookup,
|
||||
ColorOverlay,
|
||||
Solarize,
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl StepKind {
|
||||
/// Every kind, in the order of their codes.
|
||||
pub const ALL: [StepKind; 21] = [
|
||||
pub const ALL: [StepKind; 22] = [
|
||||
StepKind::Desaturate,
|
||||
StepKind::GammaCorrection,
|
||||
StepKind::MakeOpaque,
|
||||
@@ -56,6 +57,7 @@ impl StepKind {
|
||||
StepKind::ColorLookup,
|
||||
StepKind::ColorOverlay,
|
||||
StepKind::Solarize,
|
||||
StepKind::AlphaToGray,
|
||||
];
|
||||
|
||||
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
||||
@@ -269,6 +271,7 @@ mod tests {
|
||||
opacity: 50.,
|
||||
},
|
||||
Adjustment::Solarize,
|
||||
Adjustment::AlphaToGray,
|
||||
];
|
||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||
|
||||
|
||||
@@ -226,6 +226,7 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
||||
}
|
||||
Adjustment::Invert => visitor.visit(Invert),
|
||||
Adjustment::Solarize => visitor.visit(Solarize),
|
||||
Adjustment::AlphaToGray => visitor.visit(AlphaToGray),
|
||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||
min_luminance: (min_luminance / 100.) as f32,
|
||||
max_luminance: (max_luminance / 100.) as f32,
|
||||
@@ -1121,6 +1122,20 @@ impl MapColor for Solarize {
|
||||
}
|
||||
}
|
||||
|
||||
/// Grays each color to the gamma-encoded level of its alpha, keeping the alpha.
|
||||
struct AlphaToGray;
|
||||
|
||||
impl MapColor for AlphaToGray {
|
||||
fn map_cpu(&self, color: Color) -> Color {
|
||||
let gray = srgb_to_linear(color.a());
|
||||
color.map_rgb(|_| gray)
|
||||
}
|
||||
|
||||
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
||||
steps.push(StepKind::AlphaToGray, []);
|
||||
}
|
||||
}
|
||||
|
||||
struct Threshold {
|
||||
min_luminance: f32,
|
||||
max_luminance: f32,
|
||||
@@ -2007,4 +2022,69 @@ mod tests {
|
||||
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustments_changing_alpha_are_known_to_without_running_their_kernels() {
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use glam::DVec2;
|
||||
use graphic_types::effects::{EffectKind, EffectOperation};
|
||||
|
||||
let kinds = [
|
||||
EffectKind::Desaturate,
|
||||
EffectKind::GammaCorrection,
|
||||
EffectKind::MakeOpaque,
|
||||
EffectKind::BrightnessContrast,
|
||||
EffectKind::Levels,
|
||||
EffectKind::Curves,
|
||||
EffectKind::BlackAndWhite,
|
||||
EffectKind::HueSaturation,
|
||||
EffectKind::Invert,
|
||||
EffectKind::Threshold,
|
||||
EffectKind::GradientMap,
|
||||
EffectKind::Vibrance,
|
||||
EffectKind::ChannelMixer,
|
||||
EffectKind::SelectiveColor,
|
||||
EffectKind::Posterize,
|
||||
EffectKind::Exposure,
|
||||
EffectKind::ColorBalance,
|
||||
EffectKind::PhotoFilter,
|
||||
EffectKind::ColorLookup,
|
||||
EffectKind::Solarize,
|
||||
];
|
||||
let defaults = kinds.map(|kind| match EffectOperation::default_for(kind) {
|
||||
EffectOperation::Adjustment(adjustment) => adjustment,
|
||||
operation => panic!("{kind} isn't an adjustment: {operation:?}"),
|
||||
});
|
||||
|
||||
// Levels and Curves change alpha by their alpha records and curves, and nothing else of theirs
|
||||
let identity = settings::LevelsRecord::IDENTITY;
|
||||
let darkened = settings::LevelsRecord { output_maximums: 50., ..identity };
|
||||
let levels = |composite, alpha| {
|
||||
Adjustment::Levels(Box::new(settings::LevelsSettings {
|
||||
composite,
|
||||
red: identity,
|
||||
green: identity,
|
||||
blue: identity,
|
||||
alpha,
|
||||
}))
|
||||
};
|
||||
let curve = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(1., 0.5)]);
|
||||
let curves = |composite: TransferCurve, alpha: TransferCurve| {
|
||||
Adjustment::Curves(Box::new(settings::CurvesSettings {
|
||||
composite,
|
||||
alpha,
|
||||
..Default::default()
|
||||
}))
|
||||
};
|
||||
let settings = [
|
||||
levels(darkened, identity),
|
||||
levels(identity, darkened),
|
||||
curves(curve.clone(), TransferCurve::default()),
|
||||
curves(TransferCurve::default(), curve),
|
||||
];
|
||||
|
||||
for adjustment in defaults.iter().chain(&settings) {
|
||||
assert_eq!(adjustment.may_change_alpha(), !preserves_alpha(adjustment), "{adjustment:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The pixel filters on the CPU, which mirror the renderer's GPU passes on premultiplied gamma-encoded channels.
|
||||
|
||||
use crate::effect_kernels::{BlurKernel, Plane};
|
||||
use crate::resample_kernels::sample_bilinear;
|
||||
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use graphic_types::effects::{MAX_MEDIAN_GRID_RADIUS, spans_along_axes};
|
||||
use graphic_types::filters::{
|
||||
Convolution, FieldSampling, GAUSSIAN_NOISE_LIMIT, HIGH_PASS_GRAY, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, average_weight,
|
||||
edge_gain, fill_shifts, neighborhood_radii, noise_extent, unsharp, unsharp_change,
|
||||
@@ -10,6 +11,7 @@ use graphic_types::filters::{
|
||||
use graphic_types::generator::pcg3d;
|
||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Carries out a filter effect on premultiplied gamma-encoded pixels, which `pixels_to_effect` places in the effect space, or returns them as they are for any other operation.
|
||||
/// The pixels visible in the `full`-strength content (the plane itself for `None`) are those whose colors the filter reads.
|
||||
@@ -27,12 +29,12 @@ pub fn filter(plane: Plane<[f32; 4]>, full: Option<&Plane<[f32; 4]>>, operation:
|
||||
match *operation {
|
||||
EffectOperation::FindEdges => find_edges(&plane, document_to_pixels),
|
||||
EffectOperation::MinimumMaximum { radius, mode } => neighborhood_extreme(&plane, radius, mode == MinimumMaximumMode::Maximum, document_to_pixels),
|
||||
EffectOperation::AddNoise {
|
||||
EffectOperation::Speckle {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
seed,
|
||||
} => add_noise(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect),
|
||||
} => speckle(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect),
|
||||
EffectOperation::Dissolve { opacity, seed } => dissolve(&plane, opacity / 100., seed, pixels_to_effect),
|
||||
_ => plane,
|
||||
}
|
||||
@@ -475,6 +477,105 @@ fn window_extremes(source: &[[f32; 4]], target: &mut [[f32; 4]], radius: usize,
|
||||
}
|
||||
}
|
||||
|
||||
/// The GPU's median of `radius` whole effect-space units, which `pixels_per_length` makes pixels along each axis, on a grid of a pixel to each unit coarsened past [`MAX_MEDIAN_GRID_RADIUS`] as the GPU's is.
|
||||
/// The `image` is the range of pixels along each axis holding the image, whose own pixels read only each other, and `origin` its corner, where the coarse grid starts.
|
||||
pub fn median_on_content_grid(plane: &Plane<[f32; 4]>, radius: f64, pixels_per_length: DVec2, origin: DVec2, image: [Range<usize>; 2]) -> Plane<[f32; 4]> {
|
||||
let whole = radius.max(0.).floor();
|
||||
let coarsening = (MAX_MEDIAN_GRID_RADIUS / whole).min(1.);
|
||||
if coarsening >= 1. {
|
||||
let radii = (pixels_per_length * whole).round().min(DVec2::new(plane.width as f64, plane.height as f64));
|
||||
return match radii == DVec2::ZERO {
|
||||
true => plane.clone(),
|
||||
false => median(plane, [radii.x as usize, radii.y as usize], image),
|
||||
};
|
||||
}
|
||||
|
||||
// The coarse grid's texels, each spanning this many pixels, lie on a lattice from the image's corner, as the GPU's lattice lies from the content's origin
|
||||
let texel = pixels_per_length / coarsening;
|
||||
let first = ((DVec2::ZERO - origin) / texel).floor();
|
||||
let end = ((DVec2::new(plane.width as f64, plane.height as f64) - origin) / texel).ceil();
|
||||
let size = (end - first).max(DVec2::ONE);
|
||||
let texel_center = |index: DVec2| origin + (first + index + 0.5) * texel;
|
||||
|
||||
// The content drawn onto the coarse grid by sampling it at each texel's center, as the GPU draws it
|
||||
let (coarse_width, coarse_height) = (size.x as usize, size.y as usize);
|
||||
let mut coarse = Plane::new(coarse_width, coarse_height);
|
||||
fill_rows(&mut coarse.data, coarse_width, |y, row| {
|
||||
for (x, texel) in row.iter_mut().enumerate() {
|
||||
*texel = sample_bilinear(plane, texel_center(DVec2::new(x as f64, y as f64)));
|
||||
}
|
||||
});
|
||||
|
||||
// The texels whose centers lie within the image, and the median over a window of the radius in texels, then resampled back onto the pixels
|
||||
let within = |axis: usize, count: usize| {
|
||||
let inside = |index: usize| image[axis].contains(&(texel_center(DVec2::splat(index as f64))[axis].floor().max(0.) as usize));
|
||||
let start = (0..count).find(|&index| inside(index)).unwrap_or(count);
|
||||
let end = (start..count).find(|&index| !inside(index)).unwrap_or(count);
|
||||
start..end
|
||||
};
|
||||
let radius_in_texels = (coarsening * whole).round() as usize;
|
||||
let medians = median(&coarse, [radius_in_texels; 2], [within(0, coarse_width), within(1, coarse_height)]);
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let center = DVec2::new(x as f64, y as f64) + 0.5;
|
||||
*pixel = sample_bilinear(&medians, (center - origin) / texel - first);
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// The median of each pixel's window reaching `across` and `down` pixels, as the GPU's median finds it: the alpha's among the window's pixels, with those past the plane's edges transparent,
|
||||
/// and each straight color's among those with coverage, taking the upper median of an even count. A pixel within the `within` range along each axis reads only pixels within it. O(width × height × across × down).
|
||||
pub fn median(plane: &Plane<[f32; 4]>, [across, down]: [usize; 2], within: [Range<usize>; 2]) -> Plane<[f32; 4]> {
|
||||
let inside = |x: isize, y: isize| x >= 0 && y >= 0 && within[0].contains(&(x as usize)) && within[1].contains(&(y as usize));
|
||||
let upper_median = |values: &mut [f32]| *values.select_nth_unstable_by(values.len() / 2, f32::total_cmp).1;
|
||||
let window_capacity = (2 * across + 1) * (2 * down + 1);
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
// Allocated once for the row and reused for each of its pixels
|
||||
let mut alphas: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut colors: [Vec<f32>; 3] = std::array::from_fn(|_| Vec::with_capacity(window_capacity));
|
||||
|
||||
let y = y as isize;
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let x = x as isize;
|
||||
alphas.clear();
|
||||
colors.iter_mut().for_each(Vec::clear);
|
||||
|
||||
let clips = inside(x, y);
|
||||
for read_y in y - down as isize..=y + down as isize {
|
||||
for read_x in x - across as isize..=x + across as isize {
|
||||
if clips && !inside(read_x, read_y) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let on_plane = read_x >= 0 && read_y >= 0 && (read_x as usize) < plane.width && (read_y as usize) < plane.height;
|
||||
let [red, green, blue, alpha] = if on_plane { plane.data[read_y as usize * plane.width + read_x as usize] } else { [0.; 4] };
|
||||
alphas.push(alpha.min(1.));
|
||||
if alpha > 0. {
|
||||
// Kept within the finite range of the GPU's half floats
|
||||
let straight = |channel: f32| (channel / alpha).max(0.).min(65504.);
|
||||
colors.iter_mut().zip([red, green, blue]).for_each(|(values, channel)| values.push(straight(channel)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let alpha = upper_median(&mut alphas);
|
||||
*pixel = match colors[0].is_empty() || !(alpha > 0.) {
|
||||
true => [0.; 4],
|
||||
false => {
|
||||
let [red, green, blue] = colors.each_mut().map(|values| upper_median(values));
|
||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// A value strictly between 0 and 1 from the top 23 bits of a hash, which an f32 holds exactly with the half added, matching the GPU's.
|
||||
fn unit_interval(hash: u32) -> f32 {
|
||||
((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32
|
||||
@@ -511,7 +612,7 @@ fn noise_at(sampling: &FieldSampling, pixel: [usize; 2], distribution: NoiseDist
|
||||
|
||||
/// For PSD interop, each straight color offset by noise of `amount` (a fraction of full brightness) with its `distribution`, the same for every color of a pixel if it's `monochromatic`, and clamped.
|
||||
/// The coverage is kept. The noise is fixed to the cells of the effect space, which `pixels_to_effect` places the plane's pixels among. O(width × height × samples per pixel).
|
||||
pub fn add_noise(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||
pub fn speckle(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||
let sampling = FieldSampling::new(pixels_to_effect);
|
||||
let extent = noise_extent(amount, distribution) as f32;
|
||||
let scale = (amount * sampling.deviation_scale) as f32;
|
||||
@@ -849,7 +950,7 @@ mod tests {
|
||||
let amount = 0.2;
|
||||
|
||||
// Uniform noise spreads evenly up to the amount, with a deviation of the amount over √3
|
||||
let uniform = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY);
|
||||
let uniform = speckle(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY);
|
||||
let (mean, deviation, correlation) = offset_statistics(&uniform);
|
||||
for channel in 0..3 {
|
||||
assert!(
|
||||
@@ -861,21 +962,21 @@ mod tests {
|
||||
assert!(uniform.data.iter().all(|pixel| (pixel[0] - 0.5).abs() <= amount as f32 && pixel[3] == 1.));
|
||||
|
||||
// Gaussian noise deviates by the amount, cut off at its limit
|
||||
let gaussian = add_noise(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY);
|
||||
let gaussian = speckle(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY);
|
||||
let (_, deviation, _) = offset_statistics(&gaussian);
|
||||
assert!((deviation[0] / amount - 1.).abs() < 0.03, "{deviation:?}");
|
||||
|
||||
// Monochromatic noise shifts every color of a pixel together, and another seed gives other noise
|
||||
let monochromatic = add_noise(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
|
||||
let monochromatic = speckle(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
|
||||
assert!(monochromatic.data.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
|
||||
let reseeded = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY);
|
||||
let reseeded = speckle(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY);
|
||||
assert_ne!(reseeded.data[..64], uniform.data[..64]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_is_fixed_to_the_effect_spaces_cells_and_averages_where_pixels_span_several() {
|
||||
let gray = |size: usize| plane(size, size, vec![[0.5, 0.5, 0.5, 1.]; size * size]);
|
||||
let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| add_noise(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect);
|
||||
let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| speckle(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect);
|
||||
|
||||
// A plane placed three cells right and five down holds the same noise at the same cells
|
||||
let placed = noise(&gray(16), DAffine2::IDENTITY);
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! Blends a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend.
|
||||
//! The modes CSS lacks blend normally, since layers only ever take the others.
|
||||
//! The modes CSS lacks, which layers read what lies beneath to blend by, take the formulas the effects share (see [`crate::blending::blend_gamma`]).
|
||||
|
||||
use crate::effect_kernels::Plane;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::Color;
|
||||
use core_types::blending::{BlendMode, apply_blend_mode_at_strength, layer_fill_shown};
|
||||
use core_types::color::BLEND_EDGE_TOLERANCE;
|
||||
|
||||
/// The premultiplied gamma-encoded `layer` blended by the mode onto the layers `below` it. O(width × height).
|
||||
pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode: BlendMode) -> Plane<[f32; 4]> {
|
||||
@@ -11,6 +13,20 @@ pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode:
|
||||
|
||||
/// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop.
|
||||
pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] {
|
||||
blend_pixel_at_strength(source, backdrop, blend_mode, 1.)
|
||||
}
|
||||
|
||||
/// One premultiplied pixel of a layer's full-strength content blended onto another by the mode, faded by the layer's `fill`, or over the backdrop
|
||||
/// in a mode whose fill moves the content toward its neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), moved there by it.
|
||||
pub fn blend_layer_pixel(content: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, fill: f32) -> [f32; 4] {
|
||||
match blend_mode.fill_moves_layer_toward_neutral() {
|
||||
true => blend_pixel_at_strength(content, backdrop, blend_mode, fill),
|
||||
false => blend_pixel(content.map(|channel| channel * fill), backdrop, blend_mode),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`blend_pixel`] with the source at `strength`, which moves it toward the mode's neutral color where it blends, and shows it as strongly as [`layer_fill_shown`] gives.
|
||||
fn blend_pixel_at_strength(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, strength: f32) -> [f32; 4] {
|
||||
let (source_alpha, backdrop_alpha) = (source[3], backdrop[3]);
|
||||
if source_alpha <= 0. {
|
||||
return backdrop;
|
||||
@@ -21,14 +37,18 @@ pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode)
|
||||
false => [0.; 3],
|
||||
};
|
||||
let (source_color, backdrop_color) = (straight(source), straight(backdrop));
|
||||
let blended = blend(backdrop_color, source_color, blend_mode);
|
||||
let blended = match strength < 1. {
|
||||
true => blend_at_strength(backdrop_color, source_color, blend_mode, strength),
|
||||
false => blend(backdrop_color, source_color, blend_mode),
|
||||
};
|
||||
|
||||
let shown = source_alpha * layer_fill_shown(backdrop_alpha, strength);
|
||||
let mut result = [0.; 4];
|
||||
for channel in 0..3 {
|
||||
let mixed = (1. - backdrop_alpha) * source_color[channel] + backdrop_alpha * blended[channel];
|
||||
result[channel] = source_alpha * mixed + (1. - source_alpha) * backdrop[channel];
|
||||
result[channel] = shown * mixed + (1. - shown) * backdrop[channel];
|
||||
}
|
||||
result[3] = source_alpha + backdrop_alpha * (1. - source_alpha);
|
||||
result[3] = shown + backdrop_alpha * (1. - shown);
|
||||
result
|
||||
}
|
||||
|
||||
@@ -39,10 +59,22 @@ fn blend(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode) -> [f32; 3
|
||||
BlendMode::Saturation => set_luminosity(set_saturation(backdrop, saturation(source)), luminosity(backdrop)),
|
||||
BlendMode::Color => set_luminosity(source, luminosity(backdrop)),
|
||||
BlendMode::Luminosity => set_luminosity(backdrop, luminosity(source)),
|
||||
blend_mode if blend_mode.reads_backdrop() => crate::blending::blend_gamma(backdrop, source, blend_mode),
|
||||
_ => [0, 1, 2].map(|channel| blend_channel(backdrop[channel], source[channel], blend_mode)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The blend of straight `backdrop` and `source` colors with the source at `strength`, moved toward the mode's neutral color (see [`apply_blend_mode_at_strength`]).
|
||||
fn blend_at_strength(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode, strength: f32) -> [f32; 3] {
|
||||
if !blend_mode.strength_moves_toward_neutral() {
|
||||
return blend(backdrop, source, blend_mode);
|
||||
}
|
||||
|
||||
let color = |[red, green, blue]: [f32; 3]| Color::from_rgbaf32_unchecked(red, green, blue, 1.);
|
||||
let blended = apply_blend_mode_at_strength(color(source), color(backdrop), blend_mode, strength);
|
||||
[blended.r(), blended.g(), blended.b()]
|
||||
}
|
||||
|
||||
/// The mode's blend of one channel of the backdrop and source, for the modes that blend each channel on its own.
|
||||
fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
|
||||
let hard_light = |backdrop: f32, source: f32| match source <= 0.5 {
|
||||
@@ -56,8 +88,8 @@ fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
|
||||
BlendMode::Overlay => hard_light(source, backdrop),
|
||||
BlendMode::Darken => backdrop.min(source),
|
||||
BlendMode::Lighten => backdrop.max(source),
|
||||
BlendMode::ColorDodge if backdrop <= 0. => 0.,
|
||||
BlendMode::ColorDodge if source >= 1. => 1.,
|
||||
BlendMode::ColorDodge if backdrop <= BLEND_EDGE_TOLERANCE => 0.,
|
||||
BlendMode::ColorDodge if source >= 1. - BLEND_EDGE_TOLERANCE => 1.,
|
||||
BlendMode::ColorDodge => (backdrop / (1. - source)).min(1.),
|
||||
BlendMode::ColorBurn if backdrop >= 1. => 1.,
|
||||
BlendMode::ColorBurn if source <= 0. => 0.,
|
||||
@@ -142,6 +174,195 @@ mod tests {
|
||||
assert!((screened[0] - (0.5 * 0.75 + 0.5 * 0.5)).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// The reference formulas, for PSD interop, for the modes CSS lacks and for Color Burn and Color Dodge, at full strength, on a channel of straight gamma-encoded `backdrop` and `source` colors.
|
||||
fn reference_formula(blend_mode: BlendMode, backdrop: [f32; 3], source: [f32; 3]) -> [f32; 3] {
|
||||
let luma = |color: [f32; 3]| 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2];
|
||||
let color_burn = |b: f32, s: f32| {
|
||||
if b >= 1. {
|
||||
1.
|
||||
} else if s <= 0. {
|
||||
0.
|
||||
} else {
|
||||
1. - ((1. - b) / s).min(1.)
|
||||
}
|
||||
};
|
||||
let color_dodge = |b: f32, s: f32| {
|
||||
if b <= 0. {
|
||||
0.
|
||||
} else if s >= 1. {
|
||||
1.
|
||||
} else {
|
||||
(b / (1. - s)).min(1.)
|
||||
}
|
||||
};
|
||||
let channels = |formula: &dyn Fn(f32, f32) -> f32| [0, 1, 2].map(|channel| formula(backdrop[channel], source[channel]).clamp(0., 1.));
|
||||
|
||||
match blend_mode {
|
||||
BlendMode::ColorBurn => channels(&color_burn),
|
||||
BlendMode::ColorDodge => channels(&color_dodge),
|
||||
BlendMode::LinearBurn => channels(&|b, s| b + s - 1.),
|
||||
BlendMode::LinearDodge => channels(&|b, s| b + s),
|
||||
BlendMode::VividLight => channels(&|b, s| if s <= 0.5 { color_burn(b, 2. * s) } else { color_dodge(b, 2. * s - 1.) }),
|
||||
BlendMode::LinearLight => channels(&|b, s| b + 2. * s - 1.),
|
||||
BlendMode::PinLight => channels(&|b, s| if s <= 0.5 { b.min(2. * s) } else { b.max(2. * s - 1.) }),
|
||||
BlendMode::HardMix => channels(&|b, s| 256. * b - 255. * (1. - s)),
|
||||
BlendMode::Subtract => channels(&|b, s| b - s),
|
||||
BlendMode::Divide => channels(&|b, s| {
|
||||
if b <= 0. {
|
||||
0.
|
||||
} else if s <= 0. {
|
||||
1.
|
||||
} else {
|
||||
b / s
|
||||
}
|
||||
}),
|
||||
BlendMode::DarkerColor => {
|
||||
if luma(source) < luma(backdrop) {
|
||||
source
|
||||
} else {
|
||||
backdrop
|
||||
}
|
||||
}
|
||||
BlendMode::LighterColor => {
|
||||
if luma(source) > luma(backdrop) {
|
||||
source
|
||||
} else {
|
||||
backdrop
|
||||
}
|
||||
}
|
||||
_ => panic!("{blend_mode} blends natively"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pairs of a backdrop and a source color, away from Hard Mix's ramp and the lumas' ties.
|
||||
const PAIRS: [([f32; 3], [f32; 3]); 4] = [
|
||||
([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]),
|
||||
([0.9, 0.1, 0.5], [0.3, 0.7, 0.2]),
|
||||
([0.55, 0.55, 0.55], [0.05, 0.95, 0.35]),
|
||||
([0., 1., 0.3], [0.6, 0.15, 0.8]),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn modes_css_lacks_take_the_reference_formulas_over_any_backdrop() {
|
||||
for blend_mode in BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop) {
|
||||
for (backdrop, source) in PAIRS {
|
||||
let expected = reference_formula(blend_mode, backdrop, source);
|
||||
let opaque = |[red, green, blue]: [f32; 3]| [red, green, blue, 1.];
|
||||
|
||||
// Over an opaque backdrop, the source takes the formula
|
||||
let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode);
|
||||
assert!(
|
||||
(0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5),
|
||||
"{blend_mode}: {blended:?} rather than {expected:?}"
|
||||
);
|
||||
|
||||
// Over one of half alpha, its color mixes halfway from its own to the formula's, as the 16 native modes do
|
||||
let half = [backdrop[0] * 0.5, backdrop[1] * 0.5, backdrop[2] * 0.5, 0.5];
|
||||
let blended = blend_pixel(opaque(source), half, blend_mode);
|
||||
for channel in 0..3 {
|
||||
let mixed = 0.5 * source[channel] + 0.5 * expected[channel];
|
||||
assert!((blended[channel] - mixed).abs() < 1e-5, "{blend_mode} over half alpha: {blended:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_move_the_content_toward_neutral_in_seven_modes_and_fade_it_in_the_others() {
|
||||
let fill = 0.5;
|
||||
let reading = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop);
|
||||
for blend_mode in reading.chain([BlendMode::ColorDodge, BlendMode::ColorBurn]) {
|
||||
for (backdrop, source) in PAIRS {
|
||||
let blended = blend_layer_pixel([source[0], source[1], source[2], 1.], [backdrop[0], backdrop[1], backdrop[2], 1.], blend_mode, fill);
|
||||
|
||||
let expected = match blend_mode {
|
||||
// The paint at full strength once moved halfway toward black, white, or middle gray
|
||||
BlendMode::ColorDodge | BlendMode::LinearDodge => reference_formula(blend_mode, backdrop, source.map(|channel| fill * channel)),
|
||||
BlendMode::ColorBurn | BlendMode::LinearBurn => reference_formula(blend_mode, backdrop, source.map(|channel| 1. - fill * (1. - channel))),
|
||||
BlendMode::VividLight | BlendMode::LinearLight => reference_formula(blend_mode, backdrop, source.map(|channel| 0.5 + fill * (channel - 0.5))),
|
||||
// A ramp a fill of half makes `clamp(2b - 1 + s)`
|
||||
BlendMode::HardMix => [0, 1, 2].map(|channel| Color::blend_hard_mix_at_strength(backdrop[channel], source[channel], fill).clamp(0., 1.)),
|
||||
// Halfway from the backdrop to the blend
|
||||
_ => {
|
||||
let full = reference_formula(blend_mode, backdrop, source);
|
||||
[0, 1, 2].map(|channel| backdrop[channel] + (full[channel] - backdrop[channel]) * fill)
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
(0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5),
|
||||
"{blend_mode}: {blended:?} rather than {expected:?}"
|
||||
);
|
||||
assert!((blended[3] - 1.).abs() < 1e-6, "{blend_mode} covers the opaque backdrop");
|
||||
}
|
||||
}
|
||||
|
||||
// Where nothing lies beneath, the fill fades the content as it is, as a fill fades content in the other modes
|
||||
let faded = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.; 4], BlendMode::LinearDodge, fill);
|
||||
assert!(faded.iter().zip([0.4, 0.2, 0.1, 0.5]).all(|(channel, expected)| (channel - expected).abs() < 1e-6), "{faded:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_moving_layers_toward_neutral_blend_their_share_at_full_strength_over_opaque_backdrops_and_change_nothing_at_no_fill() {
|
||||
let close = |ours: [f32; 4], expected: [f32; 4]| ours.iter().zip(expected).all(|(ours, expected)| (ours - expected).abs() < 1e-5);
|
||||
let premultiplied = |[red, green, blue]: [f32; 3], alpha: f32| [red * alpha, green * alpha, blue * alpha, alpha];
|
||||
let pushed = |blend_mode: BlendMode, source: [f32; 3], fill: f32| {
|
||||
source.map(|channel| match blend_mode {
|
||||
BlendMode::ColorDodge | BlendMode::LinearDodge => fill * channel,
|
||||
BlendMode::ColorBurn | BlendMode::LinearBurn => 1. - fill * (1. - channel),
|
||||
_ => 0.5 + fill * (channel - 0.5),
|
||||
})
|
||||
};
|
||||
|
||||
let modes = [
|
||||
BlendMode::ColorDodge,
|
||||
BlendMode::ColorBurn,
|
||||
BlendMode::LinearDodge,
|
||||
BlendMode::LinearBurn,
|
||||
BlendMode::VividLight,
|
||||
BlendMode::LinearLight,
|
||||
];
|
||||
for blend_mode in modes {
|
||||
for (backdrop, source) in PAIRS {
|
||||
for alpha in [1., 0.5] {
|
||||
for fill in [0., 0.3, 1.] {
|
||||
// Over an opaque backdrop, the content's share blends the paint moved toward neutral at full strength, the rest showing the backdrop, for PSD interop
|
||||
let full = reference_formula(blend_mode, backdrop, pushed(blend_mode, source, fill));
|
||||
let expected = [0, 1, 2].map(|channel| alpha * full[channel] + (1. - alpha) * backdrop[channel]);
|
||||
let blended = blend_layer_pixel(premultiplied(source, alpha), premultiplied(backdrop, 1.), blend_mode, fill);
|
||||
assert!(close(blended, premultiplied(expected, 1.)), "{blend_mode} at fill {fill}, alpha {alpha}: {blended:?}");
|
||||
|
||||
// Over nothing, the fill fades the content as it is
|
||||
let blended = blend_layer_pixel(premultiplied(source, alpha), [0.; 4], blend_mode, fill);
|
||||
assert!(close(blended, premultiplied(source, alpha * fill)), "{blend_mode} at fill {fill} over nothing: {blended:?}");
|
||||
}
|
||||
|
||||
for backdrop_alpha in [0.25, 0.5, 0.75] {
|
||||
let beneath = premultiplied(backdrop, backdrop_alpha);
|
||||
|
||||
// No fill leaves a partly covering backdrop as it is, alpha included
|
||||
let unfilled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 0.);
|
||||
assert!(close(unfilled, beneath), "{blend_mode} at no fill over alpha {backdrop_alpha}: {unfilled:?}");
|
||||
|
||||
// A full fill blends by the W3C's general formula, mixing toward the blend as far as the backdrop covers
|
||||
let blend = reference_formula(blend_mode, backdrop, source);
|
||||
let mixed = [0, 1, 2].map(|channel| (1. - backdrop_alpha) * source[channel] + backdrop_alpha * blend[channel]);
|
||||
let expected = [0, 1, 2]
|
||||
.map(|channel| alpha * mixed[channel] + (1. - alpha) * beneath[channel])
|
||||
.into_iter()
|
||||
.chain([alpha + (1. - alpha) * backdrop_alpha])
|
||||
.collect::<Vec<f32>>();
|
||||
let filled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 1.);
|
||||
assert!(close(filled, expected.try_into().unwrap()), "{blend_mode} at full fill over alpha {backdrop_alpha}: {filled:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An opaque layer at no fill over half alpha leaves that alpha
|
||||
let unfilled = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.25, 0.25, 0.25, 0.5], BlendMode::LinearDodge, 0.);
|
||||
assert!((unfilled[3] - 0.5).abs() < 1e-6, "{unfilled:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_luminosity_of_black_over_any_gray_is_black() {
|
||||
for level in 0..=255 {
|
||||
|
||||
@@ -18,4 +18,4 @@ pub mod warp_kernels;
|
||||
|
||||
pub use kernel::*;
|
||||
pub use raster_effects::evaluate_raster_effects;
|
||||
pub use value_effects::{evaluate_color_effects, evaluate_gradient_effects};
|
||||
pub use value_effects::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
|
||||
@@ -90,7 +90,7 @@ pub(crate) fn masked_radius_blur_codes(colors: &[Color]) -> Vec<u8> {
|
||||
pub(crate) fn masked_box_blur_luminances(colors: &[Color]) -> Vec<f32> {
|
||||
let luminance = |color: Color| {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::Luminance).clamp(0., 1.)
|
||||
mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::LuminanceSvg).clamp(0., 1.)
|
||||
};
|
||||
colors.iter().map(|&color| half::f16::from_f32(luminance(color)).to_f32()).collect()
|
||||
}
|
||||
|
||||
@@ -8,17 +8,18 @@ use crate::generators::pattern_sampler;
|
||||
use crate::layer_blending::blend_layer;
|
||||
use crate::masks::{feather_strength, mask_strength, masked, masked_box_blur_luminances, masked_radius_blur, masked_radius_blur_codes, variable_box_blur};
|
||||
use crate::resample_kernels::{MotionBlurShear, displaced, frame_warped, halftoned, motion_blurred, pixelated, radial_blurred};
|
||||
use crate::value_effects::{adjusted_gradient, adjustments, evaluate_gradient_effects, filled_color};
|
||||
use crate::value_effects::{adjusted_gradient_with_blend_ifs, adjustments, content_blend_ifs, evaluate_gradient_effects, filled_color_with_blend_ifs};
|
||||
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_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};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, paint_overlay_folds};
|
||||
use graphic_types::effect_layers::{EffectLayers, LayerPart, PiecePlace};
|
||||
use graphic_types::effects::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, EffectCapture, EffectOperation, Effects, GlowFill, GlowSource, GlowTechnique, OutlineFill, bevel_light, contour_gradient_span, effect_space,
|
||||
@@ -31,7 +32,9 @@ use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, Halft
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{CPU, Image, Raster};
|
||||
use std::collections::HashMap;
|
||||
use vector_types::gradient::{Gradient, GradientForm, GradientSettings, GradientSpread};
|
||||
use std::ops::Range;
|
||||
use vector_types::gradient::{Gradient, GradientSettings, GradientSpread};
|
||||
use vector_types::gradient_standard::GradientShape;
|
||||
|
||||
mod styles;
|
||||
|
||||
@@ -118,9 +121,22 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Each row's run and its place in it, which Blend Ifs act within as the renderers' runs do
|
||||
let operations: Vec<EffectOperation> = rows.iter().map(|(operation, ..)| operation.clone()).collect();
|
||||
let runs: Vec<Range<usize>> = effects.runs().into_iter().map(|(_, rows)| rows).collect();
|
||||
let in_run = |index: usize| match runs.iter().find(|rows| rows.contains(&index)) {
|
||||
Some(rows) => (&operations[rows.clone()], index - rows.start),
|
||||
None => (&operations[..], index),
|
||||
};
|
||||
|
||||
// Unless a fill fades them first, leading adjustments flattened into the image change its own colors, keeping even transparent pixels' colors
|
||||
let layers = EffectLayers::plan_runs(effects, BlendMode::Normal, fill, true);
|
||||
let leading_adjustments = rows.iter().take(layers.flattened).take_while(|_| fill == 1.).map_while(|(operation, ..)| match operation {
|
||||
let overlay_folds = |index: usize| {
|
||||
let (run, row) = in_run(index);
|
||||
paint_overlay_folds(run, row)
|
||||
};
|
||||
let leading_adjustments = (rows.iter().enumerate().take(layers.flattened).take_while(|_| fill == 1.)).map_while(|(index, (operation, ..))| match operation {
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { .. }) if !overlay_folds(index) => None,
|
||||
EffectOperation::Adjustment(adjustment) => Some(adjustment),
|
||||
_ => None,
|
||||
});
|
||||
@@ -181,9 +197,13 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
let mut pieces: HashMap<EffectCapture, Plane<[f32; 4]>> = HashMap::new();
|
||||
// How much the trailing masks together show of each finished layer
|
||||
let mut layer_fade: Option<Plane<f32>> = None;
|
||||
// How strongly the Blend Ifs so far show the content, which fades it like a fill varying across it
|
||||
let mut blend_if_weight: Option<Plane<f32>> = None;
|
||||
|
||||
// Each run after the first takes the result of those before it as its content at full strength, like the renderers' nested runs
|
||||
let mut run_fill = fill;
|
||||
// The leading adjustments carried out on the image's colors still start stretches that Blend Ifs act at the start of
|
||||
let mut rows_reached = 0;
|
||||
for (index, &(ref operation, effect_to_pixels, starts_later_run)) in rows.iter().enumerate().skip(leading) {
|
||||
if starts_later_run {
|
||||
full = match (filled.take(), beneath.take()) {
|
||||
@@ -192,7 +212,23 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
(None, None) => full,
|
||||
};
|
||||
run_fill = 1.;
|
||||
blend_if_weight = None;
|
||||
}
|
||||
|
||||
let acting_blend_ifs = (rows_reached..=index).flat_map(|row| {
|
||||
let (run, row) = in_run(row);
|
||||
blend_ifs_acting_before(run, row)
|
||||
});
|
||||
for ranges in acting_blend_ifs.filter(|ranges| !ranges.content.show_everything()) {
|
||||
let weight = blend_if_weights(&full, &ranges.content);
|
||||
filled = Some(filled.as_ref().unwrap_or(&full).zip(&weight, |pixel, weight| pixel.map(|channel| channel * weight)));
|
||||
blend_if_weight = Some(match blend_if_weight {
|
||||
Some(previous) => previous.zip(&weight, |previous, weight| previous * weight),
|
||||
None => weight,
|
||||
});
|
||||
}
|
||||
rows_reached = index + 1;
|
||||
|
||||
if operation.changes_nothing() {
|
||||
continue;
|
||||
}
|
||||
@@ -210,6 +246,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
let layered = index >= layers.flattened;
|
||||
let piece = |plane: usize| layered.then_some(EffectCapture { index, plane });
|
||||
let knockout_fill = if layered { 1. } else { run_fill };
|
||||
let knockout_weight = blend_if_weight.as_ref().filter(|_| !layered);
|
||||
|
||||
match *operation {
|
||||
EffectOperation::Blur { radius, box_blur, gamma, .. } if !operation.varies_blur_radius() => {
|
||||
@@ -273,7 +310,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
let silhouette = full.map(|[_, _, _, alpha]| alpha).shifted(offset.x, offset.y);
|
||||
let strength = cast(silhouette, size, spread, GlowTechnique::Softer, 100., contour, pixels_per_length);
|
||||
let shadow = tinted(&strength, color);
|
||||
let shadow = if knockout { knocked_out(shadow, &full, knockout_fill) } else { shadow };
|
||||
let shadow = if knockout { knocked_out(shadow, &full, knockout_fill, knockout_weight) } else { shadow };
|
||||
place_beneath(&mut pieces, piece(0), &mut beneath, shadow);
|
||||
}
|
||||
EffectOperation::OuterGlow {
|
||||
@@ -293,7 +330,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
let strength = shaped(raw.clone(), range, contour);
|
||||
let grain = styles::GlowGrain::new(&paint, noise, jitter, seed, pixels_to_effect);
|
||||
let fades = matches!(paint, GlowFill::Gradient { .. }) || noise > 0.;
|
||||
let glow = knocked_out(glow_tint(&paint, &strength, &raw, fades, grain.as_ref()), &full, knockout_fill);
|
||||
let glow = knocked_out(glow_tint(&paint, &strength, &raw, fades, grain.as_ref()), &full, knockout_fill, knockout_weight);
|
||||
place_beneath(&mut pieces, piece(0), &mut beneath, glow);
|
||||
}
|
||||
EffectOperation::InnerShadow {
|
||||
@@ -411,7 +448,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
|
||||
// The band outside lies beneath the content like a shadow, and the band inside over it like an inner shadow
|
||||
if let Some(band) = &bands.outside {
|
||||
let band = knocked_out(painted(band), &full, knockout_fill);
|
||||
let band = knocked_out(painted(band), &full, knockout_fill, knockout_weight);
|
||||
place_beneath(&mut pieces, piece(0), &mut beneath, band);
|
||||
}
|
||||
if let Some(band) = &bands.inside {
|
||||
@@ -492,7 +529,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
place_within(&mut pieces, piece(plane), &mut full, &mut filled, tinted(&amount, color), blend_mode);
|
||||
}
|
||||
for (plane, (amount, (color, _))) in outside.into_iter().flatten().zip(colors).enumerate() {
|
||||
let slope = knocked_out(tinted(&amount, color), &full, knockout_fill);
|
||||
let slope = knocked_out(tinted(&amount, color), &full, knockout_fill, knockout_weight);
|
||||
place_beneath(&mut pieces, piece(plane + 2), &mut beneath, slope);
|
||||
}
|
||||
}
|
||||
@@ -511,6 +548,18 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
};
|
||||
place_within(&mut pieces, piece(0), &mut full, &mut filled, painted, blend_mode);
|
||||
}
|
||||
// An image of its own has nothing beneath it to blur, or for Blend If to read, which fades the content where it acts
|
||||
EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => {}
|
||||
EffectOperation::Median { radius } => {
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
let origin = DVec2::new(margin_x as f64, margin_y as f64);
|
||||
let median = |plane: &Plane<[f32; 4]>| {
|
||||
let image = [margin_x..margin_x + width, margin_y..margin_y + height];
|
||||
crate::filter_kernels::median_on_content_grid(plane, radius, pixels_per_length, origin, image)
|
||||
};
|
||||
full = median(&full);
|
||||
filled = filled.map(|filled| median(&filled));
|
||||
}
|
||||
// A solid paint overlay paints within the content alone, like any other paint overlay
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => {
|
||||
let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32));
|
||||
@@ -670,7 +719,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
let Some(frame) = &frame else { continue };
|
||||
let Some(screens) = HalftoneScreen::of(operation, frame) else { continue };
|
||||
|
||||
// Each pixel's share of the content that the fill left fades the printed dots, rather than printing the faded content's fainter dots
|
||||
// Each pixel's share of the content that the fill and the Blend Ifs left fades the printed dots, rather than printing the faded content's fainter dots
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
let shares = filled.as_ref().map(|filled| crate::filter_kernels::fill_shares(&full, filled));
|
||||
let unfaded = filled.map(|filled| crate::filter_kernels::at_full_coverage(&filled, &full));
|
||||
@@ -690,7 +739,7 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
| EffectOperation::Dissolve { .. } => {
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
// A filter sharpening the coverage fades the fill's result by the share of the full-strength coverage each pixel's fill left, as if the fill faded the result
|
||||
@@ -879,19 +928,31 @@ fn tinted(coverage: &Plane<f32>, color: Color) -> Plane<[f32; 4]> {
|
||||
coverage.map(|coverage| color.map(|channel| channel * coverage))
|
||||
}
|
||||
|
||||
/// A tinted image of what lies beneath, hidden behind the full-strength content where the content covers it as strongly as `fill`.
|
||||
fn knocked_out(tinted: Plane<[f32; 4]>, full_content: &Plane<[f32; 4]>, fill: f32) -> Plane<[f32; 4]> {
|
||||
if fill >= 1. {
|
||||
/// A tinted image of what lies beneath, hidden behind the full-strength content where the content covers it as strongly as `fill`, times the Blend If weight if any fades it.
|
||||
fn knocked_out(tinted: Plane<[f32; 4]>, full_content: &Plane<[f32; 4]>, fill: f32, blend_if_weight: Option<&Plane<f32>>) -> Plane<[f32; 4]> {
|
||||
if fill >= 1. && blend_if_weight.is_none() {
|
||||
return tinted;
|
||||
}
|
||||
|
||||
// The faded content shows what's beneath through 1 - fill × alpha of it, of which only 1 - alpha may show this
|
||||
tinted.zip(full_content, |tinted, content| {
|
||||
let shown = (1. - content[3]) / (1. - fill * content[3]).max(f32::EPSILON);
|
||||
let covering = match blend_if_weight {
|
||||
Some(weight) => full_content.zip(weight, |content, weight| [content[3], weight * fill, 0., 0.]),
|
||||
None => full_content.map(|content| [content[3], fill, 0., 0.]),
|
||||
};
|
||||
tinted.zip(&covering, |tinted, [alpha, fill, ..]| {
|
||||
let shown = (1. - alpha) / (1. - fill * alpha).max(f32::EPSILON);
|
||||
tinted.map(|channel| channel * shown)
|
||||
})
|
||||
}
|
||||
|
||||
/// How strongly Blend If's `ranges` show each pixel of a premultiplied gamma-encoded `image`, by its straight color.
|
||||
fn blend_if_weights(image: &Plane<[f32; 4]>, ranges: &ChannelRanges) -> Plane<f32> {
|
||||
image.map(|[red, green, blue, alpha]| {
|
||||
let straight = if alpha > 0. { [red, green, blue].map(|channel| (channel / alpha) as f64) } else { [0.; 3] };
|
||||
ranges.weight(straight) as f32
|
||||
})
|
||||
}
|
||||
|
||||
/// Places a tinted image beneath the content: as the layered `piece` if it names one, or else stacked over what lies `beneath` the content so far.
|
||||
fn place_beneath(pieces: &mut HashMap<EffectCapture, Plane<[f32; 4]>>, piece: Option<EffectCapture>, beneath: &mut Option<Plane<[f32; 4]>>, tinted: Plane<[f32; 4]>) {
|
||||
match piece {
|
||||
@@ -955,7 +1016,7 @@ fn composite_layers(
|
||||
PiecePlace::Within => SharePart::Whole,
|
||||
PiecePlace::IntoContent { over: false } => SharePart::IntoContent,
|
||||
PiecePlace::IntoContent { over: true } => SharePart::IntoContentBeneathPartOver { opacity: OPACITY, fade },
|
||||
PiecePlace::Beneath | PiecePlace::Through { .. } => continue,
|
||||
PiecePlace::Beneath | PiecePlace::Through { .. } | PiecePlace::Backdrop => continue,
|
||||
};
|
||||
content = composite_in_share(&content, tinted, full_content, piece.blend_mode, part);
|
||||
}
|
||||
@@ -977,7 +1038,8 @@ fn composite_layers(
|
||||
PiecePlace::Beneath => tinted.clone(),
|
||||
PiecePlace::Within if !holds_content => tinted.zip(full_content, |tinted, content| tinted.map(|channel| channel * content[3])),
|
||||
PiecePlace::Through { .. } => tinted.zip(&through_shares(full_content, &content, OPACITY, fade), |tinted, share| tinted.map(|channel| channel * share)),
|
||||
PiecePlace::Within | PiecePlace::IntoContent { .. } => continue,
|
||||
// What lies beneath, for a backdrop the image doesn't have
|
||||
PiecePlace::Within | PiecePlace::IntoContent { .. } | PiecePlace::Backdrop => continue,
|
||||
};
|
||||
stack = Some(stack_over(stack, upper));
|
||||
}
|
||||
@@ -1178,7 +1240,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());
|
||||
@@ -1189,8 +1251,9 @@ fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync +
|
||||
// The fill fades the color beneath its paint overlays, which paint over it at full strength, as the renderers fill an endless color
|
||||
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||
let adjustments = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments).unwrap_or_default();
|
||||
let color = filled_color(*item.element(), &adjustments, fill);
|
||||
let effects = item.attribute::<Effects>(ATTR_EFFECTS);
|
||||
let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default());
|
||||
let color = filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill);
|
||||
Some(Box::new(move |_| faded(color, opacity)))
|
||||
}
|
||||
Graphic::RasterCPU(item) => {
|
||||
@@ -1208,7 +1271,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) => {
|
||||
@@ -1341,12 +1408,13 @@ fn displacement_map_sampler(map: &Graphic) -> Option<Box<dyn Fn(DVec2) -> [f32;
|
||||
Some(Box::new(move |point| sample_gamma(&image, to_pixels.transform_point2(point)).map(|channel| channel * opacity)))
|
||||
}
|
||||
Graphic::Gradient(item) => {
|
||||
// The GPU fades a gradient by its fill in the layer of its opacity, unless adjustments act on the ramp the fill fades
|
||||
let adjustments = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing()).map(adjustments).unwrap_or_default();
|
||||
// The GPU fades a gradient by its fill in the layer of its opacity, unless effects act on the ramp the fill fades
|
||||
let effects = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing());
|
||||
let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default());
|
||||
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||
let settings = GradientSettings::from_item_attributes(item);
|
||||
let (gradient, settings, opacity) = match adjusted_gradient(item.element(), settings, &adjustments, fill) {
|
||||
let (gradient, settings, opacity) = match adjusted_gradient_with_blend_ifs(item.element(), settings, &adjustments, &blend_ifs, fill) {
|
||||
Some((adjusted, adjusted_settings)) => (std::borrow::Cow::Owned(adjusted), adjusted_settings, opacity),
|
||||
None => (std::borrow::Cow::Borrowed(item.element()), settings, opacity * fill),
|
||||
};
|
||||
@@ -1355,17 +1423,23 @@ 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)
|
||||
}))
|
||||
}
|
||||
Graphic::Color(item) => {
|
||||
// The GPU fills a solid color from 8-bit channels in a layer of its opacity, which the fill fades too unless adjustments act on the faded color
|
||||
let adjustments = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing()).map(adjustments).unwrap_or_default();
|
||||
// The GPU fills a solid color from 8-bit channels in a layer of its opacity, which the fill fades too unless effects act on the faded color
|
||||
let effects = item.attribute::<Effects>(ATTR_EFFECTS).filter(|effects| !effects.change_nothing());
|
||||
let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default());
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||
let (color, opacity) = match adjustments.is_empty() {
|
||||
let (color, opacity) = match adjustments.is_empty() && blend_ifs.is_empty() {
|
||||
true => (*item.element(), paint_opacity(item)),
|
||||
false => (filled_color(*item.element(), &adjustments, fill), item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32),
|
||||
false => (
|
||||
filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill),
|
||||
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32,
|
||||
),
|
||||
};
|
||||
let (color, opacity) = (core_types::color::SRGBA8::from(color), layer_opacity(opacity));
|
||||
|
||||
@@ -1438,22 +1512,49 @@ 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),
|
||||
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)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1670,7 +1771,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn random_fields_move_and_scale_with_the_content_after_them() {
|
||||
let noise = EffectOperation::AddNoise {
|
||||
let noise = EffectOperation::Speckle {
|
||||
amount: 30.,
|
||||
distribution: graphic_types::NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
@@ -1820,9 +1921,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 {
|
||||
@@ -2446,6 +2545,60 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halftones_keep_the_fade_of_blend_ifs_before_them() {
|
||||
use graphic_types::blend_if::{BlendIfRanges, BlendRange};
|
||||
|
||||
// A Blend If hiding the white content stays hiding it once a halftone prints it, which white leaves as white
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.content.gray = BlendRange {
|
||||
falloff_start: 0.,
|
||||
range_start: 0.,
|
||||
range_end: 50.,
|
||||
falloff_end: 50.,
|
||||
};
|
||||
let halftone = EffectOperation::ColorHalftone {
|
||||
radius: 4.,
|
||||
red_angle: 45.,
|
||||
green_angle: 45.,
|
||||
blue_angle: 45.,
|
||||
offset: DVec2::ZERO,
|
||||
phase: 0.,
|
||||
};
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(24, 24, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(24.)));
|
||||
[EffectOperation::BlendIf(Box::new(ranges)), halftone]
|
||||
.iter()
|
||||
.for_each(|operation| graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation)));
|
||||
|
||||
let evaluated = evaluate_raster_effects(item);
|
||||
assert!(evaluated.element().data.iter().all(|color| color.a() < 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_still_act_after_leading_adjustments_that_change_nothing() {
|
||||
use graphic_types::blend_if::{BlendIfRanges, BlendRange};
|
||||
|
||||
// A Blend If hiding the white content hides it before the invert, though the image's own colors take the Make Opaque of no strength ahead of it
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.content.gray = BlendRange {
|
||||
falloff_start: 0.,
|
||||
range_start: 0.,
|
||||
range_end: 50.,
|
||||
falloff_end: 50.,
|
||||
};
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(8, 8, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.)));
|
||||
[
|
||||
EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 0. }),
|
||||
EffectOperation::BlendIf(Box::new(ranges)),
|
||||
EffectOperation::Adjustment(Adjustment::Invert),
|
||||
]
|
||||
.iter()
|
||||
.for_each(|operation| graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation)));
|
||||
|
||||
let evaluated = evaluate_raster_effects(item);
|
||||
assert!(evaluated.element().data.iter().all(|color| color.a() < 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halftones_too_fine_to_print_show_their_tone() {
|
||||
// Dots a fraction of a pixel apart print the tone they average to, which for opaque content is the content
|
||||
|
||||
@@ -5,8 +5,9 @@ use crate::adjustments::{PreparedAdjustment, adjust_color};
|
||||
use crate::blending::overlay_paint;
|
||||
use core_types::Color;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_OPACITY, ATTR_OPACITY_FILL, Item};
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
|
||||
use graphic_types::effects::{EffectOperation, Effects};
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
@@ -29,6 +30,47 @@ pub fn adjustments(effects: &Effects) -> Vec<Adjustment> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A step a value's Blend Ifs take among its adjustments (see [`content_blend_ifs`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum BlendIfStep {
|
||||
/// A Blend If reads the value's colors and fades the value by these content ranges, as a fill does.
|
||||
Fade(ChannelRanges),
|
||||
/// An effect run after the first starts (see [`Effects::runs`]), taking the value as the runs before it leave it as its content at full strength.
|
||||
NextRun,
|
||||
}
|
||||
|
||||
/// Where each Blend If among the effects that fades a value by its own colors reads it, after how many of the [`adjustments`], with where each effect run after the first starts.
|
||||
/// Empty if no Blend If fades the value.
|
||||
pub fn content_blend_ifs(effects: &Effects) -> Vec<(usize, BlendIfStep)> {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
if !fades_content(&operations) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// Each run's Blend Ifs act from its own start, as the renderers draw each run's effects on the result of those before it
|
||||
let mut adjustments_before = 0;
|
||||
let mut steps = Vec::new();
|
||||
for (run_index, (_, rows)) in effects.runs().into_iter().enumerate() {
|
||||
if run_index > 0 {
|
||||
steps.push((adjustments_before, BlendIfStep::NextRun));
|
||||
}
|
||||
|
||||
let run = &operations[rows];
|
||||
for (row, operation) in run.iter().enumerate() {
|
||||
let acting = blend_ifs_acting_before(run, row).into_iter().filter(|ranges| !ranges.content.show_everything());
|
||||
steps.extend(acting.map(|ranges| (adjustments_before, BlendIfStep::Fade(ranges.content))));
|
||||
|
||||
adjustments_before += usize::from(matches!(operation, EffectOperation::Adjustment(_)));
|
||||
}
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// Whether a Blend If fades a value with effects in more than one run, so later runs read and paint within the result of those before them.
|
||||
pub fn blend_ifs_span_runs(effects: &Effects) -> bool {
|
||||
content_blend_ifs(effects).iter().any(|(_, step)| *step == BlendIfStep::NextRun)
|
||||
}
|
||||
|
||||
/// The color with `adjustments` carried out on it in order.
|
||||
pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color {
|
||||
adjustments.iter().fold(color, |color, adjustment| adjust_color(adjustment, color))
|
||||
@@ -37,19 +79,60 @@ pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color {
|
||||
/// The color an endless paint of `color` shows with `adjustments` carried out over it and its `fill` fading it, though not the paint overlays painted over it.
|
||||
/// Without edges, each paint overlay blends with the paint itself, which is exact where the paint is opaque.
|
||||
pub fn filled_color(color: Color, adjustments: &[Adjustment], fill: f32) -> Color {
|
||||
if fill >= 1. {
|
||||
return adjusted_color(color, adjustments);
|
||||
}
|
||||
fill_through(color, adjustments, fill, |index, color| adjust_color(&adjustments[index], color))
|
||||
filled_color_with_blend_ifs(color, adjustments, &[], fill)
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` over a paint faded by `fill` as [`filled_color`] does, with `adjust` carrying out each one besides a paint overlay, given its index.
|
||||
fn fill_through(color: Color, adjustments: &[Adjustment], fill: f32, adjust: impl Fn(usize, Color) -> Color) -> Color {
|
||||
/// Like [`filled_color`], with the steps of the `blend_ifs` (see [`content_blend_ifs`]) also fading the paint by each one's content ranges where it reads the paint's colors.
|
||||
pub fn filled_color_with_blend_ifs(color: Color, adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> Color {
|
||||
if fill >= 1. && blend_ifs.is_empty() {
|
||||
return adjusted_color(color, adjustments);
|
||||
}
|
||||
fill_through(color, adjustments, blend_ifs, fill, |index, color| adjust_color(&adjustments[index], color), ChannelRanges::weight)
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` over a paint faded by `fill` and the `blend_ifs` as [`filled_color_with_blend_ifs`] does, with `adjust` carrying out each one besides a paint overlay, given its index.
|
||||
/// `weigh` gives how strongly a Blend If's ranges show the gamma-encoded channels it reads.
|
||||
fn fill_through(
|
||||
color: Color,
|
||||
adjustments: &[Adjustment],
|
||||
blend_ifs: &[(usize, BlendIfStep)],
|
||||
fill: f32,
|
||||
adjust: impl Fn(usize, Color) -> Color,
|
||||
mut weigh: impl FnMut(&ChannelRanges, [f64; 3]) -> f64,
|
||||
) -> Color {
|
||||
// Each Blend If fades the faded color by how strongly it shows the full-strength one, which each later run resets to the faded color
|
||||
let mut steps = blend_ifs.iter().peekable();
|
||||
let mut take_steps = |full: &mut Color, filled: &mut Color, adjusted_count: usize| {
|
||||
let mut weight = 1.;
|
||||
let mut faded = false;
|
||||
while let Some((_, step)) = steps.next_if(|(before, _)| *before <= adjusted_count) {
|
||||
match step {
|
||||
BlendIfStep::Fade(ranges) => {
|
||||
let [red, green, blue, _] = full.to_gamma_srgb_channels();
|
||||
weight *= weigh(ranges, [red, green, blue].map(f64::from));
|
||||
faded = true;
|
||||
}
|
||||
BlendIfStep::NextRun => {
|
||||
*filled = filled.with_alpha(filled.a() * std::mem::replace(&mut weight, 1.) as f32);
|
||||
*full = *filled;
|
||||
}
|
||||
}
|
||||
}
|
||||
*filled = filled.with_alpha(filled.a() * weight as f32);
|
||||
faded
|
||||
};
|
||||
|
||||
// The color at full strength, which each paint overlay blends with, and the color the fill fades, which it paints over at full strength
|
||||
let (mut full, mut filled) = (color, color.with_alpha(color.a() * fill));
|
||||
|
||||
// Once a Blend If fades them, adjustments keep the colors empty where they're empty, as the renderers keep empty pixels
|
||||
let mut faded = false;
|
||||
for (index, adjustment) in adjustments.iter().enumerate() {
|
||||
faded |= take_steps(&mut full, &mut filled, index);
|
||||
|
||||
let Adjustment::ColorOverlay { color: paint, blend_mode, opacity } = *adjustment else {
|
||||
(full, filled) = (adjust(index, full), adjust(index, filled));
|
||||
let adjusted = |color: Color| if !faded || color.a() > 0. { adjust(index, color) } else { color };
|
||||
(full, filled) = (adjusted(full), adjusted(filled));
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -64,18 +147,39 @@ fn fill_through(color: Color, adjustments: &[Adjustment], fill: f32, adjust: imp
|
||||
filled = Color::from_gamma_srgb_channels(mix(red, under_red), mix(green, under_green), mix(blue, under_blue), alpha);
|
||||
full = overlay_paint(full, paint, blend_mode, (opacity / 100.) as f32);
|
||||
}
|
||||
take_steps(&mut full, &mut filled, adjustments.len());
|
||||
filled
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` in order on any number of colors with the `fill` fading them, with each one's kernel prepared once.
|
||||
fn prepared(adjustments: &[Adjustment], fill: f32) -> Box<dyn Fn(Color) -> Color> {
|
||||
/// Carries out `adjustments` in order on any number of colors with the `fill` and the `blend_ifs` fading them, with each one's kernel prepared once.
|
||||
fn prepared(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> Box<dyn Fn(Color) -> Color> {
|
||||
let kernels: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
if fill >= 1. {
|
||||
if fill >= 1. && blend_ifs.is_empty() {
|
||||
return Box::new(move |color| kernels.iter().fold(color, |color, kernel| kernel.adjust(color)));
|
||||
}
|
||||
|
||||
let adjustments = adjustments.to_vec();
|
||||
Box::new(move |color| fill_through(color, &adjustments, fill, |index, color| kernels[index].adjust(color)))
|
||||
let (adjustments, blend_ifs) = (adjustments.to_vec(), blend_ifs.to_vec());
|
||||
Box::new(move |color| fill_through(color, &adjustments, &blend_ifs, fill, |index, color| kernels[index].adjust(color), ChannelRanges::weight))
|
||||
}
|
||||
|
||||
/// Tells apart the colors each channel's range of each of the `blend_ifs` shows fully, partly, or not at all, as it reads them where [`fill_through`] fades by it.
|
||||
fn blend_if_regions(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> impl Fn(Color) -> u64 {
|
||||
let kernels: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
let (adjustments, blend_ifs) = (adjustments.to_vec(), blend_ifs.to_vec());
|
||||
|
||||
// Each channel's state (hidden, partly shown, or shown) is a digit in base 3, so up to ten Blend Ifs stay apart exactly
|
||||
move |color| {
|
||||
let mut region = 0_u64;
|
||||
let weigh = |ranges: &ChannelRanges, channels: [f64; 3]| {
|
||||
for weight in ranges.channel_weights(channels) {
|
||||
let state = u64::from(weight > 0.) + u64::from(weight >= 1.);
|
||||
region = region.wrapping_mul(3).wrapping_add(state);
|
||||
}
|
||||
ranges.weight(channels)
|
||||
};
|
||||
fill_through(color, &adjustments, &blend_ifs, fill, |index, color| kernels[index].adjust(color), weigh);
|
||||
region
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient with `adjustments` carried out along its ramp, with the settings to read the result with, or `None` if there are no adjustments.
|
||||
@@ -83,17 +187,28 @@ fn prepared(adjustments: &[Adjustment], fill: f32) -> Box<dyn Fn(Color) -> Color
|
||||
/// A stepped ramp holds each stop's color, so adjusting the stops is exact. Elsewhere an adjustment can bend the ramp between stops,
|
||||
/// so the adjusted ramp is resampled into stops that interpolate linearly in gamma.
|
||||
pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjustments: &[Adjustment], fill: f32) -> Option<(Gradient, GradientSettings)> {
|
||||
if adjustments.is_empty() {
|
||||
adjusted_gradient_with_blend_ifs(gradient, settings, adjustments, &[], fill)
|
||||
}
|
||||
|
||||
/// Like [`adjusted_gradient`], with the `blend_ifs` also fading the ramp as [`filled_color_with_blend_ifs`] fades a color, or `None` if there are neither adjustments nor Blend Ifs.
|
||||
pub fn adjusted_gradient_with_blend_ifs(
|
||||
gradient: &Gradient,
|
||||
settings: GradientSettings,
|
||||
adjustments: &[Adjustment],
|
||||
blend_ifs: &[(usize, BlendIfStep)],
|
||||
fill: f32,
|
||||
) -> Option<(Gradient, GradientSettings)> {
|
||||
if adjustments.is_empty() && blend_ifs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// A gradient without stops reads as black, so its adjusted ramp is one stop of the adjusted black
|
||||
if gradient.is_empty() {
|
||||
return Some((Gradient::from(vec![prepared(adjustments, fill)(Color::BLACK)]), settings));
|
||||
return Some((Gradient::from(vec![prepared(adjustments, blend_ifs, fill)(Color::BLACK)]), settings));
|
||||
}
|
||||
|
||||
if settings.interpolation == GradientInterpolation::Stepped {
|
||||
let adjust = prepared(adjustments, fill);
|
||||
let adjust = prepared(adjustments, blend_ifs, fill);
|
||||
return Some((gradient.map_colors(|color| adjust(*color)), settings));
|
||||
}
|
||||
|
||||
@@ -102,6 +217,16 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
|
||||
gradient.cache_hash(&mut hasher);
|
||||
settings.cache_hash(&mut hasher);
|
||||
adjustments.iter().for_each(|adjustment| adjustment.cache_hash(&mut hasher));
|
||||
for (before, step) in blend_ifs {
|
||||
hasher.write_usize(*before);
|
||||
match step {
|
||||
BlendIfStep::Fade(ranges) => {
|
||||
hasher.write_u8(0);
|
||||
ranges.cache_hash(&mut hasher);
|
||||
}
|
||||
BlendIfStep::NextRun => hasher.write_u8(1),
|
||||
}
|
||||
}
|
||||
hasher.write_u32(fill.to_bits());
|
||||
let key = hasher.finish();
|
||||
|
||||
@@ -114,7 +239,11 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
|
||||
return Some(result);
|
||||
}
|
||||
|
||||
let resampled = gradient.map_ramp(settings, prepared(adjustments, fill));
|
||||
// A Blend If cuts the ramp off wherever the colors it reads cross its ranges, which may lie between the resampling's probes
|
||||
let resampled = match blend_ifs.is_empty() {
|
||||
true => gradient.map_ramp(settings, prepared(adjustments, blend_ifs, fill)),
|
||||
false => gradient.map_ramp_by_regions(settings, prepared(adjustments, blend_ifs, fill), blend_if_regions(adjustments, blend_ifs, fill)),
|
||||
};
|
||||
let resampled_settings = GradientSettings {
|
||||
space: GradientSpace::RgbGamma,
|
||||
interpolation: GradientInterpolation::Linear,
|
||||
@@ -129,29 +258,84 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust
|
||||
Some((resampled, resampled_settings))
|
||||
}
|
||||
|
||||
/// The color with the adjustments among its effects carried out and the effects consumed, for nodes that read the color.
|
||||
/// Whether [`color_after_effects`] and [`gradient_after_effects`] carry out every one of the effects, since each changes every color on its own:
|
||||
/// an adjustment, a Blend If reading only the value's own colors, or an effect that changes nothing.
|
||||
pub fn carries_out_every_effect(effects: &Effects) -> bool {
|
||||
effects.operations().all(|operation| match operation {
|
||||
EffectOperation::Adjustment(_) => true,
|
||||
EffectOperation::BlendIf(ranges) => ranges.underlying.show_everything(),
|
||||
_ => operation.changes_nothing(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
|
||||
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
|
||||
filled_color_after_effects(color, effects, 1.)
|
||||
}
|
||||
|
||||
/// Like [`color_after_effects`], carried out over the color faded by a `fill`, which leaves the paint overlays among them at full strength, as the renderers fade content.
|
||||
pub fn filled_color_after_effects(color: Color, effects: &Effects, fill: f32) -> Color {
|
||||
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), fill)
|
||||
}
|
||||
|
||||
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
|
||||
pub fn prepared_color_after_effects(effects: &Effects) -> Box<dyn Fn(Color) -> Color> {
|
||||
prepared(&adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||
}
|
||||
|
||||
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
|
||||
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
|
||||
filled_gradient_after_effects(gradient, settings, effects, 1.)
|
||||
}
|
||||
|
||||
/// Like [`gradient_after_effects`], carried out along the ramp faded by a `fill` as [`filled_color_after_effects`] carries them out on a color.
|
||||
pub fn filled_gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects, fill: f32) -> Option<(Gradient, GradientSettings)> {
|
||||
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), fill)
|
||||
}
|
||||
|
||||
/// The color with its effects carried out as [`color_after_effects`] does and consumed, though not its opacity (see [`evaluate_color_parameter`]).
|
||||
/// A color without the effects attribute is returned as it is.
|
||||
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
||||
let Some(adjustments) = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments) else {
|
||||
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
|
||||
return item;
|
||||
};
|
||||
|
||||
let mut item = item;
|
||||
*item.element_mut() = adjusted_color(*item.element(), &adjustments);
|
||||
*item.element_mut() = color;
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item
|
||||
}
|
||||
|
||||
/// The gradient with the adjustments among its effects carried out along its ramp and the effects consumed, for nodes that read its colors.
|
||||
/// The color as the renderers show it, for a node reading it as a parameter: its effects carried out over it faded by its fill, then its opacity fading it all, each consumed.
|
||||
/// Every node reading one color goes through this, so those attributes mean the same to all of them.
|
||||
pub fn evaluate_color_parameter(item: Item<Color>) -> Item<Color> {
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
|
||||
let (adjustments, blend_ifs) = item
|
||||
.attribute::<Effects>(ATTR_EFFECTS)
|
||||
.map(|effects| (adjustments(effects), content_blend_ifs(effects)))
|
||||
.unwrap_or_default();
|
||||
|
||||
let shown = filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill);
|
||||
let mut item = item;
|
||||
*item.element_mut() = shown.with_alpha(shown.a() * opacity);
|
||||
|
||||
// Consumed so a node passing the item on doesn't get them carried out twice where it's drawn
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item.remove_attribute::<f64>(ATTR_OPACITY);
|
||||
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
|
||||
item
|
||||
}
|
||||
|
||||
/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors.
|
||||
/// A gradient without the effects attribute is returned as it is.
|
||||
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
||||
let Some(adjustments) = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments) else {
|
||||
return item;
|
||||
};
|
||||
let Some(effects) = item.attribute::<Effects>(ATTR_EFFECTS) else { return item };
|
||||
let settings = GradientSettings::from_item_attributes(&item);
|
||||
let adjusted = gradient_after_effects(item.element(), settings, effects);
|
||||
|
||||
let mut item = item;
|
||||
let settings = match adjusted_gradient(item.element(), settings, &adjustments, 1.) {
|
||||
let settings = match adjusted {
|
||||
Some((gradient, adjusted_settings)) => {
|
||||
*item.element_mut() = gradient;
|
||||
adjusted_settings
|
||||
@@ -180,6 +364,16 @@ mod tests {
|
||||
actual.iter().zip(expected).all(|(actual, expected)| (actual - expected).abs() < 1e-4)
|
||||
}
|
||||
|
||||
/// The `element` with each row stamped on it while it's placed by the row's scale, so a row stamped at a new scale starts a run of its own.
|
||||
fn stamped<T>(element: T, rows: &[(EffectOperation, f64)]) -> Item<T> {
|
||||
let mut item = Item::new_from_element(element);
|
||||
for (operation, scale) in rows {
|
||||
item.set_attribute(core_types::ATTR_TRANSFORM, glam::DAffine2::from_scale(glam::DVec2::splat(*scale)));
|
||||
graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation));
|
||||
}
|
||||
item
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlays_mix_in_gamma_unfaded_by_the_fill() {
|
||||
let half_white = [Adjustment::ColorOverlay {
|
||||
@@ -198,6 +392,177 @@ mod tests {
|
||||
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_parameters_fill_fades_it_beneath_its_paint_overlays_and_its_opacity_over_them() {
|
||||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let unfilled = Item::new_from_element(Color::BLACK)
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([red]))
|
||||
.with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||||
|
||||
assert!(close(gamma(*evaluate_color_parameter(unfilled.clone()).element()), [1., 0., 0., 1.]));
|
||||
assert!(close(gamma(*evaluate_color_parameter(unfilled.with_attribute(ATTR_OPACITY, 0.5_f64)).element()), [1., 0., 0., 0.5]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
|
||||
// Shown only where the gray is at least half
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
|
||||
let invert = EffectOperation::Adjustment(Adjustment::Invert);
|
||||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let black_through = |operations: Vec<EffectOperation>| evaluate_color_effects(Item::new_from_element(Color::BLACK).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations)));
|
||||
|
||||
// Black is hidden, whether inverted after the Blend If reads it or not, but shows once inverted before
|
||||
assert_eq!(black_through(vec![blend_if.clone()]).element().a(), 0.);
|
||||
assert_eq!(black_through(vec![blend_if.clone(), invert.clone()]).element().a(), 0.);
|
||||
assert!(close(gamma(*black_through(vec![invert, blend_if.clone()]).element()), [1.; 4]));
|
||||
|
||||
// An overlay after it paints over the hidden color at full strength, as over a fill of none, and the effects are consumed
|
||||
let overlaid = black_through(vec![blend_if.clone(), red]);
|
||||
assert!(close(gamma(*overlaid.element()), [1., 0., 0., 1.]));
|
||||
assert!(overlaid.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||
|
||||
// A gradient's dark start is hidden and its light end shown
|
||||
let gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_EFFECTS, Effects::from_operations([blend_if]));
|
||||
let evaluated = evaluate_gradient_effects(gradient);
|
||||
let settings = GradientSettings::from_item_attributes(&evaluated);
|
||||
assert!(evaluated.element().evaluate(0., settings).a() < 1e-6);
|
||||
assert!(close(gamma(evaluated.element().evaluate(1., settings)), [1.; 4]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consumed_values_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_it_leave_it() {
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
|
||||
// Shown only where the gray is at least half
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
|
||||
let overlay = |color: Color| {
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
})
|
||||
};
|
||||
|
||||
// White painted blue is read as blue by a Blend If after a scale, which hides it, but in the same run the Blend If reads the white beneath the overlay
|
||||
let color_through = |color: Color, rows: &[(EffectOperation, f64)]| *evaluate_color_effects(stamped(color, rows)).element();
|
||||
assert_eq!(color_through(Color::WHITE, &[(overlay(Color::BLUE), 1.), (blend_if.clone(), 2.)]).a(), 0.);
|
||||
assert!(close(gamma(color_through(Color::WHITE, &[(overlay(Color::BLUE), 1.), (blend_if.clone(), 1.)])), [0., 0., 1., 1.]));
|
||||
|
||||
// Black hidden before a scale leaves nothing for an overlay after it to paint within
|
||||
assert_eq!(color_through(Color::BLACK, &[(blend_if.clone(), 1.), (overlay(Color::RED), 2.)]).a(), 0.);
|
||||
assert!(close(gamma(color_through(Color::BLACK, &[(blend_if.clone(), 1.), (overlay(Color::RED), 1.)])), [1., 0., 0., 1.]));
|
||||
|
||||
// A ramp painted blue is hidden all along by a Blend If after a scale
|
||||
let ramp = stamped(Gradient::from(vec![Color::BLACK, Color::WHITE]), &[(overlay(Color::BLUE), 1.), (blend_if, 2.)]);
|
||||
let evaluated = evaluate_gradient_effects(ramp);
|
||||
let settings = GradientSettings::from_item_attributes(&evaluated);
|
||||
for t in [0., 0.25, 0.75, 1.] {
|
||||
let shown = evaluated.element().evaluate(t, settings);
|
||||
assert!(shown.a() < 1e-6, "hidden at {t}: {:?}", gamma(shown));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_a_blend_if_hides_stay_hidden_through_adjustments_raising_alpha_as_rasters_do() {
|
||||
use crate::raster_effects::{evaluate_raster_effects, premultiplied_gamma_channels};
|
||||
use graphic_types::EffectKind;
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
use raster_types::{Image, Raster};
|
||||
|
||||
// Shown only where the gray is at least half
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
|
||||
let make_opaque = EffectOperation::default_for(EffectKind::MakeOpaque);
|
||||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
|
||||
// Black consumed as a color, which agrees with a raster's pixel of it
|
||||
let black_through = |name: &str, rows: &[(EffectOperation, f64)]| {
|
||||
let color = *evaluate_color_effects(stamped(Color::BLACK, rows)).element();
|
||||
let raster = evaluate_raster_effects(stamped(Raster::new_cpu(Image::new(1, 1, Color::BLACK)), rows));
|
||||
let pixel = raster.element().data.first().copied().unwrap_or(Color::TRANSPARENT);
|
||||
let (color_channels, pixel_channels) = (premultiplied_gamma_channels(color), premultiplied_gamma_channels(pixel));
|
||||
assert!(close(color_channels, pixel_channels), "black {name}: {color_channels:?} vs the raster's {pixel_channels:?}");
|
||||
color
|
||||
};
|
||||
|
||||
// Hidden black stays hidden when made opaque, in its run or the next, where an overlay finds nothing to paint within either
|
||||
let hidden = [
|
||||
("made opaque", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 1.)]),
|
||||
("made opaque in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.)]),
|
||||
("made opaque and painted in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.), (red.clone(), 2.)]),
|
||||
];
|
||||
for (name, rows) in hidden {
|
||||
assert_eq!(black_through(name, &rows).a(), 0., "black {name}");
|
||||
}
|
||||
|
||||
// In its own run, an overlay still paints within the full-strength black
|
||||
let painted = black_through("made opaque and painted", &[(blend_if.clone(), 1.), (make_opaque.clone(), 1.), (red, 1.)]);
|
||||
assert!(close(gamma(painted), [1., 0., 0., 1.]), "{:?}", gamma(painted));
|
||||
|
||||
// A ramp made opaque stays hidden where it's dark, in the Blend If's run or the next
|
||||
for scale in [1., 2.] {
|
||||
let ramp = stamped(Gradient::from(vec![Color::BLACK, Color::WHITE]), &[(blend_if.clone(), 1.), (make_opaque.clone(), scale)]);
|
||||
let evaluated = evaluate_gradient_effects(ramp);
|
||||
let settings = GradientSettings::from_item_attributes(&evaluated);
|
||||
for (t, alpha) in [(0., 0.), (0.25, 0.), (0.75, 1.), (1., 1.)] {
|
||||
let shown = evaluated.element().evaluate(t, settings).a();
|
||||
assert!((shown - alpha).abs() < 1e-6, "the alpha at {t} with the scale {scale} is {shown}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ramp_keeps_the_band_a_blend_if_shows_between_where_resampling_probes_it() {
|
||||
use graphic_types::blend_if::{BlendIfRanges, BlendRange};
|
||||
|
||||
// Shown only where the gray lies from 30% to 40%, which neither end of the ramp nor any of its quarter points lands within
|
||||
let mut band = BlendIfRanges::default();
|
||||
band.content.gray = BlendRange {
|
||||
falloff_start: 30.,
|
||||
range_start: 30.,
|
||||
range_end: 40.,
|
||||
falloff_end: 40.,
|
||||
};
|
||||
let effects = Effects::from_operations([EffectOperation::BlendIf(Box::new(band))]);
|
||||
let gamma_settings = GradientSettings {
|
||||
space: GradientSpace::RgbGamma,
|
||||
interpolation: GradientInterpolation::Linear,
|
||||
..Default::default()
|
||||
};
|
||||
let (resampled, settings) = gradient_after_effects(&Gradient::from(vec![Color::BLACK, Color::WHITE]), gamma_settings, &effects).expect("the Blend If fades the ramp");
|
||||
|
||||
// The band shows its own grays from level 77 to 102, which lie from 30% to just past 40% along the ramp, with sharp edges
|
||||
for t in [0.301, 0.35, 0.4] {
|
||||
let shown = resampled.evaluate(t, settings);
|
||||
assert!(close(gamma(shown), [t as f32, t as f32, t as f32, 1.]), "the band shows at {t}: {:?}", gamma(shown));
|
||||
}
|
||||
for t in [0., 0.25, 0.299, 0.403, 0.5, 0.75, 1.] {
|
||||
assert!(resampled.evaluate(t, settings).a() < 1e-6, "hidden at {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_without_stops_adjusts_the_black_it_reads_as() {
|
||||
let empty = Gradient::from(Vec::<Color>::new());
|
||||
|
||||
@@ -312,6 +312,29 @@ mod cpu {
|
||||
}
|
||||
}
|
||||
|
||||
/// An image's pixels as it's drawn, with its effects and fill carried out on its own pixel grid.
|
||||
/// A node input of this type has the compiler read them back from the image wired into it, which carries its effects as attributes until then.
|
||||
#[derive(Clone, Debug, Default, PartialEq, DynAny, core_types::CacheHash)]
|
||||
pub struct Pixels(Raster<CPU>);
|
||||
|
||||
impl Pixels {
|
||||
pub fn new(raster: Raster<CPU>) -> Self {
|
||||
Self(raster)
|
||||
}
|
||||
|
||||
pub fn into_raster(self) -> Raster<CPU> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for Pixels {
|
||||
type Target = Image<Color>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
self.0.data()
|
||||
}
|
||||
}
|
||||
|
||||
pub use gpu::GPU;
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub use gpu::{Texture, TextureWeakRef};
|
||||
|
||||
@@ -34,6 +34,7 @@ log = { workspace = true }
|
||||
num-traits = { workspace = true }
|
||||
usvg = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
linesweeper = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
//! 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 at all is drawn as an image of it in place of its 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, render_raster_cpu_image_svg};
|
||||
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};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::transform::Footprint;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
use kurbo::{Affine, BezPath};
|
||||
use std::sync::Arc;
|
||||
use vello_gpu::peniko::Fill;
|
||||
|
||||
/// The most pixels across or down a map or image may have.
|
||||
pub const MAX_DEFERRED_IMAGE_PIXELS: u32 = 8192;
|
||||
@@ -183,13 +187,12 @@ pub fn substitute_effect_map(svg: &mut String, placement: &EffectMapPlacement, m
|
||||
svg.replace_range(span, &image);
|
||||
}
|
||||
|
||||
/// One item of content an SVG draws as an image the GPU renders of it, since its effects hold one SVG filters can't carry out.
|
||||
/// Content an SVG draws as an image the GPU renders of it, since SVG can't carry it out as markup.
|
||||
#[derive(Clone)]
|
||||
pub struct DeferredImage {
|
||||
/// Names the markers around the content's own markup in the SVG, which the image replaces.
|
||||
pub id: u64,
|
||||
/// The item with its effects, but without its opacity and blend mode, which the image takes instead.
|
||||
pub content: Graphic,
|
||||
pub content: DeferredContent,
|
||||
pub render_params: RenderParams,
|
||||
/// Maps the user space the markers sit in into the document.
|
||||
pub user_to_document: DAffine2,
|
||||
@@ -199,6 +202,69 @@ pub struct DeferredImage {
|
||||
pub margin: f64,
|
||||
pub opacity: f32,
|
||||
pub blend_mode: BlendMode,
|
||||
/// The reference for the mask fading the image by Blend If's ranges of what lies beneath, if any.
|
||||
pub mask: Option<String>,
|
||||
}
|
||||
|
||||
/// 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 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.
|
||||
Beneath { clip: Option<BezPath>, drawn: Vec<DrawnContent> },
|
||||
}
|
||||
|
||||
/// Content an SVG draws, which the GPU draws again into images of what lies beneath content drawn after it.
|
||||
#[derive(Clone)]
|
||||
pub struct DrawnContent {
|
||||
items: Arc<dyn DrawnItems>,
|
||||
/// How many of the items are drawn, since content drawn among them lies over only those before it.
|
||||
pub(crate) count: usize,
|
||||
/// Maps the user space the items are drawn in into the document.
|
||||
user_to_document: DAffine2,
|
||||
render_params: RenderParams,
|
||||
}
|
||||
|
||||
impl DrawnContent {
|
||||
/// The `items` drawn in a user space that `user_to_document` maps into the document, none of them drawn yet.
|
||||
pub(crate) fn new(items: Arc<dyn DrawnItems>, user_to_document: DAffine2, render_params: &RenderParams) -> Self {
|
||||
Self {
|
||||
items,
|
||||
count: 0,
|
||||
user_to_document,
|
||||
render_params: render_params.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A list of graphical content, or one item of it, whose first items the GPU can draw.
|
||||
pub(crate) trait DrawnItems: Send + Sync {
|
||||
/// Draws the first `count` items into a scene of the document, from the user space that `transform` maps into it.
|
||||
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams);
|
||||
}
|
||||
|
||||
impl<T: Clone + Send + Sync + 'static> DrawnItems for List<T>
|
||||
where
|
||||
List<T>: Render,
|
||||
{
|
||||
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
||||
if count >= self.len() {
|
||||
return self.render_to_vello(scene, transform, render_params);
|
||||
}
|
||||
|
||||
let first: List<T> = (0..count).filter_map(|index| self.clone_item(index)).collect();
|
||||
first.render_to_vello(scene, transform, render_params);
|
||||
}
|
||||
}
|
||||
|
||||
impl DrawnItems for Graphic {
|
||||
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
||||
if count > 0 {
|
||||
self.render_to_vello(scene, transform, render_params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an SVG draws the image the GPU rendered of an item of deferred content.
|
||||
@@ -212,6 +278,7 @@ pub struct DeferredImagePlacement {
|
||||
pub user_to_document: DAffine2,
|
||||
pub opacity: f32,
|
||||
pub blend_mode: BlendMode,
|
||||
pub mask: Option<String>,
|
||||
/// Whether the image is drawn to a canvas rather than embedded in the SVG.
|
||||
pub to_canvas: bool,
|
||||
/// Screen pixels per document unit, which sizes an image drawn to a canvas.
|
||||
@@ -225,9 +292,22 @@ pub struct DeferredImageLayout {
|
||||
pub size: UVec2,
|
||||
}
|
||||
|
||||
/// The starts of the markers around the markup standing in for an item of deferred content, which its ID and `-->` follow.
|
||||
pub(crate) const DEFERRED_IMAGE_OPENING: &str = "<!--deferred-image-";
|
||||
pub(crate) const DEFERRED_IMAGE_CLOSING: &str = "<!--/deferred-image-";
|
||||
|
||||
/// The starts of the markers around a copy of that markup in a Blend If mask, which can't draw the canvas of its image, followed by its ID, a hyphen and the key color's hex (for the opening), and `-->`.
|
||||
pub(crate) const DEFERRED_COVER_OPENING: &str = "<!--deferred-cover-";
|
||||
pub(crate) const DEFERRED_COVER_CLOSING: &str = "<!--/deferred-cover-";
|
||||
|
||||
/// The markers that open and close the markup standing in for the item of deferred content `id` names.
|
||||
pub(crate) fn image_markers(id: u64) -> (String, String) {
|
||||
(format!("<!--deferred-image-{id}-->"), format!("<!--/deferred-image-{id}-->"))
|
||||
(format!("{DEFERRED_IMAGE_OPENING}{id}-->"), format!("{DEFERRED_IMAGE_CLOSING}{id}-->"))
|
||||
}
|
||||
|
||||
/// Whether the `markup` holds markers of markup standing in for an item of deferred content.
|
||||
pub(crate) fn holds_image_markers(markup: &str) -> bool {
|
||||
markup.contains(DEFERRED_IMAGE_OPENING)
|
||||
}
|
||||
|
||||
impl DeferredImage {
|
||||
@@ -242,6 +322,7 @@ impl DeferredImage {
|
||||
user_to_document: self.user_to_document,
|
||||
opacity: self.opacity,
|
||||
blend_mode: self.blend_mode,
|
||||
mask: self.mask.clone(),
|
||||
to_canvas: self.render_params.to_canvas(),
|
||||
canvas_image_scale: self.render_params.canvas_image_scale,
|
||||
},
|
||||
@@ -252,8 +333,25 @@ impl DeferredImage {
|
||||
|
||||
/// Draws the content with its effects into a scene of the document, which the `layout` places in the image's pixels.
|
||||
pub fn draw(&self, scene: &mut VelloSceneBuilder, layout: &DeferredImageLayout) {
|
||||
self.content
|
||||
.render_to_vello(scene, self.user_to_document, &image_render_params(&self.render_params, layout.document_to_pixels, layout.size));
|
||||
let image_params = |render_params: &RenderParams| image_render_params(render_params, layout.document_to_pixels, layout.size);
|
||||
|
||||
match &self.content {
|
||||
DeferredContent::Item(content) => content.render_to_vello(scene, self.user_to_document, &image_params(&self.render_params)),
|
||||
DeferredContent::Beneath { clip, drawn } => {
|
||||
// A clip rather than a layer, within which content reading what lies beneath it would find nothing
|
||||
if let Some(clip) = clip {
|
||||
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, clip);
|
||||
}
|
||||
|
||||
for drawn in drawn {
|
||||
drawn.items.draw_first(drawn.count, scene, drawn.user_to_document, &image_params(&drawn.render_params));
|
||||
}
|
||||
|
||||
if clip.is_some() {
|
||||
scene.pop_layer();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -272,11 +370,41 @@ pub fn substitute_deferred_image(svg: &mut String, image_data: &mut Vec<(u64, Ca
|
||||
canvas_image_scale: placement.canvas_image_scale,
|
||||
..Default::default()
|
||||
};
|
||||
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
|
||||
let opacity = if placement.opacity < 1. { format!(r#" opacity="{}""#, placement.opacity) } else { String::new() };
|
||||
let style = if placement.blend_mode != BlendMode::Normal {
|
||||
format!(r#" style="{}""#, placement.blend_mode.render())
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let markup = render.svg.to_svg_string();
|
||||
// A mask goes on a group taking the image's opacity and blend mode, which still blends with what lies beneath
|
||||
let markup = match &placement.mask {
|
||||
Some(mask) => {
|
||||
render_raster_cpu_image_svg(image, placement.transform, 1., BlendMode::Normal, &mut render, &render_params);
|
||||
format!(r#"<g mask="{mask}"{opacity}{style}>{}</g>"#, render.svg.to_svg_string())
|
||||
}
|
||||
None => {
|
||||
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
|
||||
render.svg.to_svg_string()
|
||||
}
|
||||
};
|
||||
while let Some(span) = marked_span(svg, &opening, &closing) {
|
||||
svg.replace_range(span, &markup);
|
||||
}
|
||||
image_data.extend(render.image_data);
|
||||
|
||||
// A Blend If mask can't draw the canvas in its copy of what lies beneath, so a rectangle of the color its ranges show in full covers the image there
|
||||
if placement.to_canvas {
|
||||
let (opening, closing) = (format!("{DEFERRED_COVER_OPENING}{}-", placement.id), format!("{DEFERRED_COVER_CLOSING}{}-->", placement.id));
|
||||
let transform = format_transform_matrix(placement.transform);
|
||||
while let Some(start) = svg.find(&opening) {
|
||||
let key_start = start + opening.len();
|
||||
let Some(key_end) = svg[key_start..].find("-->").map(|offset| key_start + offset) else { break };
|
||||
let Some(end) = svg[key_end..].find(&closing).map(|offset| key_end + offset + closing.len()) else {
|
||||
break;
|
||||
};
|
||||
let cover = format!(r##"<rect width="1" height="1" transform="{transform}" fill="#{}"{opacity}{style} />"##, &svg[key_start..key_end]);
|
||||
svg.replace_range(start..end, &cover);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@ pub mod convert_usvg_path;
|
||||
pub mod deferred_image;
|
||||
pub mod render_ext;
|
||||
mod renderer;
|
||||
mod svg_backdrop;
|
||||
mod svg_blend_if;
|
||||
mod svg_layer_blend;
|
||||
pub mod to_peniko;
|
||||
pub mod vello_scene_builder;
|
||||
|
||||
|
||||
@@ -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, paint_draws_by_its_colors, 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,26 +86,35 @@ 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.
|
||||
/// `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> {
|
||||
/// 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_fill_and_opacity`] explains.
|
||||
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 (stops, settings, paint_opacity) = painted_gradient(item, for_mask)?;
|
||||
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.reaches_before_start());
|
||||
with_two_stops_at_least(shape, &mut samples);
|
||||
|
||||
let paint_opacity = item.paint_opacity(for_mask);
|
||||
if paint_opacity < 1. {
|
||||
for (_, color, _) in &mut samples {
|
||||
*color = color.with_alpha(color.a() * paint_opacity);
|
||||
}
|
||||
}
|
||||
|
||||
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 +147,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 +155,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 +207,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 +217,8 @@ impl RenderExt for List<Gradient> {
|
||||
svg_defs,
|
||||
item_transform,
|
||||
element_transform,
|
||||
stroke_transform,
|
||||
bounds,
|
||||
render_params.for_mask,
|
||||
)
|
||||
}
|
||||
@@ -278,10 +302,11 @@ impl RenderExt for Graphic {
|
||||
target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
let paint_attr = target.paint_attr();
|
||||
let by_colors = paint_draws_by_its_colors(self);
|
||||
|
||||
match self {
|
||||
Graphic::Color(item) => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
||||
Graphic::ColorList(color_list) => color_list.render(
|
||||
Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
||||
Graphic::ColorList(color_list) if by_colors => color_list.render(
|
||||
svg_defs,
|
||||
user_to_document,
|
||||
paint_reach,
|
||||
@@ -292,11 +317,11 @@ 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) if by_colors => 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
|
||||
Graphic::GradientList(gradient_list) if gradient_list.len() <= 1 => gradient_list
|
||||
Graphic::GradientList(gradient_list) if by_colors => gradient_list
|
||||
.render(
|
||||
svg_defs,
|
||||
user_to_document,
|
||||
@@ -311,7 +336,10 @@ impl RenderExt for Graphic {
|
||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
|
||||
Graphic::Graphic(_)
|
||||
Graphic::Color(_)
|
||||
| Graphic::ColorList(_)
|
||||
| Graphic::Gradient(_)
|
||||
| Graphic::Graphic(_)
|
||||
| Graphic::Vector(_)
|
||||
| Graphic::RasterCPU(_)
|
||||
| Graphic::RasterGPU(_)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -96,10 +96,12 @@ impl SvgFilterPrimitives {
|
||||
match *operation {
|
||||
// The Euclidean length of the gradient loses too much precision through the 8-bit results between primitives
|
||||
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
||||
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
|
||||
// No SVG primitive ranks values, and the GPU's median runs on the content's own grid besides
|
||||
EffectOperation::Median { .. } => self.map_showing(capture, image),
|
||||
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
|
||||
EffectOperation::AddNoise { amount, distribution, .. } => self.add_noise(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
||||
EffectOperation::Speckle { amount, distribution, .. } => self.speckle(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
||||
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
|
||||
_ => image.to_string(),
|
||||
}
|
||||
@@ -124,7 +126,7 @@ impl SvgFilterPrimitives {
|
||||
Some(convolution) => native && LatticeKernel::new(&convolution).is_some(),
|
||||
None => matches!(
|
||||
operation,
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Sharpen { .. } | EffectOperation::HighPass { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. }
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Sharpen { .. } | EffectOperation::HighPass { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. }
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -275,9 +277,9 @@ impl SvgFilterPrimitives {
|
||||
self.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), "")
|
||||
}
|
||||
|
||||
/// The image with each straight color offset by the noise in the GPU's map for `capture`, which holds offsets up to `extent` either way around middle gray, matching the GPU's `add_noise`.
|
||||
/// The image with each straight color offset by the noise in the GPU's map for `capture`, which holds offsets up to `extent` either way around middle gray, matching the GPU's `speckle`.
|
||||
/// Until the map is resolved, its middle gray offsets nothing.
|
||||
fn add_noise(&mut self, image: &str, extent: f64, capture: EffectCapture) -> String {
|
||||
fn speckle(&mut self, image: &str, extent: f64, capture: EffectCapture) -> String {
|
||||
let colors = self.opaque_colors(image);
|
||||
let noise = self.map_unresolved_as(capture, Color::from(SRGBA8::new(128, 128, 128, 255)));
|
||||
let attributes = format!(r#"in="{colors}" in2="{noise}" operator="arithmetic" k2="1" k3="{}" k4="{}""#, 2. * extent, -extent);
|
||||
@@ -719,8 +721,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn random_fields_come_from_the_gpu_combined_with_the_live_content() {
|
||||
// Add Noise adds the map's offsets, scaled out from middle gray to their extent, to the opaque colors within the live coverage
|
||||
let noise = EffectOperation::AddNoise {
|
||||
// Speckle adds the map's offsets, scaled out from middle gray to their extent, to the opaque colors within the live coverage
|
||||
let noise = EffectOperation::Speckle {
|
||||
amount: 40.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
@@ -760,13 +762,13 @@ mod tests {
|
||||
use core_types::list::{ATTR_EFFECTS, List};
|
||||
use core_types::transform::Footprint;
|
||||
|
||||
// A color with Add Noise after Levels draws through a filter over the view, with the noise's map and the Levels within it
|
||||
// A color with Speckle after Levels draws through a filter over the view, with the noise's map and the Levels within it
|
||||
let levels = graphic_types::Adjustment::Exposure {
|
||||
exposure: 1.,
|
||||
offset: 0.,
|
||||
gamma_correction: 1.,
|
||||
};
|
||||
let noise = EffectOperation::AddNoise {
|
||||
let noise = EffectOperation::Speckle {
|
||||
amount: 20.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
@@ -800,7 +802,7 @@ mod tests {
|
||||
|
||||
// A gradient mask without a transform lies across the color's own unit square, as on the GPU, rather than across the view
|
||||
let stops = [(0., core_types::Color::BLACK), (1., core_types::Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||||
let noise = EffectOperation::AddNoise {
|
||||
let noise = EffectOperation::Speckle {
|
||||
amount: 20.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
|
||||
@@ -8,7 +8,7 @@ use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effects::{EffectOperation, Effects, spans_along_axes};
|
||||
use graphic_types::masks::{MaskMode, mask_density_line, mask_feather_sigma, masked_radius_blur_weight};
|
||||
use graphic_types::masks::{MASK_LUMINANCE_WEIGHTS, MaskMode, mask_density_line, mask_feather_sigma, masked_radius_blur_weight};
|
||||
use graphic_types::{Appearance, Graphic};
|
||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||
use std::fmt::Write;
|
||||
@@ -98,7 +98,7 @@ pub(super) fn placed(mask: &Graphic, placement: DAffine2) -> Graphic {
|
||||
|
||||
/// Writes into `svg_defs` the masks for the effects in each of the `ranges`, given the markup of the graphics the effects draw with in order, and the content's `bounds` in the user space, which is the effects' own.
|
||||
/// Returns the reference to each range's mask, which shows the content as much as all its masks together do.
|
||||
pub(super) fn write_native_masks(svg_defs: &mut String, effects: &Effects, ranges: [Range<usize>; 2], paints: &[String], bounds: [DVec2; 2]) -> [Option<String>; 2] {
|
||||
pub(super) fn write_native_masks<const N: usize>(svg_defs: &mut String, effects: &Effects, ranges: [Range<usize>; N], paints: &[String], bounds: [DVec2; 2]) -> [Option<String>; N] {
|
||||
let length_scale = DVec2::ONE;
|
||||
let region = svg_effects_region(effects, bounds, length_scale);
|
||||
|
||||
@@ -308,15 +308,19 @@ impl SvgFilterPrimitives {
|
||||
|
||||
/// The `mode`'s coverage of a mask graphic's `image`, in the alpha of the result, matching the GPU's `mask_coverage`.
|
||||
pub(super) fn mask_coverage(&mut self, image: &str, mode: MaskMode) -> String {
|
||||
match mode {
|
||||
// Over black, the luminance of the opaque result is that of the premultiplied channels
|
||||
let luminance = match mode {
|
||||
MaskMode::Luminance => {
|
||||
let black = self.push("feFlood", r#"flood-color="black""#, "");
|
||||
let opaque = self.push("feComposite", &format!(r#"in="{image}" in2="{black}" operator="over""#), "");
|
||||
self.push("feColorMatrix", &format!(r#"in="{opaque}" type="luminanceToAlpha""#), "")
|
||||
let [red, green, blue] = MASK_LUMINANCE_WEIGHTS;
|
||||
format!(r#"type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 {red} {green} {blue} 0 0""#)
|
||||
}
|
||||
MaskMode::Alpha => image.to_string(),
|
||||
}
|
||||
MaskMode::LuminanceSvg => r#"type="luminanceToAlpha""#.to_string(),
|
||||
MaskMode::Alpha => return image.to_string(),
|
||||
};
|
||||
|
||||
// Over black, the luminance of the opaque result is that of the premultiplied channels
|
||||
let black = self.push("feFlood", r#"flood-color="black""#, "");
|
||||
let opaque = self.push("feComposite", &format!(r#"in="{image}" in2="{black}" operator="over""#), "");
|
||||
self.push("feColorMatrix", &format!(r#"in="{opaque}" {luminance}"#), "")
|
||||
}
|
||||
|
||||
/// How much the mask graphic's `image` shows the content, in the alpha of the result, matching the GPU's mask passes.
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
//! What lies beneath content in an SVG, which filters can't read, copied for content that reads it, like a background blur.
|
||||
//! Per the W3C's Backdrop Root, the backdrop is everything drawn before the content since the innermost group that isolates it, or since the start of the render.
|
||||
|
||||
use crate::deferred_image::{self, DeferredContent, DeferredImage, DrawnContent, DrawnItems};
|
||||
use crate::renderer::{RenderParams, SvgRender, SvgSegment, format_transform_matrix};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use graphic_types::{EffectOperation, Effects};
|
||||
use kurbo::{BezPath, PathEl, Shape};
|
||||
use linesweeper::topology::Topology;
|
||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A group an SVG render has open, where the content drawn so far lies beneath what's drawn next inside it.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct OpenGroup {
|
||||
/// Where the group's opening tag starts among the render's segments.
|
||||
pub tag_start: usize,
|
||||
/// Where the group's content starts among the render's segments.
|
||||
pub content_start: usize,
|
||||
/// Whether the group isolates what's drawn inside it from what lies beneath it, as opacity, a filter, a mask, a clip path, or a blend mode does.
|
||||
pub isolates: bool,
|
||||
/// The group's `clip-path` attribute, which a copy of its content takes too.
|
||||
pub clip_path: Option<String>,
|
||||
/// Maps the user space of the group's content into the document, once its content begins.
|
||||
pub user_to_document: Option<DAffine2>,
|
||||
/// Whether a copy of what lies beneath, or an image of it, is drawn inside the group so far.
|
||||
pub holds_backdrop: bool,
|
||||
/// The content drawn directly inside the group so far, for the GPU to draw again in an image of what lies beneath content drawn after it.
|
||||
pub drawn: Vec<DrawnContent>,
|
||||
}
|
||||
|
||||
impl OpenGroup {
|
||||
pub fn new(tag_start: usize, content_start: usize, isolates: bool, clip_path: Option<String>) -> Self {
|
||||
Self {
|
||||
tag_start,
|
||||
content_start,
|
||||
isolates,
|
||||
clip_path,
|
||||
user_to_document: None,
|
||||
holds_backdrop: false,
|
||||
drawn: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The groups an SVG render has open, from the render's own start inward to the innermost.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct OpenGroups {
|
||||
pub groups: Vec<OpenGroup>,
|
||||
/// Whether the attributes of the tag being opened isolate its content.
|
||||
pub opening_isolates: bool,
|
||||
/// The `clip-path` attribute of the tag being opened.
|
||||
pub opening_clip_path: Option<String>,
|
||||
/// Whether the render draws a clipping base's clip.
|
||||
pub clip: bool,
|
||||
/// The shapes of the clip paths in the render's defs, paths in the document each filled by the nonzero rule, by the `clip-path` attribute referencing each.
|
||||
/// Images of what lies beneath inside one are cut to the union of its shapes.
|
||||
pub clip_shapes: HashMap<String, Vec<BezPath>>,
|
||||
}
|
||||
|
||||
impl Default for OpenGroups {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
groups: vec![OpenGroup::new(0, 0, true, None)],
|
||||
opening_isolates: false,
|
||||
opening_clip_path: None,
|
||||
clip: false,
|
||||
clip_shapes: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an attribute makes the element carrying it an isolated group, which the content inside it blends within.
|
||||
pub(crate) fn isolates(name: &str, value: &str) -> bool {
|
||||
match name {
|
||||
"opacity" | "filter" | "mask" | "clip-path" => true,
|
||||
"style" => value.contains("mix-blend-mode") || value.contains("isolation"),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
impl SvgRender {
|
||||
/// Records the `items` drawn next, from the user space `user_to_document` maps into the document, in the innermost open group, returning where for [`Self::drew_items`].
|
||||
/// Nothing is recorded where no image can replace markup, since no image of what lies beneath could.
|
||||
pub(crate) fn record_drawn<T: DrawnItems + 'static>(&mut self, items: impl FnOnce() -> T, user_to_document: DAffine2, render_params: &RenderParams) -> Option<usize> {
|
||||
if !self.images_replace_markup(render_params) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let group = self.open_groups.groups.last_mut()?;
|
||||
group.drawn.push(DrawnContent::new(Arc::new(items()), user_to_document, render_params));
|
||||
Some(group.drawn.len() - 1)
|
||||
}
|
||||
|
||||
/// Notes that the first `count` of the items recorded at `record` are drawn, in place of anything recorded after them while they were drawn.
|
||||
pub(crate) fn drew_items(&mut self, record: Option<usize>, count: usize) {
|
||||
let (Some(record), Some(group)) = (record, self.open_groups.groups.last_mut()) else { return };
|
||||
|
||||
group.drawn.truncate(record + 1);
|
||||
if let Some(drawn) = group.drawn.get_mut(record) {
|
||||
drawn.count = count;
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the `shapes` of the clip path a `clip-path` attribute of the `reference` cuts by (see [`OpenGroups::clip_shapes`]), for images of what lies beneath inside it.
|
||||
pub(crate) fn record_clip_shapes(&mut self, reference: &str, shapes: impl FnOnce() -> Vec<BezPath>, render_params: &RenderParams) {
|
||||
if self.images_replace_markup(render_params) {
|
||||
self.open_groups.clip_shapes.insert(reference.to_string(), shapes());
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline of the clip path a `clip-path` attribute of the `reference` cuts by, its shapes united into one path filled by the nonzero rule,
|
||||
/// or `None` if its shapes aren't recorded or can't be united.
|
||||
fn clip_outline(&mut self, reference: &str) -> Option<BezPath> {
|
||||
let shapes = self.open_groups.clip_shapes.get(reference)?;
|
||||
if let [shape] = shapes.as_slice() {
|
||||
return Some(shape.clone());
|
||||
}
|
||||
|
||||
// United once, the outline is kept in place of the shapes, which are forgotten if they can't be
|
||||
let outline = united_outline(shapes);
|
||||
match &outline {
|
||||
Some(outline) => _ = self.open_groups.clip_shapes.insert(reference.to_string(), vec![outline.clone()]),
|
||||
None => _ = self.open_groups.clip_shapes.remove(reference),
|
||||
}
|
||||
outline
|
||||
}
|
||||
|
||||
/// Markup showing what lies beneath the content drawn next, within the `region` of the current user space it reads, or `None` if nothing does.
|
||||
/// It copies the markup drawn since the backdrop root, or where that holds a copy already, stands for an image the GPU renders of it or else leaves held copies out.
|
||||
/// The image is embedded `for_mask`, since a mask can't render canvases.
|
||||
pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64, for_mask: bool) -> Option<BackdropCopy> {
|
||||
let root = self.backdrop_root()?;
|
||||
|
||||
// The backdrop root's own clip cuts every level's copy as it cuts the originals, from a group around them in the space of its content
|
||||
let root_group = &self.open_groups.groups[root];
|
||||
let holds_backdrop = root_group.holds_backdrop;
|
||||
let clip = root_group.clip_path.clone().zip(root_group.user_to_document);
|
||||
let copies_to_document = clip.as_ref().map_or(self.transform, |(_, root_to_document)| *root_to_document);
|
||||
|
||||
// In the viewport, images draw to canvases in `<foreignObject>` elements, which a mask can't render, so a mask reads the GPU's image of what lies beneath instead, as later readers do
|
||||
let draws_canvases = self.draws_canvases_since(root, render_params);
|
||||
let images = holds_backdrop || (for_mask && draws_canvases);
|
||||
|
||||
// An image needs the outline of the root's clip, if it has one, to cut what it holds by
|
||||
let image_clip = match images && self.images_replace_markup(render_params) {
|
||||
true => match &clip {
|
||||
Some((reference, _)) => self.clip_outline(reference).map(Some),
|
||||
None => Some(None),
|
||||
},
|
||||
false => None,
|
||||
};
|
||||
|
||||
// Elsewhere, copies leave out the blurred copies earlier content holds, so they never nest, losing only the blur of a blur where it overlaps
|
||||
let image = images && image_clip.is_some();
|
||||
let copies = match (images, image_clip) {
|
||||
(false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas() || draws_canvases, false),
|
||||
(true, Some(clip)) => {
|
||||
let image_params = RenderParams {
|
||||
embeds_images: render_params.embeds_images || for_mask,
|
||||
..render_params.clone()
|
||||
};
|
||||
self.backdrop_image(root, copies_to_document, clip, region, read_reach, &image_params)
|
||||
}
|
||||
(true, None) => self.backdrop_markup_copies(root, copies_to_document, true, true),
|
||||
}?;
|
||||
|
||||
// Every open group now holds it
|
||||
for group in &mut self.open_groups.groups {
|
||||
group.holds_backdrop = true;
|
||||
}
|
||||
|
||||
let markup = match clip {
|
||||
Some((clip_path, root_to_document)) => {
|
||||
let matrix = format_transform_matrix(self.transform.inverse() * root_to_document);
|
||||
let transform = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) };
|
||||
format!(r#"<g{transform} clip-path="{clip_path}">{copies}</g>"#)
|
||||
}
|
||||
None => copies,
|
||||
};
|
||||
Some(BackdropCopy { markup, image })
|
||||
}
|
||||
|
||||
/// The group isolating the content drawn next from what lies beneath it, its backdrop root, as an index of the open groups, or `None` if it reads nothing beneath.
|
||||
fn backdrop_root(&self) -> Option<usize> {
|
||||
if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() {
|
||||
return None;
|
||||
}
|
||||
let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?;
|
||||
|
||||
// A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew
|
||||
(root > 0 || !self.open_groups.clip).then_some(root)
|
||||
}
|
||||
|
||||
/// Whether anything is drawn beneath the content drawn next for [`Self::backdrop_copy`] to show, as markup it copies or content it has the GPU draw again.
|
||||
/// O(segments drawn since the backdrop root).
|
||||
pub(crate) fn draws_beneath(&self) -> bool {
|
||||
let Some(root) = self.backdrop_root() else { return false };
|
||||
|
||||
(root..self.open_groups.groups.len()).any(|level| {
|
||||
let group = &self.open_groups.groups[level];
|
||||
let markup = &self.svg[group.content_start..self.level_content_end(level)];
|
||||
let copied = group.user_to_document.is_some() && markup.iter().any(|segment| segment.as_str().contains('<'));
|
||||
copied || group.drawn.iter().any(|drawn| drawn.count > 0)
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the markup drawn directly inside the open group at `level` ends among the render's segments, at the tag of the group open inside it, if any.
|
||||
fn level_content_end(&self, level: usize) -> usize {
|
||||
self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start)
|
||||
}
|
||||
|
||||
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport the `render_params` draw in,
|
||||
/// even where the content reading it embeds its own images. O(segments drawn since the root).
|
||||
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
|
||||
let in_viewport = !(render_params.for_export || render_params.thumbnail || render_params.for_mask || render_params.inside_pattern);
|
||||
let start = self.open_groups.groups[root].content_start;
|
||||
let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str());
|
||||
in_viewport && self.svg[start..].iter().any(draws_canvas)
|
||||
}
|
||||
|
||||
/// Copies of the content drawn at each level of the groups open since the backdrop `root`, in the space `copies_to_document` maps into the document, or `None` if there's none.
|
||||
/// Each is wrapped in a group with an ID for `<use>` copies, or with `repeats_markup`, copied as markup, keeping the viewport's canvases,
|
||||
/// and without the markup showing what lies beneath earlier content if `leaves_out_backdrops`. O(segments drawn since the root).
|
||||
fn backdrop_markup_copies(&mut self, root: usize, copies_to_document: DAffine2, repeats_markup: bool, leaves_out_backdrops: bool) -> Option<String> {
|
||||
let current = self.open_groups.groups.len() - 1;
|
||||
let kept = |segment: &&SvgSegment| !(leaves_out_backdrops && matches!(segment, SvgSegment::Backdrop(_)));
|
||||
|
||||
// From the innermost level out, so wrapping one level's content leaves the outer levels' positions as they are
|
||||
let mut copies = Vec::new();
|
||||
for level in (root..=current).rev() {
|
||||
let group = &self.open_groups.groups[level];
|
||||
let (start, end) = (group.content_start, self.level_content_end(level));
|
||||
let drawn = self.svg[start..end].iter().filter(kept).any(|segment| segment.as_str().contains('<'));
|
||||
let Some(user_to_document) = group.user_to_document.filter(|_| drawn) else { continue };
|
||||
|
||||
let matrix = format_transform_matrix(copies_to_document.inverse() * user_to_document);
|
||||
let attributes = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) };
|
||||
|
||||
if repeats_markup {
|
||||
let markup: String = self.svg[start..end].iter().filter(kept).map(SvgSegment::as_str).collect();
|
||||
copies.push(format!("<g{attributes}>{markup}</g>"));
|
||||
continue;
|
||||
}
|
||||
|
||||
let id = format!("backdrop-{}", generate_uuid());
|
||||
self.svg.insert(end, "</g>".into());
|
||||
self.svg.insert(start, format!(r#"<g id="{id}">"#).into());
|
||||
for inner in &mut self.open_groups.groups[level + 1..] {
|
||||
inner.tag_start += 2;
|
||||
inner.content_start += 2;
|
||||
}
|
||||
copies.push(format!(r##"<use href="#{id}"{attributes} />"##));
|
||||
}
|
||||
if copies.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
copies.reverse();
|
||||
Some(copies.concat())
|
||||
}
|
||||
|
||||
/// The markers standing for an image the GPU renders of the content drawn since the backdrop `root`, cut by the outline of its `clip`, placed in the space `copies_to_document` maps into the document,
|
||||
/// or `None` if there's none. It covers the `region` of the current user space and how far past the view the reading reaches, `read_reach` in the document.
|
||||
fn backdrop_image(&mut self, root: usize, copies_to_document: DAffine2, clip: Option<BezPath>, region: [DVec2; 2], read_reach: f64, render_params: &RenderParams) -> Option<String> {
|
||||
let drawn: Vec<DrawnContent> = self.open_groups.groups[root..].iter().flat_map(|group| &group.drawn).filter(|drawn| drawn.count > 0).cloned().collect();
|
||||
if drawn.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let id = generate_uuid();
|
||||
let bounds = (copies_to_document.inverse() * self.transform * Quad::from_box(region)).bounding_box();
|
||||
self.deferred_images.push(DeferredImage {
|
||||
id,
|
||||
content: DeferredContent::Beneath { clip, drawn },
|
||||
render_params: render_params.clone(),
|
||||
user_to_document: copies_to_document,
|
||||
bounds,
|
||||
margin: self.ancestors_reach + read_reach,
|
||||
opacity: 1.,
|
||||
blend_mode: BlendMode::Normal,
|
||||
mask: None,
|
||||
});
|
||||
|
||||
let (opening, closing) = deferred_image::image_markers(id);
|
||||
Some(format!("{opening}{closing}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Markup showing what lies beneath content (see [`SvgRender::backdrop_copy`]).
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct BackdropCopy {
|
||||
pub markup: String,
|
||||
/// Whether the markup stands for an image the GPU renders of what lies beneath, rather than copying what's drawn.
|
||||
pub image: bool,
|
||||
}
|
||||
|
||||
/// The outline of the union of the `shapes`, each filled by the nonzero rule, as one path filled by that rule, or `None` if their coordinates aren't finite or a sweep fails.
|
||||
/// Each shape's winding is resolved alone first, so the final sweep counts one winding rather than one per shape at every edge.
|
||||
fn united_outline(shapes: &[BezPath]) -> Option<BezPath> {
|
||||
const EPSILON: f64 = 1e-5;
|
||||
|
||||
// A fill closes each subpath, which the sweep takes only explicitly
|
||||
let closed: Vec<BezPath> = shapes.iter().map(closed_subpaths).collect();
|
||||
if !closed.iter().all(BezPath::is_finite) {
|
||||
return None;
|
||||
}
|
||||
let Some(bounds) = closed.iter().map(Shape::bounding_box).reduce(|first, second| first.union(second)) else {
|
||||
return Some(BezPath::new());
|
||||
};
|
||||
|
||||
// Far from the origin, the tolerance grows with the coordinates' magnitude, since the sweep can't resolve less
|
||||
let magnitude = bounds.min_x().min(bounds.min_y()).abs().max(bounds.max_x().max(bounds.max_y()).abs());
|
||||
let epsilon = EPSILON.max(magnitude * f64::EPSILON * 64.);
|
||||
|
||||
// Each shape alone is outlined first by what it fills, wound once around, so no shape's winding can cancel another's where they then unite
|
||||
let mut outlines = BezPath::new();
|
||||
for shape in &closed {
|
||||
outlines.extend(swept_outline(shape, epsilon, |&winding| winding != 0)?);
|
||||
}
|
||||
swept_outline(&outlines, epsilon, |&winding| winding > 0)
|
||||
}
|
||||
|
||||
/// The outline of where the `inside` test accepts the winding number of the closed `path`, wound once around what it holds, or `None` if the sweep fails.
|
||||
fn swept_outline(path: &BezPath, epsilon: f64, inside: impl Fn(&i32) -> bool) -> Option<BezPath> {
|
||||
let topology = Topology::<i32>::from_path(path, epsilon).ok()?;
|
||||
Some(topology.contours(inside).contours().flat_map(|contour| contour.path.elements().iter().copied()).collect())
|
||||
}
|
||||
|
||||
/// The `shape` with each of its subpaths closed, as a fill closes them.
|
||||
pub(crate) fn closed_subpaths(shape: &BezPath) -> BezPath {
|
||||
let mut closed = BezPath::new();
|
||||
for &element in shape.elements() {
|
||||
if matches!(element, PathEl::MoveTo(_)) && !matches!(closed.elements().last(), None | Some(PathEl::ClosePath)) {
|
||||
closed.close_path();
|
||||
}
|
||||
closed.push(element);
|
||||
}
|
||||
if !matches!(closed.elements().last(), None | Some(PathEl::ClosePath)) {
|
||||
closed.close_path();
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
/// What lies beneath content with background blurs, in SVG.
|
||||
pub(crate) struct SvgBackdrop {
|
||||
/// Each copy of what lies beneath, blurred by one background blur, stacked in order within a group the mask cuts to the content.
|
||||
pub markup: String,
|
||||
/// The opening tag of the mask cutting it to the content's silhouette, which the content's own markup goes in once it's drawn.
|
||||
pub mask_tag: String,
|
||||
/// The content's extent, which cuts it instead where the content draws through canvases, since a mask draws no `<foreignObject>`.
|
||||
pub content_bounds: [DVec2; 2],
|
||||
}
|
||||
|
||||
/// What lies beneath content with background blurs, or `None` with nothing beneath it, given the content's `bounds` in the effects' `space`.
|
||||
/// That space is placed in the current user space, or is the user space itself for `None`, and the markup lies in it.
|
||||
/// The filters go in the render's defs (see [`SvgRender::backdrop_copy`] for what they blur).
|
||||
/// A length in that space spans `pixels_per_length` screen pixels, across which a blur too slight to show is left out.
|
||||
pub(crate) fn backdrop_markup(render: &mut SvgRender, effects: &Effects, bounds: [DVec2; 2], space: Option<DAffine2>, pixels_per_length: f64, render_params: &RenderParams) -> Option<SvgBackdrop> {
|
||||
let blurs: Vec<(f64, bool, bool)> = (effects.operations())
|
||||
.filter(|operation| !operation.changes_nothing())
|
||||
.filter_map(|operation| match operation {
|
||||
EffectOperation::BackgroundBlur { radius, box_blur, gamma } => Some((radius, box_blur, gamma)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if blurs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// SVG has no box blur, so a box becomes the Gaussian of the same variance, which reads past the box's own reach
|
||||
let sigma = |radius: f64, box_blur: bool| if box_blur { (radius * (radius + 1.) / 3.).sqrt() } else { radius };
|
||||
let box_overreach: f64 = blurs
|
||||
.iter()
|
||||
.filter(|(_, box_blur, _)| *box_blur)
|
||||
.map(|&(radius, ..)| (3. * sigma(radius, true) - radius - 1.).max(0.))
|
||||
.sum();
|
||||
|
||||
// The blurs read as far past the content as the effects reach
|
||||
let reach = effects.reach() + box_overreach;
|
||||
let (min, max) = (bounds[0] - reach, bounds[1] + reach);
|
||||
let region = format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y);
|
||||
|
||||
let space_to_user = space.unwrap_or_default();
|
||||
let read_region = (space_to_user * Quad::from_box([min, max])).bounding_box();
|
||||
let read_reach = reach * spans_along_axes((render.transform * space_to_user).matrix2).max_element();
|
||||
let copy = render.backdrop_copy(render_params, read_region, read_reach, false)?.markup;
|
||||
let copy = match space.map(|space| format_transform_matrix(space.inverse())) {
|
||||
Some(matrix) if !matrix.is_empty() => format!(r#"<g transform="{matrix}">{copy}</g>"#),
|
||||
_ => copy,
|
||||
};
|
||||
|
||||
let mut blurred = String::new();
|
||||
for (radius, box_blur, gamma) in blurs {
|
||||
if radius * pixels_per_length.max(1.) < NEGLIGIBLE_LENGTH {
|
||||
blurred.push_str(©);
|
||||
continue;
|
||||
}
|
||||
|
||||
let sigma = sigma(radius, box_blur);
|
||||
let space = if gamma { "sRGB" } else { "linearRGB" };
|
||||
let filter_id = format!("background-blur-{}", generate_uuid());
|
||||
write!(
|
||||
render.svg_defs,
|
||||
r#"<filter id="{filter_id}" filterUnits="userSpaceOnUse" {region}><feGaussianBlur stdDeviation="{sigma}" color-interpolation-filters="{space}" /></filter>"#
|
||||
)
|
||||
.unwrap();
|
||||
write!(blurred, r#"<g filter="url(#{filter_id})">{copy}</g>"#).unwrap();
|
||||
}
|
||||
|
||||
let mask_id = format!("backdrop-mask-{}", generate_uuid());
|
||||
Some(SvgBackdrop {
|
||||
markup: format!(r#"<g mask="url(#{mask_id})">{blurred}</g>"#),
|
||||
mask_tag: format!(r#"<mask id="{mask_id}" mask-type="alpha" maskUnits="userSpaceOnUse" {region}>"#),
|
||||
content_bounds: bounds,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn clip_shapes_with_coordinates_past_finite_ones_unite_into_no_outline() {
|
||||
let square = kurbo::Rect::new(0., 0., 10., 10.).to_path(0.1);
|
||||
let mut broken = BezPath::new();
|
||||
broken.move_to((0., 0.));
|
||||
broken.line_to((f64::NAN, 5.));
|
||||
broken.line_to((5., f64::INFINITY));
|
||||
|
||||
// Images inside such a clip path give way to copies leaving held ones out, rather than drawing an outline that's wrong
|
||||
assert!(united_outline(&[square.clone(), broken]).is_none());
|
||||
assert!(united_outline(&[square.clone(), square]).is_some_and(|outline| (outline.area().abs() - 100.).abs() < 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thousands_of_overlapping_clip_shapes_wound_either_way_unite_quickly_into_what_they_cover() {
|
||||
// A 100 by 50 grid of squares a unit and a half wide, a unit apart so neighbors overlap, every other one wound the other way
|
||||
let squares: Vec<BezPath> = (0..5_000)
|
||||
.map(|index| {
|
||||
let corner = kurbo::Point::new((index % 100) as f64, (index / 100) as f64);
|
||||
let square = kurbo::Rect::from_origin_size(corner, (1.5, 1.5)).to_path(0.1);
|
||||
if index % 2 == 0 { square } else { square.reverse_subpaths() }
|
||||
})
|
||||
.collect();
|
||||
|
||||
// They unite into the rectangle they cover, none cancelling a neighbor wound against it
|
||||
let start = std::time::Instant::now();
|
||||
let outline = united_outline(&squares).expect("the squares unite");
|
||||
let elapsed = start.elapsed();
|
||||
assert!((outline.area().abs() - 100.5 * 50.5).abs() < 1e-6, "the union spans {}", outline.area().abs());
|
||||
assert!(elapsed < std::time::Duration::from_secs(10), "uniting took {elapsed:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
//! Blend If in SVG, all native: filter primitives weigh each pixel by its channels' levels through tables of the ranges' weights, fading the content within its effects filter,
|
||||
//! and a mask holding a copy of what lies beneath, filtered into its weights, fades every layer the content draws.
|
||||
|
||||
use crate::deferred_image::{DEFERRED_COVER_CLOSING, DEFERRED_COVER_OPENING, DEFERRED_IMAGE_CLOSING, DEFERRED_IMAGE_OPENING};
|
||||
use crate::renderer::{RenderParams, SvgRender};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::DVec2;
|
||||
use graphic_types::BlendIfChannel;
|
||||
use graphic_types::blend_if::{BlendRange, ChannelRanges, GRAY_PERCENTAGES};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use std::fmt::Write;
|
||||
|
||||
/// Pushes the primitives weighing how strongly the `ranges` show each pixel of the `image` result by its straight color, given `push` (a primitive's tag, attributes, and children, returning its result's name).
|
||||
/// Returns the name of the result holding the weight in its alpha, or `None` if the ranges show everything.
|
||||
pub(crate) fn weight(push: &mut impl FnMut(&str, &str, &str) -> String, image: &str, ranges: &ChannelRanges) -> Option<String> {
|
||||
let mut weight: Option<String> = None;
|
||||
|
||||
for (channel, range) in ranges.limiting() {
|
||||
// A gray exactly between two levels gains a sliver of a level, so it rounds up as `gray_level` rounds it
|
||||
let [red, green, blue] = GRAY_PERCENTAGES.map(|percentage| percentage as f64 / 100.);
|
||||
let alpha_row = match channel {
|
||||
BlendIfChannel::Gray => format!("{red} {green} {blue} 0 {}", 0.005 / 255.),
|
||||
BlendIfChannel::Red => "1 0 0 0 0".to_string(),
|
||||
BlendIfChannel::Green => "0 1 0 0 0".to_string(),
|
||||
BlendIfChannel::Blue => "0 0 1 0 0".to_string(),
|
||||
};
|
||||
|
||||
// The channel's level moved into alpha, then looked up in the table of the range's weight at each level, which the browser's 8-bit filters index exactly
|
||||
let level = push(
|
||||
"feColorMatrix",
|
||||
&format!(r#"in="{image}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 {alpha_row}" color-interpolation-filters="sRGB""#),
|
||||
"",
|
||||
);
|
||||
let table: Vec<String> = range.level_weights().iter().map(|weight| format_table_value(*weight)).collect();
|
||||
let shown = push(
|
||||
"feComponentTransfer",
|
||||
&format!(r#"in="{level}" color-interpolation-filters="sRGB""#),
|
||||
&format!(r#"<feFuncA type="table" tableValues="{}" />"#, table.join(" ")),
|
||||
);
|
||||
|
||||
weight = Some(match weight {
|
||||
Some(previous) => push("feComposite", &format!(r#"in="{shown}" in2="{previous}" operator="in""#), ""),
|
||||
None => shown,
|
||||
});
|
||||
}
|
||||
|
||||
weight
|
||||
}
|
||||
|
||||
/// The viewport's copy of what lies beneath as `markup`, with what a mask can't draw, so SVG can't read, covered by rectangles of the `key` color the ranges show in full.
|
||||
/// What's drawn over a cover still hides it, as it hides the image the cover stands in for.
|
||||
pub(crate) fn with_unreadable_covered(markup: &str, key: &str) -> String {
|
||||
with_canvases_covered(&with_deferred_images_marked_for_covers(markup, key), key)
|
||||
}
|
||||
|
||||
/// The `markup` with the canvases standing in for images covered with the `key` color, at their own placement, size, opacity, and blend mode, so a translucent image hides less of what lies beneath it.
|
||||
fn with_canvases_covered(markup: &str, key: &str) -> String {
|
||||
const OPENING: &str = "<foreignObject";
|
||||
const CLOSING: &str = "</foreignObject>";
|
||||
|
||||
let mut covered = String::with_capacity(markup.len());
|
||||
let mut rest = markup;
|
||||
while let Some(start) = rest.find(OPENING) {
|
||||
let Some(end) = rest[start..].find(CLOSING).map(|offset| start + offset + CLOSING.len()) else {
|
||||
break;
|
||||
};
|
||||
covered.push_str(&rest[..start]);
|
||||
|
||||
// A canvas's cover takes its opening tag's attributes
|
||||
let element = &rest[start..end];
|
||||
match (element.contains("data-canvas-placeholder"), element.find('>')) {
|
||||
(true, Some(tag_end)) => write!(covered, r#"<rect{} fill="{key}" />"#, &element[OPENING.len()..tag_end]).unwrap(),
|
||||
(true, None) => {}
|
||||
(false, _) => covered.push_str(element),
|
||||
}
|
||||
rest = &rest[end..];
|
||||
}
|
||||
covered.push_str(rest);
|
||||
covered
|
||||
}
|
||||
|
||||
/// The `markup` with the markup standing in for each image the GPU renders marked for a rectangle of the `key` color to cover once the image arrives (see [`crate::deferred_image::substitute_deferred_image`]).
|
||||
/// Without a GPU the markup is what's drawn, which the mask reads as it is.
|
||||
fn with_deferred_images_marked_for_covers(markup: &str, key: &str) -> String {
|
||||
let markup = markup.replace(DEFERRED_IMAGE_CLOSING, DEFERRED_COVER_CLOSING);
|
||||
let mut parts = markup.split(DEFERRED_IMAGE_OPENING);
|
||||
let mut marked = parts.next().unwrap_or_default().to_string();
|
||||
for part in parts {
|
||||
// Each opening marker's ID is followed by the end of the comment, before which the key goes
|
||||
match part.split_once("-->") {
|
||||
Some((id, rest)) => write!(marked, "{DEFERRED_COVER_OPENING}{id}-{}-->{rest}", key.trim_start_matches('#')).unwrap(),
|
||||
None => write!(marked, "{DEFERRED_IMAGE_OPENING}{part}").unwrap(),
|
||||
}
|
||||
}
|
||||
marked
|
||||
}
|
||||
|
||||
/// A color the `underlying` ranges, which multiply, show most strongly (in full if any color is shown in full), as a hex color.
|
||||
/// Each channel shows its levels in full in one span, and the gray rises with each channel, so the colors from every channel's lowest such level to every one's highest pass through each gray between them.
|
||||
fn key_color(underlying: &[ChannelRanges]) -> String {
|
||||
// The span of levels each channel shows most strongly, by itself
|
||||
let span = |range: fn(&ChannelRanges) -> &BlendRange| {
|
||||
let shown = |level: usize| underlying.iter().map(|ranges| range(ranges).weight(level as f64 / 255.)).product::<f64>();
|
||||
let most = (0..256).map(shown).fold(0., f64::max);
|
||||
let levels: Vec<usize> = (0..256).filter(|&level| shown(level) >= most).collect();
|
||||
[levels.first().copied().unwrap_or(0), levels.last().copied().unwrap_or(255)].map(|level| level as f64)
|
||||
};
|
||||
let spans = [span(|ranges| &ranges.red), span(|ranges| &ranges.green), span(|ranges| &ranges.blue)];
|
||||
|
||||
// O(256 × ranges): the colors along the way from the lowest ends to the highest, which the gray's ranges show most strongly somewhere
|
||||
let weight = |color: [f64; 3]| underlying.iter().map(|ranges| ranges.weight(color)).product::<f64>();
|
||||
let color_at = |step: usize| spans.map(|[low, high]| (low + (high - low) * step as f64 / 255.).round() / 255.);
|
||||
let best = (0..256).map(color_at).fold(color_at(0), |best, color| if weight(color) > weight(best) { color } else { best });
|
||||
let [red, green, blue] = best.map(|channel| (channel * 255.).round() as u8);
|
||||
format!("#{red:02x}{green:02x}{blue:02x}")
|
||||
}
|
||||
|
||||
/// A weight for a table, with no more digits than it needs.
|
||||
fn format_table_value(weight: f64) -> String {
|
||||
let rounded = format!("{weight:.4}");
|
||||
rounded.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
}
|
||||
|
||||
/// Writes a mask into the render's defs that fades what's drawn in the current user space by how strongly the `underlying` ranges, which multiply, show what lies beneath, returning its reference, or `None` with nothing beneath to read.
|
||||
/// `bounds` is the content's extent in this user space and `reach` how far its effects reach past it along each axis there.
|
||||
pub(crate) fn underlying_mask(render: &mut SvgRender, underlying: &[ChannelRanges], bounds: [DVec2; 2], reach: DVec2, render_params: &RenderParams) -> Option<String> {
|
||||
let mut markup = String::new();
|
||||
let mut count = 0;
|
||||
let mut push = |tag: &str, attributes: &str, children: &str| {
|
||||
count += 1;
|
||||
let result = format!("blend-if-{count}");
|
||||
match children.is_empty() {
|
||||
true => write!(markup, r#"<{tag} {attributes} result="{result}" />"#),
|
||||
false => write!(markup, r#"<{tag} {attributes} result="{result}">{children}</{tag}>"#),
|
||||
}
|
||||
.unwrap();
|
||||
result
|
||||
};
|
||||
|
||||
// Each side's channels multiply, and so do the sides
|
||||
let mut weight: Option<String> = None;
|
||||
for ranges in underlying {
|
||||
let Some(shown) = self::weight(&mut push, "SourceGraphic", ranges) else { continue };
|
||||
weight = Some(match weight {
|
||||
Some(previous) => push("feComposite", &format!(r#"in="{shown}" in2="{previous}" operator="in""#), ""),
|
||||
None => shown,
|
||||
});
|
||||
}
|
||||
let weight = weight?;
|
||||
|
||||
// Where nothing lies beneath, nothing is hidden: the weight is 1 - alpha × (1 - weight)
|
||||
let invert = r#"<feFuncA type="linear" slope="-1" intercept="1" />"#;
|
||||
let hidden = push("feComponentTransfer", &format!(r#"in="{weight}""#), invert);
|
||||
let hidden_beneath = push("feComposite", &format!(r#"in="{hidden}" in2="SourceAlpha" operator="in""#), "");
|
||||
push("feComponentTransfer", &format!(r#"in="{hidden_beneath}""#), invert);
|
||||
|
||||
// The mask covers how far the effects reach past the content, and a document pixel more for the pixels its edges cut through
|
||||
let reach = reach + spans_along_axes(render.transform.matrix2.inverse());
|
||||
let (min, max) = (bounds[0] - reach, bounds[1] + reach);
|
||||
let region = format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y);
|
||||
|
||||
// Each pixel reads only what lies beneath it, so an image of that reads nothing past the view
|
||||
let copy = render.backdrop_copy(render_params, [min, max], 0., true)?;
|
||||
|
||||
// Where canvases and the GPU's images stand in for what lies beneath in a copy of its markup, it can't be read, so nothing there is hidden
|
||||
let copy = match copy.image {
|
||||
true => copy.markup,
|
||||
false => with_unreadable_covered(©.markup, &key_color(underlying)),
|
||||
};
|
||||
|
||||
let (filter_id, mask_id) = (format!("blend-if-{}", generate_uuid()), format!("blend-if-mask-{}", generate_uuid()));
|
||||
write!(
|
||||
render.svg_defs,
|
||||
r#"<filter id="{filter_id}" filterUnits="userSpaceOnUse" {region} color-interpolation-filters="sRGB">{markup}</filter><mask id="{mask_id}" mask-type="alpha" maskUnits="userSpaceOnUse" {region}><g filter="url(#{filter_id})">{copy}</g></mask>"#
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
Some(format!("url(#{mask_id})"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn keys_are_colors_the_ranges_show_in_full_where_no_gray_is() {
|
||||
// Red from 60% up and blue up to 40%, which no gray passes both of
|
||||
let mut ranges = ChannelRanges::default();
|
||||
(ranges.red.falloff_start, ranges.red.range_start) = (60., 60.);
|
||||
(ranges.blue.range_end, ranges.blue.falloff_end) = (40., 40.);
|
||||
|
||||
let key = key_color(&[ranges]);
|
||||
let channel = |index: usize| u8::from_str_radix(&key[1 + 2 * index..3 + 2 * index], 16).unwrap() as f64 / 255.;
|
||||
assert_eq!(ranges.weight([channel(0), channel(1), channel(2)]), 1., "{key}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_where_no_image_stands_in_cover_canvases_and_the_gpus_images_with_the_key_color() {
|
||||
use crate::deferred_image::{DeferredImagePlacement, substitute_deferred_image};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use glam::DAffine2;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
|
||||
let canvas = r#"<foreignObject x="1" y="2" width="3" height="4"><div data-canvas-placeholder="image-7"></div></foreignObject>"#;
|
||||
let stand_in = r#"<!--deferred-image-9--><path d="M0,0" /><!--/deferred-image-9-->"#;
|
||||
let covered = with_unreadable_covered(&format!("{canvas}{stand_in}"), "#000000");
|
||||
|
||||
// A canvas becomes a rectangle of the key color at its own placement, and the stand-in for the GPU's image is marked for one
|
||||
assert!(covered.starts_with(r##"<rect x="1" y="2" width="3" height="4" fill="#000000" />"##), "{covered}");
|
||||
assert!(covered.contains(r#"<!--deferred-cover-9-000000--><path d="M0,0" /><!--/deferred-cover-9-->"#), "{covered}");
|
||||
|
||||
// Once the GPU's image arrives in a canvas in place of the original stand-in, the rectangle replaces the copy's
|
||||
let placement = DeferredImagePlacement {
|
||||
id: 9,
|
||||
transform: DAffine2::IDENTITY,
|
||||
user_to_document: DAffine2::IDENTITY,
|
||||
opacity: 1.,
|
||||
blend_mode: BlendMode::Normal,
|
||||
mask: None,
|
||||
to_canvas: true,
|
||||
canvas_image_scale: 1.,
|
||||
};
|
||||
let mut svg = format!("{covered}{stand_in}");
|
||||
substitute_deferred_image(&mut svg, &mut Vec::new(), &placement, &Raster::new_cpu(Image::new(1, 1, Color::BLACK)));
|
||||
assert!(svg.contains(r##"<rect width="1" height="1" transform="" fill="#000000" />"##) && !svg.contains("deferred-"), "{svg}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
//! Layers in the blend modes `mix-blend-mode` lacks, or below a full fill moving them toward neutral in Color Dodge and Color Burn, built all natively from what SVG composites,
|
||||
//! over a copy of what lies beneath (see [`SvgRender::backdrop_copy`]).
|
||||
//! The layer's alpha, times [`layer_fill_shown`] where its fill moves it toward neutral, shows an opaque result: the layer made opaque, and over it the blend, shown by the alpha of what lies beneath,
|
||||
//! as the W3C's general formula mixes them. The blend draws the layer, recolored and made opaque, over an opaque copy of what lies beneath, where `s` is the layer moved toward neutral by its fill:
|
||||
//! - Linear Burn, Subtract: Lighten by `x`, then Difference by `x`, which leaves `max(0, b - x)` exactly, for `x` of `1 - s` or `s`.
|
||||
//! - Linear Dodge: that over the inverted copy, inverted back. Linear Light: Linear Burn by `2s`, then Linear Dodge by `2s - 1`.
|
||||
//! - Hard Mix: at full strength, the copy where it and the layer sum to white exactly, and white where they sum past it, each where Color Dodge reaches white.
|
||||
//! Below it, Linear Burn by `q (1 - s)`, stretched by `1 / (1 - q)`.
|
||||
//! - Divide: Color Dodge by the inverted layer. Pin Light: Darken by `2s`, then Lighten by `2s - 1`. Vivid Light: Color Burn by `2s`, then Color Dodge by `2s - 1`.
|
||||
//! - Darker Color, Lighter Color: the layer over the copy, masked to where Luminosity moves the copy's color down (or up) by a level or more.
|
||||
//! - Color Dodge, Color Burn: themselves by `s`.
|
||||
|
||||
use crate::renderer::{RenderParams, SvgRender, SvgSegment};
|
||||
use crate::svg_backdrop::BackdropCopy;
|
||||
use crate::svg_blend_if::with_unreadable_covered;
|
||||
use core_types::blending::{BlendMode, layer_fill_shown};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::DVec2;
|
||||
use std::fmt::Write;
|
||||
|
||||
/// A layer blending by a mode `mix-blend-mode` lacks, with what it reads to blend onto what lies beneath.
|
||||
pub(crate) struct SvgLayerBlend {
|
||||
blend_mode: BlendMode,
|
||||
/// The copy of what lies beneath, taken before any of the item is drawn, or `None` with nothing beneath.
|
||||
copy: Option<BackdropCopy>,
|
||||
/// The region of the current user space the layer covers, which the blend's filters and masks cover too.
|
||||
region: [DVec2; 2],
|
||||
/// The fill moving the layer toward the mode's neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), or 1 where the layer is faded by its fill already.
|
||||
fill: f64,
|
||||
}
|
||||
|
||||
impl SvgLayerBlend {
|
||||
/// Copies what lies beneath the `region` of the current user space, before any of the layer is drawn, for it to blend onto by the mode.
|
||||
pub(crate) fn new(render: &mut SvgRender, render_params: &RenderParams, blend_mode: BlendMode, region: [DVec2; 2], fill: f64) -> Self {
|
||||
Self {
|
||||
blend_mode,
|
||||
copy: render.backdrop_copy(render_params, region, 0., true),
|
||||
region,
|
||||
fill,
|
||||
}
|
||||
}
|
||||
|
||||
/// The blend of another layer of the same item by its own `blend_mode` at full strength, onto the same copy of what lies beneath.
|
||||
pub(crate) fn with_mode(&self, blend_mode: BlendMode) -> Self {
|
||||
Self {
|
||||
blend_mode,
|
||||
copy: self.copy.clone(),
|
||||
region: self.region,
|
||||
fill: 1.,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the layer blends onto what lies beneath, rather than over nothing.
|
||||
pub(crate) fn blends(&self) -> bool {
|
||||
self.copy.is_some() && recipe(self.blend_mode, self.fill).is_some()
|
||||
}
|
||||
|
||||
/// Whether the blend moves the layer toward the mode's neutral color by a fill below full, which the layer itself then leaves out.
|
||||
pub(crate) fn moves_by_fill(&self) -> bool {
|
||||
self.fill < 1.
|
||||
}
|
||||
}
|
||||
|
||||
/// A map of each straight color channel, `scale × channel + offset`, clamped to 0 to 1.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Recolor {
|
||||
scale: f64,
|
||||
offset: f64,
|
||||
}
|
||||
|
||||
impl Recolor {
|
||||
const IDENTITY: Self = Self { scale: 1., offset: 0. };
|
||||
const INVERT: Self = Self { scale: -1., offset: 1. };
|
||||
}
|
||||
|
||||
/// One step building a mode SVG lacks: the layer recolored and made opaque, then drawn by a native mode.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct BlendStep {
|
||||
recolor: Recolor,
|
||||
blend_mode: BlendMode,
|
||||
}
|
||||
|
||||
/// A stage of steps over its base (the copy of what lies beneath, or the stage before), recolored, whose result it then recolors by `stretch`.
|
||||
#[derive(Clone, Debug)]
|
||||
struct BlendStage {
|
||||
base: Recolor,
|
||||
steps: Vec<BlendStep>,
|
||||
stretch: Recolor,
|
||||
}
|
||||
|
||||
/// How SVG builds a mode it lacks over an opaque copy of what lies beneath.
|
||||
#[derive(Clone, Debug)]
|
||||
enum BlendRecipe {
|
||||
Stages(Vec<BlendStage>),
|
||||
/// Hard Mix at full strength: the copy where it and the layer sum to white exactly, and white where they sum past it.
|
||||
HardMixThreshold,
|
||||
/// The layer's whole color where its luma is lower than that of what lies beneath, or higher if `lighter`.
|
||||
Pick {
|
||||
lighter: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// The recipe for a mode SVG lacks at the `fill` moving the layer's color toward neutral where the mode does that, or `None` for a mode SVG has at it.
|
||||
fn recipe(blend_mode: BlendMode, fill: f64) -> Option<BlendRecipe> {
|
||||
use BlendMode::*;
|
||||
|
||||
let step = |scale: f64, offset: f64, blend_mode: BlendMode| BlendStep {
|
||||
recolor: Recolor { scale, offset },
|
||||
blend_mode,
|
||||
};
|
||||
// Lightening by `x`, then the difference from it, leaves `max(0, b - x)` in whole levels
|
||||
let burn_by = |scale: f64, offset: f64| vec![step(scale, offset, Lighten), step(scale, offset, Difference)];
|
||||
let stage = |base: Recolor, steps: Vec<BlendStep>, stretch: Recolor| BlendStage { base, steps, stretch };
|
||||
let (identity, invert) = (Recolor::IDENTITY, Recolor::INVERT);
|
||||
let steepness = 255. * fill / 256.;
|
||||
|
||||
let stages = match blend_mode {
|
||||
LinearBurn => vec![stage(identity, burn_by(-fill, fill), identity)],
|
||||
Subtract => vec![stage(identity, burn_by(1., 0.), identity)],
|
||||
LinearDodge => vec![stage(invert, burn_by(fill, 0.), invert)],
|
||||
LinearLight => vec![stage(identity, burn_by(-2. * fill, fill), identity), stage(invert, burn_by(2. * fill, -fill), invert)],
|
||||
HardMix if fill >= 1. => return Some(BlendRecipe::HardMixThreshold),
|
||||
HardMix => vec![stage(
|
||||
identity,
|
||||
burn_by(-steepness, steepness),
|
||||
Recolor {
|
||||
scale: 1. / (1. - steepness),
|
||||
offset: 0.,
|
||||
},
|
||||
)],
|
||||
Divide => vec![stage(identity, vec![step(-1., 1., ColorDodge)], identity)],
|
||||
ColorDodge if fill < 1. => vec![stage(identity, vec![step(fill, 0., ColorDodge)], identity)],
|
||||
ColorBurn if fill < 1. => vec![stage(identity, vec![step(fill, 1. - fill, ColorBurn)], identity)],
|
||||
PinLight => vec![stage(identity, vec![step(2., 0., Darken), step(2., -1., Lighten)], identity)],
|
||||
VividLight => vec![stage(identity, vec![step(2. * fill, 1. - fill, ColorBurn), step(2. * fill, -fill, ColorDodge)], identity)],
|
||||
DarkerColor => return Some(BlendRecipe::Pick { lighter: false }),
|
||||
LighterColor => return Some(BlendRecipe::Pick { lighter: true }),
|
||||
_ => return None,
|
||||
};
|
||||
Some(BlendRecipe::Stages(stages))
|
||||
}
|
||||
|
||||
/// The filters and masks one blended layer writes into the render's defs, each within the layer's region.
|
||||
struct BlendDefs<'a> {
|
||||
defs: &'a mut String,
|
||||
region: String,
|
||||
uuid: u64,
|
||||
recolors: Vec<(Recolor, String)>,
|
||||
}
|
||||
|
||||
impl BlendDefs<'_> {
|
||||
/// Writes a def named `name` with the `tag`, the `attributes` past its ID, and the `children`, returning a reference to it.
|
||||
fn write(&mut self, name: &str, tag: &str, attributes: &str, children: &str) -> String {
|
||||
let id = format!("layer-blend-{name}-{}", self.uuid);
|
||||
write!(self.defs, r#"<{tag} id="{id}" {attributes} {}>{children}</{tag}>"#, self.region).unwrap();
|
||||
format!("url(#{id})")
|
||||
}
|
||||
|
||||
/// A filter named `name` of the `primitives` on gamma-encoded colors.
|
||||
fn filter(&mut self, name: &str, primitives: &str) -> String {
|
||||
self.write(name, "filter", r#"filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB""#, primitives)
|
||||
}
|
||||
|
||||
/// A mask named `name` showing what the `markup` covers, by its alpha.
|
||||
fn mask(&mut self, name: &str, markup: &str) -> String {
|
||||
self.write(name, "mask", r#"mask-type="alpha" maskUnits="userSpaceOnUse""#, markup)
|
||||
}
|
||||
|
||||
/// A filter making what it draws opaque in its straight color, recolored, written once for each recoloring.
|
||||
fn recolor(&mut self, recolor: Recolor) -> String {
|
||||
if let Some((_, reference)) = self.recolors.iter().find(|(written, _)| *written == recolor) {
|
||||
return reference.clone();
|
||||
}
|
||||
|
||||
let Recolor { scale, offset } = recolor;
|
||||
let name = format!("recolor-{}", self.recolors.len());
|
||||
let reference = self.filter(
|
||||
&name,
|
||||
&format!(r#"<feColorMatrix type="matrix" values="{scale} 0 0 0 {offset} 0 {scale} 0 0 {offset} 0 0 {scale} 0 {offset} 0 0 0 0 1" />"#),
|
||||
);
|
||||
self.recolors.push((recolor, reference.clone()));
|
||||
reference
|
||||
}
|
||||
}
|
||||
|
||||
/// What a blended layer draws around it, with its defs written.
|
||||
struct BlendGroups {
|
||||
/// The attributes of each group around the layer made opaque and the blend over it, outermost first.
|
||||
around: Vec<Vec<(&'static str, String)>>,
|
||||
/// The filter making the layer opaque, beneath the blend.
|
||||
opaque: String,
|
||||
/// The ID the layer's own group takes, for copies of it to reference.
|
||||
layer_id: String,
|
||||
/// The blend's markup, drawn over the layer made opaque, which copies of what lies beneath leave out so they never nest.
|
||||
blended: String,
|
||||
}
|
||||
|
||||
/// Writes the defs of the `blend` of a layer at `opacity` and returns what it draws around the layer, or `None` with nothing beneath to blend onto.
|
||||
fn blend_groups(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32) -> Option<BlendGroups> {
|
||||
let (Some(copy), Some(recipe)) = (&blend.copy, recipe(blend.blend_mode, blend.fill)) else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let uuid = generate_uuid();
|
||||
let layer_id = format!("layer-blend-layer-{uuid}");
|
||||
let [min, max] = blend.region;
|
||||
let mut defs = BlendDefs {
|
||||
defs: &mut render.svg_defs,
|
||||
region: format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y),
|
||||
uuid,
|
||||
recolors: Vec::new(),
|
||||
};
|
||||
|
||||
// Copies of the layer reference it, and masks read what lies beneath from an image or a copy covering what they can't draw
|
||||
let layer = format!(r##"<use href="#{layer_id}" />"##);
|
||||
let beneath_in_mask = if copy.image { copy.markup.clone() } else { with_unreadable_covered(©.markup, "#000000") };
|
||||
let opaque = defs.recolor(Recolor::IDENTITY);
|
||||
let drawn = |filter: &str, blend_mode: BlendMode, markup: &str| format!(r#"<g filter="{filter}" style="{}">{markup}</g>"#, blend_mode.render().trim());
|
||||
|
||||
let blend_markup = match recipe {
|
||||
// Each stage's steps blend over its base alone, within a group recoloring what they leave
|
||||
BlendRecipe::Stages(stages) => {
|
||||
let mut result = copy.markup.clone();
|
||||
for stage in stages {
|
||||
let base = format!(r#"<g filter="{}">{result}</g>"#, defs.recolor(stage.base));
|
||||
let steps: String = stage.steps.iter().map(|step| drawn(&defs.recolor(step.recolor), step.blend_mode, &layer)).collect();
|
||||
result = format!(r#"<g filter="{}">{base}{steps}</g>"#, defs.recolor(stage.stretch));
|
||||
}
|
||||
result
|
||||
}
|
||||
// Color Dodge reaches white exactly where the layer and the copy sum to white or past it, or past it alone for the layer a level darker
|
||||
BlendRecipe::HardMixThreshold => {
|
||||
let white = defs.filter("white", r#"<feComponentTransfer><feFuncR type="linear" slope="255" intercept="-254" /><feFuncG type="linear" slope="255" intercept="-254" /><feFuncB type="linear" slope="255" intercept="-254" /></feComponentTransfer>"#);
|
||||
let mut reaches_white = |offset: f64| {
|
||||
format!(
|
||||
r#"<g filter="{opaque}">{}</g>{}"#,
|
||||
copy.markup,
|
||||
drawn(&defs.recolor(Recolor { scale: 1., offset }), BlendMode::ColorDodge, &layer)
|
||||
)
|
||||
};
|
||||
let (sums_to_white, sums_past_white) = (reaches_white(0.), reaches_white(-1. / 255.));
|
||||
format!(
|
||||
r#"<g filter="{opaque}">{}</g><g filter="{white}" style="mix-blend-mode: multiply;">{sums_to_white}</g><g filter="{white}" style="mix-blend-mode: lighten;">{sums_past_white}</g>"#,
|
||||
copy.markup
|
||||
)
|
||||
}
|
||||
// Luminosity moves the copy's color by the layer's luma less its own, which the change in any channel shows the direction of
|
||||
BlendRecipe::Pick { lighter } => {
|
||||
let any_channel = defs.filter("any-channel", r#"<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 255 255 0 0" />"#);
|
||||
let toward = if lighter { BlendMode::Lighten } else { BlendMode::Darken };
|
||||
let moved = format!(
|
||||
r#"<g filter="{any_channel}"><g filter="{opaque}">{beneath_in_mask}</g>{}{}{}</g>"#,
|
||||
drawn(&opaque, BlendMode::Luminosity, &layer),
|
||||
drawn(&opaque, toward, &beneath_in_mask),
|
||||
drawn(&opaque, BlendMode::Difference, &beneath_in_mask)
|
||||
);
|
||||
let picked = defs.mask("picked", &moved);
|
||||
format!(r#"<g filter="{opaque}">{}</g><g filter="{opaque}" mask="{picked}">{layer}</g>"#, copy.markup)
|
||||
}
|
||||
};
|
||||
|
||||
// The blend shows by the alpha of what lies beneath, and the whole by the layer's own alpha, at its opacity
|
||||
let beneath = defs.mask("beneath", &beneath_in_mask);
|
||||
let blended = format!(r#"<g mask="{beneath}">{blend_markup}</g>"#);
|
||||
let mut outer = vec![("mask", defs.mask("shown", &layer))];
|
||||
if opacity < 1. {
|
||||
outer.push(("opacity", opacity.to_string()));
|
||||
}
|
||||
let mut around = vec![outer];
|
||||
|
||||
// A fill moving the layer toward neutral shows it by how much lies beneath, by a table of each level of alpha there
|
||||
if blend.fill < 1. {
|
||||
let table: Vec<String> = (0..=255).map(|level| format!("{:.5}", layer_fill_shown(level as f32 / 255., blend.fill as f32))).collect();
|
||||
let weight = defs.filter(
|
||||
"fill-weight",
|
||||
&format!(r#"<feComponentTransfer><feFuncA type="table" tableValues="{}" /></feComponentTransfer>"#, table.join(" ")),
|
||||
);
|
||||
around.push(vec![("mask", defs.mask("fill-shown", &format!(r#"<g filter="{weight}">{beneath_in_mask}</g>"#)))]);
|
||||
}
|
||||
|
||||
Some(BlendGroups { around, opaque, layer_id, blended })
|
||||
}
|
||||
|
||||
/// Draws the layer `draw_layer` draws, blended by the mode onto what lies beneath it and faded by `opacity`.
|
||||
pub(crate) fn draw_blended_layer(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32, draw_layer: impl FnOnce(&mut SvgRender)) {
|
||||
let Some(BlendGroups { around, opaque, layer_id, blended }) = blend_groups(render, blend, opacity) else {
|
||||
// Over nothing, the layer shows as it is, faded by a fill it would otherwise move toward neutral
|
||||
let opacity = opacity as f64 * blend.fill;
|
||||
return render.parent_tag(
|
||||
"g",
|
||||
|attributes| {
|
||||
if opacity < 1. {
|
||||
attributes.push("opacity", opacity.to_string());
|
||||
}
|
||||
},
|
||||
draw_layer,
|
||||
);
|
||||
};
|
||||
|
||||
nest_groups(render, &around, |render| {
|
||||
render.parent_tag(
|
||||
"g",
|
||||
|attributes| attributes.push("filter", opaque),
|
||||
|render| render.parent_tag("g", |attributes| attributes.push("id", layer_id), draw_layer),
|
||||
);
|
||||
render.leaf_node(SvgSegment::Backdrop(blended));
|
||||
});
|
||||
}
|
||||
|
||||
/// Wraps the markup drawn since the segment at `start`, an image of the layer the GPU renders, in what [`draw_blended_layer`] draws around a layer. Returns whether it blends.
|
||||
pub(crate) fn wrap_blended_layer(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32, start: usize) -> bool {
|
||||
let Some(BlendGroups { around, opaque, layer_id, blended }) = blend_groups(render, blend, opacity) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let opening = |attributes: &Vec<(&'static str, String)>| format!("<g{}>", attributes.iter().map(|(name, value)| format!(r#" {name}="{value}""#)).collect::<String>());
|
||||
let mut opened: String = around.iter().map(opening).collect();
|
||||
write!(opened, r#"<g filter="{opaque}"><g id="{layer_id}">"#).unwrap();
|
||||
render.svg.insert(start, opened.into());
|
||||
render.svg.push("</g></g>".into());
|
||||
render.svg.push(SvgSegment::Backdrop(blended));
|
||||
render.svg.push("</g>".repeat(around.len()).into());
|
||||
true
|
||||
}
|
||||
|
||||
/// Opens a group of each of the `groups`' attributes, outermost first, around what `inner` draws.
|
||||
fn nest_groups(render: &mut SvgRender, groups: &[Vec<(&'static str, String)>], inner: impl FnOnce(&mut SvgRender)) {
|
||||
let Some((attributes, nested)) = groups.split_first() else { return inner(render) };
|
||||
render.parent_tag(
|
||||
"g",
|
||||
|tag| attributes.iter().for_each(|(name, value)| tag.push(*name, value.clone())),
|
||||
|render| nest_groups(render, nested, inner),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use raster_kernels::layer_blending::{blend_layer_pixel, blend_pixel};
|
||||
|
||||
/// The modes SVG builds from native compositing.
|
||||
const MODES: [BlendMode; 10] = [
|
||||
BlendMode::LinearBurn,
|
||||
BlendMode::DarkerColor,
|
||||
BlendMode::LinearDodge,
|
||||
BlendMode::LighterColor,
|
||||
BlendMode::VividLight,
|
||||
BlendMode::LinearLight,
|
||||
BlendMode::PinLight,
|
||||
BlendMode::HardMix,
|
||||
BlendMode::Subtract,
|
||||
BlendMode::Divide,
|
||||
];
|
||||
|
||||
/// The modes SVG has, which it builds from native compositing too below a full fill moving the layer toward neutral.
|
||||
const BELOW_FULL_FILL: [BlendMode; 2] = [BlendMode::ColorDodge, BlendMode::ColorBurn];
|
||||
|
||||
/// A value as the 8-bit buffers browsers hold the results of filters and groups in keep it.
|
||||
fn quantized(value: f64) -> f64 {
|
||||
(value.clamp(0., 1.) * 255.).round() / 255.
|
||||
}
|
||||
|
||||
/// The opaque color an opaque `source` composites natively by the mode onto an opaque `backdrop`, by the W3C's formula, held in 8 bits.
|
||||
fn native(blend_mode: BlendMode, backdrop: [f64; 3], source: [f64; 3]) -> [f64; 3] {
|
||||
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
|
||||
let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode);
|
||||
[0, 1, 2].map(|channel| quantized(blended[channel] as f64))
|
||||
}
|
||||
|
||||
/// A color recolored, held in 8 bits.
|
||||
fn recolored(recolor: Recolor, color: [f64; 3]) -> [f64; 3] {
|
||||
color.map(|channel| quantized(recolor.scale * channel + recolor.offset))
|
||||
}
|
||||
|
||||
/// The opaque color the `recipe` builds from an opaque `layer` over an opaque `backdrop`, compositing natively by the W3C's formulas, each result held in 8 bits.
|
||||
fn emulated(recipe: &BlendRecipe, backdrop: [f64; 3], layer: [f64; 3]) -> [f64; 3] {
|
||||
match recipe {
|
||||
BlendRecipe::Stages(stages) => {
|
||||
let mut result = backdrop;
|
||||
for stage in stages {
|
||||
result = recolored(stage.base, result);
|
||||
for step in &stage.steps {
|
||||
result = native(step.blend_mode, result, recolored(step.recolor, layer));
|
||||
}
|
||||
result = recolored(stage.stretch, result);
|
||||
}
|
||||
result
|
||||
}
|
||||
BlendRecipe::HardMixThreshold => {
|
||||
let reaches_white = |offset: f64| native(BlendMode::ColorDodge, backdrop, recolored(Recolor { scale: 1., offset }, layer)).map(|channel| quantized(255. * channel - 254.));
|
||||
let at_white = native(BlendMode::Multiply, backdrop, reaches_white(0.));
|
||||
native(BlendMode::Lighten, at_white, reaches_white(-1. / 255.))
|
||||
}
|
||||
BlendRecipe::Pick { lighter } => {
|
||||
let moved = native(BlendMode::Luminosity, backdrop, layer);
|
||||
let toward = native(if *lighter { BlendMode::Lighten } else { BlendMode::Darken }, moved, backdrop);
|
||||
let change = native(BlendMode::Difference, toward, backdrop);
|
||||
let layer_wins = change.iter().sum::<f64>() * 255. >= 1.;
|
||||
if layer_wins { layer } else { backdrop }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Colors on the 8-bit grid, which a render's inputs lie on.
|
||||
fn levels(colors: &[[u8; 3]]) -> Vec<[f64; 3]> {
|
||||
colors.iter().map(|color| color.map(|level| level as f64 / 255.)).collect()
|
||||
}
|
||||
|
||||
/// How many levels the recipe's result may stray from the CPU's at a `fill` below full, where the layer's recolored channels round to whole levels:
|
||||
/// none at full strength, which leaves them whole, a level otherwise, and on Hard Mix's ramp half a level stretched by `1 / (1 - steepness)`, more past a level.
|
||||
fn tolerance(blend_mode: BlendMode, fill: f64) -> f64 {
|
||||
match (fill < 1., blend_mode) {
|
||||
(false, _) => 0.5,
|
||||
(true, BlendMode::HardMix) => 1. + 0.5 / (1. - 255. * fill / 256.),
|
||||
// Burning and dodging by a nearly black or white layer stretch its rounding most, by up to a fifth across these colors
|
||||
(true, BlendMode::VividLight | BlendMode::ColorDodge | BlendMode::ColorBurn) => 3.,
|
||||
(true, _) => 1.,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipes_build_each_mode_from_native_compositing_at_full_strength_exactly() {
|
||||
// Every level of a gray backdrop under every level of a gray layer, and a spread of colors
|
||||
let grays: Vec<[f64; 3]> = (0..=255).map(|level| [level as f64 / 255.; 3]).collect();
|
||||
let colors = levels(&[
|
||||
[0, 0, 0],
|
||||
[255, 255, 255],
|
||||
[204, 51, 128],
|
||||
[30, 200, 90],
|
||||
[128, 128, 128],
|
||||
[250, 180, 20],
|
||||
[64, 96, 230],
|
||||
[127, 129, 140],
|
||||
]);
|
||||
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
|
||||
|
||||
for blend_mode in MODES.into_iter().filter(|blend_mode| !matches!(blend_mode, BlendMode::DarkerColor | BlendMode::LighterColor)) {
|
||||
let recipe = recipe(blend_mode, 1.).expect("SVG lacks the mode");
|
||||
for (backdrops, layers) in [(&grays, &grays), (&colors, &colors)] {
|
||||
for &backdrop in backdrops {
|
||||
for &layer in layers {
|
||||
let svg = emulated(&recipe, backdrop, layer);
|
||||
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, 1.);
|
||||
for channel in 0..3 {
|
||||
assert!(
|
||||
(svg[channel] - cpu[channel] as f64).abs() * 255. <= 0.5 + 1e-4,
|
||||
"{blend_mode} of {layer:?} over {backdrop:?} gives {svg:?} in SVG and {cpu:?} on the CPU"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipes_build_each_mode_from_native_compositing_below_full_strength_within_their_rounding() {
|
||||
let colors = levels(&[
|
||||
[0, 0, 0],
|
||||
[255, 255, 255],
|
||||
[204, 51, 128],
|
||||
[30, 200, 90],
|
||||
[128, 128, 128],
|
||||
[250, 180, 20],
|
||||
[64, 96, 230],
|
||||
[127, 129, 140],
|
||||
]);
|
||||
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
|
||||
|
||||
for blend_mode in MODES.into_iter().filter(BlendMode::fill_moves_layer_toward_neutral).chain(BELOW_FULL_FILL) {
|
||||
for fill in [0.8, 0.6, 0.25, 0.] {
|
||||
let recipe = recipe(blend_mode, fill).expect("SVG lacks the mode");
|
||||
for &backdrop in &colors {
|
||||
for &layer in &colors {
|
||||
let svg = emulated(&recipe, backdrop, layer);
|
||||
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, fill as f32);
|
||||
for channel in 0..3 {
|
||||
let difference = (svg[channel] - cpu[channel] as f64).abs() * 255.;
|
||||
assert!(
|
||||
difference <= tolerance(blend_mode, fill),
|
||||
"{blend_mode} at fill {fill} of {layer:?} over {backdrop:?} gives {svg:?} in SVG and {cpu:?} on the CPU"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn darker_and_lighter_color_pick_as_on_the_cpu_but_may_keep_the_backdrop_within_half_a_level_of_luma() {
|
||||
let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.];
|
||||
let luma = |color: [f64; 3]| 255. * (0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2]);
|
||||
|
||||
// Pairs of colors around ties of luma, by a fraction of a level or a level or more, with channels at black and white where Luminosity clips
|
||||
let colors = levels(&[
|
||||
[0, 0, 255],
|
||||
[0, 48, 0],
|
||||
[0, 47, 0],
|
||||
[0, 49, 0],
|
||||
[255, 0, 0],
|
||||
[0, 130, 0],
|
||||
[10, 120, 40],
|
||||
[128, 128, 128],
|
||||
[100, 140, 140],
|
||||
[255, 255, 255],
|
||||
[0, 0, 0],
|
||||
[255, 254, 255],
|
||||
]);
|
||||
for lighter in [false, true] {
|
||||
let blend_mode = if lighter { BlendMode::LighterColor } else { BlendMode::DarkerColor };
|
||||
for &backdrop in &colors {
|
||||
for &layer in &colors {
|
||||
let svg = emulated(&BlendRecipe::Pick { lighter }, backdrop, layer);
|
||||
let difference = luma(layer) - luma(backdrop);
|
||||
let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, 1.);
|
||||
let cpu = [cpu[0] as f64, cpu[1] as f64, cpu[2] as f64];
|
||||
// It picks what the CPU picks, or within half a level of a tie, where Luminosity may move no channel a level, it may keep the backdrop, as at a tie
|
||||
let near_tie = difference.abs() < 0.5;
|
||||
assert!(svg == cpu.map(quantized) || (near_tie && svg == backdrop), "{blend_mode} of {layer:?} over {backdrop:?} picks {svg:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Blue's luma lies just under green's, so Darker Color keeps the blue backdrop
|
||||
let (blue, green) = ([0., 0., 1.], [0., 48. / 255., 0.]);
|
||||
assert_eq!(emulated(&BlendRecipe::Pick { lighter: false }, blue, green), blue);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_blend_by_the_alpha_beneath_and_their_own_as_on_the_cpu() {
|
||||
let (backdrop, layer) = ([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]);
|
||||
|
||||
// Color Dodge and Color Burn blend so only below a full fill
|
||||
let cases = [(1., 0.5, 1., 1.), (0.5, 1., 0.6, 1.), (0.75, 0.25, 0.4, 0.7), (1., 0., 0.5, 1.), (1., 0.5, 0., 1.)];
|
||||
let modes_and_cases = MODES.into_iter().chain(BELOW_FULL_FILL).flat_map(|blend_mode| cases.map(|case| (blend_mode, case)));
|
||||
for (blend_mode, (layer_alpha, backdrop_alpha, fill, opacity)) in modes_and_cases.filter(|(blend_mode, (_, _, fill, _))| *fill < 1. || blend_mode.reads_backdrop()) {
|
||||
// Only a fill moving the layer toward neutral reaches the blend, which shows it by the alpha beneath, and the layer is otherwise already faded by it
|
||||
let moves = blend_mode.fill_moves_layer_toward_neutral();
|
||||
let blend_fill = if moves { fill } else { 1. };
|
||||
let drawn_alpha = if moves { layer_alpha } else { layer_alpha * fill };
|
||||
let blend = emulated(&recipe(blend_mode, blend_fill).unwrap(), backdrop, layer);
|
||||
|
||||
// The layer made opaque, the blend over it by the alpha beneath, all shown by the layer's alpha, its fill's weight, and its opacity over what lies beneath
|
||||
let shown = opacity * drawn_alpha * layer_fill_shown(backdrop_alpha as f32, blend_fill as f32) as f64;
|
||||
let svg: Vec<f64> = (0..3)
|
||||
.map(|channel| shown * (backdrop_alpha * blend[channel] + (1. - backdrop_alpha) * layer[channel]) + (1. - shown) * backdrop_alpha * backdrop[channel])
|
||||
.chain([shown + (1. - shown) * backdrop_alpha])
|
||||
.collect();
|
||||
|
||||
// The CPU blends the full-strength content by the fill, then the opacity mixes from what lies beneath to that
|
||||
let premultiplied = |color: [f64; 3], alpha: f64| [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha].map(|channel| channel as f32);
|
||||
let beneath = premultiplied(backdrop, backdrop_alpha);
|
||||
let blended = blend_layer_pixel(premultiplied(layer, layer_alpha), beneath, blend_mode, fill as f32);
|
||||
for channel in 0..4 {
|
||||
let cpu = beneath[channel] as f64 + (blended[channel] - beneath[channel]) as f64 * opacity;
|
||||
assert!(
|
||||
(svg[channel] - cpu).abs() * 255. <= 2.,
|
||||
"{blend_mode} at layer alpha {layer_alpha}, alpha beneath {backdrop_alpha}, fill {fill}, and opacity {opacity}: {svg:?} in SVG against {cpu} in channel {channel} on the CPU"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modes_svg_has_take_no_recipe() {
|
||||
for blend_mode in BlendMode::list().into_iter().flatten() {
|
||||
assert_eq!(recipe(*blend_mode, 1.).is_some(), blend_mode.reads_backdrop(), "{blend_mode}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ impl BlendModeExt for BlendMode {
|
||||
BlendMode::Saturation => peniko::Mix::Saturation,
|
||||
BlendMode::Color => peniko::Mix::Color,
|
||||
BlendMode::Luminosity => peniko::Mix::Luminosity,
|
||||
// Like SVG, the modes that layers can't blend by fall back to normal
|
||||
// Vello lacks the rest, so they draw normally, and layers in those reading what lies beneath blend in an effects group (see `BlendMode::reads_backdrop`)
|
||||
_ => peniko::Mix::Normal,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::{Image, ImageSource, PaintType, PencilGradient, TextureId, TextureRegion};
|
||||
|
||||
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
|
||||
const SHAPE_TOLERANCE: f64 = 0.1;
|
||||
@@ -47,6 +47,16 @@ pub struct VelloSceneBuilder<'a> {
|
||||
effects_renderer: Option<&'a mut dyn EffectsRenderer>,
|
||||
/// The coverage the next effects group drawn outputs in place of its result, for an SVG map of it.
|
||||
effect_capture: Option<EffectCapture>,
|
||||
/// How many placed drawings are open, each a backdrop root of its own, like a thumbnail of an atlas.
|
||||
placed_depth: u32,
|
||||
/// How many pixels past the scene's edges the content reading what lies beneath it reads, which a render of the scene grown by as much holds.
|
||||
backdrop_apron: u32,
|
||||
/// Each content drawn so far reading what lies beneath it, as its bounds in the scene and how many pixels past them it reads along each axis, for later content reading through it.
|
||||
backdrop_readers: Vec<(Rect, DVec2)>,
|
||||
/// The widest apron a render of the scene grown for content reading past its edges can have, up to which such content stops the drawing, or 0 to draw everything.
|
||||
largest_apron: u32,
|
||||
/// Whether the scene still draws, rather than only measuring the apron after content reading past its edges stopped it.
|
||||
drawing: bool,
|
||||
}
|
||||
|
||||
/// Renders the content of a scene's effects groups offscreen and carries out their effects, while the scene is drawn.
|
||||
@@ -58,6 +68,7 @@ pub trait EffectsRenderer: Send {
|
||||
/// returning one for each of the `layers` that `effects` carried out on it draw, with the mode it blends by.
|
||||
/// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers.
|
||||
/// The `frame`, in the texture's pixels, is what effects relative to the content's extent take as their own.
|
||||
/// `backdrop` is what lies beneath, for the effects that read it, with the placement of the textures' pixels in it.
|
||||
/// With a `capture`, the only texture instead holds that effect's coverage, as black with it in alpha.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_effects(
|
||||
@@ -70,10 +81,62 @@ pub trait EffectsRenderer: Send {
|
||||
opacity: f32,
|
||||
effect_to_pixels: DAffine2,
|
||||
frame: Option<EffectFrame>,
|
||||
backdrop: Option<(&wgpu::Texture, Affine)>,
|
||||
capture: Option<EffectCapture>,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) -> Vec<(wgpu::Texture, core_types::blending::BlendMode)>;
|
||||
|
||||
/// Renders a `scene` drawn so far, with the `images` it draws, into a premultiplied texture of its size, as the backdrop of what's drawn next.
|
||||
/// `None` if it fails to render.
|
||||
fn render_backdrop(&mut self, _scene: &vello_gpu::Scene, _images: &[SceneImage], _max_texture_size: u32) -> Option<wgpu::Texture> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 PencilGradient),
|
||||
}
|
||||
|
||||
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 PencilGradient> for SceneBrush<'b> {
|
||||
fn from(gradient: &'b PencilGradient) -> Self {
|
||||
Self::Apollonian(gradient)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels behind an image the scene draws.
|
||||
@@ -127,7 +190,12 @@ impl GeneratorTile {
|
||||
#[derive(Debug)]
|
||||
enum Pushed {
|
||||
Layer,
|
||||
Clip,
|
||||
/// With the path it clips to, given in the scene's space, so it can be pushed again in a scene continuing this one.
|
||||
Clip {
|
||||
path: BezPath,
|
||||
transform: Affine,
|
||||
fill_rule: Fill,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for VelloSceneBuilder<'_> {
|
||||
@@ -157,6 +225,11 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
pushed: Vec::new(),
|
||||
effects_renderer: None,
|
||||
effect_capture: None,
|
||||
placed_depth: 0,
|
||||
backdrop_apron: 0,
|
||||
backdrop_readers: Vec::new(),
|
||||
largest_apron: 0,
|
||||
drawing: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,6 +239,18 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Stops drawing at the first content reading what lies beneath it past the scene's edges by at most `largest_apron` pixels, which a render grown by as much draws instead.
|
||||
/// The scene then only measures how far past its edges the rest reads, for that render's apron.
|
||||
pub fn stopping_for_an_apron_up_to(mut self, largest_apron: u32) -> Self {
|
||||
self.largest_apron = largest_apron;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the scene drew all its content, rather than stopping at content reading past its edges.
|
||||
pub fn drew_everything(&self) -> bool {
|
||||
self.drawing
|
||||
}
|
||||
|
||||
/// Has the next effects group drawn output the coverage `capture` names in place of its result, leaving the groups drawn within it as they are.
|
||||
pub fn capture_next_effects(&mut self, capture: EffectCapture) {
|
||||
self.effect_capture = Some(capture);
|
||||
@@ -188,6 +273,11 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
self.max_texture_size
|
||||
}
|
||||
|
||||
/// How many pixels past the scene's edges the content drawn so far that reads what lies beneath it reads, which the scene doesn't hold.
|
||||
pub fn backdrop_apron(&self) -> u32 {
|
||||
self.backdrop_apron
|
||||
}
|
||||
|
||||
/// The finished Vello GPU scene and the images its external textures stand for, closing whatever layers and clips were left open.
|
||||
pub fn finish(mut self) -> (vello_gpu::Scene, Vec<SceneImage>) {
|
||||
if !self.pushed.is_empty() {
|
||||
@@ -206,10 +296,13 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
}
|
||||
|
||||
/// Draws what `draw` draws placed by `placement` within the view, as content with its own document space for its effects' lengths, like each thumbnail of an atlas.
|
||||
/// It's a backdrop root of its own with nothing beneath it to read, as a run of effects drawn into another run's content is.
|
||||
pub fn draw_placed(&mut self, placement: Affine, draw: impl FnOnce(&mut Self)) {
|
||||
let outer_view = self.view;
|
||||
self.view = outer_view * placement;
|
||||
self.placed_depth += 1;
|
||||
draw(self);
|
||||
self.placed_depth -= 1;
|
||||
self.view = outer_view;
|
||||
}
|
||||
|
||||
@@ -222,73 +315,140 @@ 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) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
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_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) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
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_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>) {
|
||||
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||
pub fn fill_viewport<'b>(&mut self, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>) {
|
||||
if !self.drawing {
|
||||
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));
|
||||
}
|
||||
|
||||
/// Begins an isolated layer clipped to `clip`, given in the space of `transform`. Must be balanced by [`Self::pop_layer`].
|
||||
pub fn push_layer(&mut self, fill_rule: Fill, blend_mode: impl Into<BlendMode>, alpha: f32, transform: Affine, clip: &impl Shape) {
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene
|
||||
.push_layer(Some(&finite_path(&clip.to_path(SHAPE_TOLERANCE))), Some(blend_mode.into()), Some(alpha), None, None);
|
||||
if self.drawing {
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene
|
||||
.push_layer(Some(&finite_path(&clip.to_path(SHAPE_TOLERANCE))), Some(blend_mode.into()), Some(alpha), None, None);
|
||||
}
|
||||
self.pushed.push(Pushed::Layer);
|
||||
}
|
||||
|
||||
/// Begins an isolated layer covering the whole scene, for content without bounds. Must be balanced by [`Self::pop_layer`].
|
||||
pub fn push_viewport_layer(&mut self, blend_mode: impl Into<BlendMode>, alpha: f32) {
|
||||
self.scene.push_layer(None, Some(blend_mode.into()), Some(alpha), None, None);
|
||||
if self.drawing {
|
||||
self.scene.push_layer(None, Some(blend_mode.into()), Some(alpha), None, None);
|
||||
}
|
||||
self.pushed.push(Pushed::Layer);
|
||||
}
|
||||
|
||||
/// Clips the content that follows to `clip`, given in the space of `transform`, without isolating it. Must be balanced by [`Self::pop_layer`].
|
||||
pub fn push_clip_layer(&mut self, fill_rule: Fill, transform: Affine, clip: &impl Shape) {
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene.push_clip_path(&finite_path(&clip.to_path(SHAPE_TOLERANCE)));
|
||||
self.pushed.push(Pushed::Clip);
|
||||
// The path is kept to begin the clip again after a render of the scene so far, copied only if it had to be made finite
|
||||
let path = clip.to_path(SHAPE_TOLERANCE);
|
||||
let finite = match finite_path(&path) {
|
||||
Cow::Owned(finite) => Some(finite),
|
||||
Cow::Borrowed(_) => None,
|
||||
};
|
||||
let (path, transform) = (finite.unwrap_or(path), self.view * transform);
|
||||
if self.drawing {
|
||||
self.scene.set_transform(transform);
|
||||
self.scene.set_fill_rule(fill_rule);
|
||||
self.scene.push_clip_path(&path);
|
||||
}
|
||||
self.pushed.push(Pushed::Clip { path, transform, fill_rule });
|
||||
}
|
||||
|
||||
/// Ends the most recent layer or clip.
|
||||
pub fn pop_layer(&mut self) {
|
||||
match self.pushed.pop() {
|
||||
Some(Pushed::Layer) => self.scene.pop_layer(),
|
||||
Some(Pushed::Clip) => self.scene.pop_clip(),
|
||||
Some(Pushed::Layer) if self.drawing => self.scene.pop_layer(),
|
||||
Some(Pushed::Clip { .. }) if self.drawing => self.scene.pop_clip(),
|
||||
Some(_) => {}
|
||||
None => log::error!("A scene ends a layer or clip it never began"),
|
||||
}
|
||||
}
|
||||
|
||||
/// What's drawn so far, which lies beneath what's drawn next, in a premultiplied texture the size of the scene.
|
||||
/// The scene is rendered so far and continues from an image of that render. `None` where content has nothing beneath it to read, or once the scene stopped drawing.
|
||||
pub fn backdrop(&mut self) -> Option<wgpu::Texture> {
|
||||
if !self.drawing || !self.backdrop_readable() {
|
||||
return None;
|
||||
}
|
||||
let renderer = self.effects_renderer.as_deref_mut()?;
|
||||
|
||||
// The clips end for the render, then begin again in the scene continuing it
|
||||
self.pushed.iter().for_each(|_| self.scene.pop_clip());
|
||||
let rendered = renderer.render_backdrop(&self.scene, &self.images, self.max_texture_size);
|
||||
if rendered.is_some() {
|
||||
self.scene.reset();
|
||||
self.images.clear();
|
||||
self.image_ids.clear();
|
||||
}
|
||||
let backdrop = rendered.inspect(|backdrop| {
|
||||
self.images.push(SceneImage::Rendered(backdrop.clone()));
|
||||
let area = Rect::new(0., 0., backdrop.width() as f64, backdrop.height() as f64);
|
||||
self.scene.set_transform(Affine::IDENTITY);
|
||||
self.scene.set_paint(PaintType::Image(Image {
|
||||
image: ImageSource::external_texture(TextureId(0), TextureRegion::Full, true),
|
||||
sampler: peniko::ImageSampler::new(),
|
||||
}));
|
||||
self.scene.set_paint_transform(Affine::IDENTITY);
|
||||
self.scene.fill_rect(&area);
|
||||
});
|
||||
for pushed in &self.pushed {
|
||||
if let Pushed::Clip { path, transform, fill_rule } = pushed {
|
||||
self.scene.set_transform(*transform);
|
||||
self.scene.set_fill_rule(*fill_rule);
|
||||
self.scene.push_clip_path(path);
|
||||
}
|
||||
}
|
||||
|
||||
backdrop
|
||||
}
|
||||
|
||||
/// Whether content drawn now has what lies beneath it to read, which it hasn't within an isolated layer, where what lies beneath is only the part inside the layer,
|
||||
/// within a placed drawing, where the content lies over nothing of its own, or without a renderer.
|
||||
fn backdrop_readable(&self) -> bool {
|
||||
self.placed_depth == 0 && !self.pushed.iter().any(|pushed| matches!(pushed, Pushed::Layer)) && self.effects_renderer.is_some()
|
||||
}
|
||||
|
||||
/// Draws an image's rectangle of pixels, from the origin to its width and height, placed by `transform`.
|
||||
pub fn draw_image(&mut self, image: &peniko::ImageBrush, transform: Affine) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Pixels(image.image.clone())) else {
|
||||
return;
|
||||
};
|
||||
@@ -297,6 +457,9 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
/// Draws a CPU raster's rectangle of pixels with `adjustments` carried out on them, from the origin to its width and height, placed by `transform`.
|
||||
pub fn draw_raster(&mut self, raster: Raster<CPU>, adjustments: Vec<Adjustment>, sampler: peniko::ImageSampler, transform: Affine) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Raster { raster, adjustments }) else {
|
||||
return;
|
||||
};
|
||||
@@ -305,6 +468,9 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
/// Draws a GPU texture's rectangle of pixels, from the origin to its width and height, placed by `transform`.
|
||||
pub fn draw_texture(&mut self, texture: Texture, sampler: peniko::ImageSampler, transform: Affine) {
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Texture(texture)) else {
|
||||
return;
|
||||
};
|
||||
@@ -317,7 +483,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
let local_to_device = self.view * transform;
|
||||
let [a, b, c, d, _, _] = local_to_device.as_coeffs();
|
||||
let determinant = a * d - b * c;
|
||||
if !determinant.is_normal() {
|
||||
if !self.drawing || !determinant.is_normal() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -409,15 +575,21 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
let layers = EffectLayers::plan(effects, blend_mode, fill, layered);
|
||||
|
||||
// The texture follows the viewport's axes if the effect space only turns and evenly scales, or else its own axes, scaled evenly to keep every direction's detail.
|
||||
// A box blur or a minimum or maximum, whose square neighborhoods aren't round, turns with its space only along that space's axes.
|
||||
// A box blur (of the content or what lies beneath it) or a minimum or maximum, whose square neighborhoods aren't round, turns with its space only along that space's axes.
|
||||
let has_square_kernel = effects.operations().any(|operation| {
|
||||
let square = matches!(operation, EffectOperation::Blur { box_blur: true, .. } | EffectOperation::MinimumMaximum { .. });
|
||||
let square = matches!(
|
||||
operation,
|
||||
EffectOperation::Blur { box_blur: true, .. } | EffectOperation::BackgroundBlur { box_blur: true, .. } | EffectOperation::MinimumMaximum { .. }
|
||||
);
|
||||
square && !operation.changes_nothing()
|
||||
});
|
||||
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
|
||||
let (frame_to_device, lengths_to_frame) = match follows_viewport {
|
||||
true => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
||||
false => {
|
||||
// Effects that don't commute with resampling, like a median, work on the content's own grid of a texel to each unit of the effect space, then resample to the view
|
||||
let content_grid_resolution = effects.content_grid_resolution();
|
||||
let (frame_to_device, lengths_to_frame) = match (content_grid_resolution, follows_viewport) {
|
||||
(Some(_), _) => (effect_to_device, DMat2::IDENTITY),
|
||||
(None, true) => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
||||
(None, false) => {
|
||||
let density = largest_stretch(effect_to_device.matrix2);
|
||||
(effect_to_device * DAffine2::from_scale(DVec2::splat(1. / density)), DMat2::from_diagonal(DVec2::splat(density)))
|
||||
}
|
||||
@@ -478,21 +650,74 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
// A region too large for one texture, or for its memory, renders at a lower resolution, which the blurs and shadows that make it so large hide.
|
||||
// Its size rounds up to a size class so a group that moves between renders keeps reusing the same textures.
|
||||
let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt()).min(1.);
|
||||
let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt());
|
||||
let resolution = resolution.min(content_grid_resolution.unwrap_or(1.)).min(1.);
|
||||
|
||||
// A coarsened content grid keeps its texels on one lattice of the effect space, so they don't slide across the content as the view pans
|
||||
if content_grid_resolution.is_some() && resolution < 1. {
|
||||
let snap = |coordinate: f64| (coordinate * resolution).floor() / resolution;
|
||||
region = Rect::new(snap(region.x0), snap(region.y0), region.x1, region.y1);
|
||||
}
|
||||
|
||||
let size_along = |length: f64| ((length * resolution).ceil() as u32).next_multiple_of(EFFECTS_SIZE_CLASS).min(max_size);
|
||||
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
||||
let origin = region.origin().to_vec2();
|
||||
|
||||
// What lies beneath, for the effects that read it, where each of the effects texture's pixels lands in it.
|
||||
// Content without bounds reads nothing, as in SVG, and content reading past the scene's edges asks for the scene to be rendered grown by as much.
|
||||
let reads_backdrop = (layers.reads_backdrop() || layers.content_reads_backdrop(fill)) && capture.is_none() && bounds.is_some() && self.backdrop_readable();
|
||||
if reads_backdrop && layers.reads_around_backdrop() {
|
||||
// A box reaches as far along each axis of the view as its square turned into it does, and a Gaussian as far every way as its widest stretch
|
||||
let readers = (effects.operations()).filter(|operation| matches!(operation, graphic_types::EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing());
|
||||
let linear = effect_to_device.matrix2;
|
||||
let backdrop_reach: DVec2 = readers
|
||||
.map(|operation| match operation {
|
||||
graphic_types::EffectOperation::BackgroundBlur { box_blur: true, .. } => operation.reach() * (linear.abs() * DVec2::ONE),
|
||||
_ => DVec2::splat(operation.reach() * largest_stretch(linear)),
|
||||
})
|
||||
.sum();
|
||||
|
||||
// The content in view reads what lies beneath only within its backdrop readers' reach, however far past the view the region extends
|
||||
let region_in_device = Affine::new(frame_to_device.to_cols_array()).transform_rect_bbox(region);
|
||||
let mut read_region = region_in_device.intersect(viewport.inflate(backdrop_reach.x, backdrop_reach.y));
|
||||
|
||||
// Content farther from the view than its backdrop reach needs no apron of its own, though later content reading through it may
|
||||
if read_region.width() > 0. && read_region.height() > 0. {
|
||||
// Where it reads earlier content reading what lies beneath, it reads what that content read too, from the latest back. O(readers drawn so far).
|
||||
for &(earlier_bounds, earlier_reach) in self.backdrop_readers.iter().rev() {
|
||||
let overlap = earlier_bounds.intersect(read_region);
|
||||
if overlap.width() > 0. && overlap.height() > 0. {
|
||||
read_region = read_region.union(overlap.inflate(earlier_reach.x, earlier_reach.y));
|
||||
}
|
||||
}
|
||||
|
||||
let past_edges = (-read_region.x0).max(-read_region.y0).max(read_region.x1 - viewport.x1).max(read_region.y1 - viewport.y1);
|
||||
self.backdrop_apron = self.backdrop_apron.max(past_edges.max(0.).ceil() as u32);
|
||||
}
|
||||
self.backdrop_readers.extend(bounds.map(|bounds| (self.view.transform_rect_bbox(bounds), backdrop_reach)));
|
||||
}
|
||||
|
||||
// Content reading past the edges by no more than a grown render holds stops the drawing, leaving all of it to that render
|
||||
if (1..=self.largest_apron).contains(&self.backdrop_apron) {
|
||||
self.drawing = false;
|
||||
}
|
||||
if !self.drawing {
|
||||
return;
|
||||
}
|
||||
let backdrop = reads_backdrop.then(|| self.backdrop()).flatten();
|
||||
|
||||
let texture_to_device = Affine::new(frame_to_device.to_cols_array()) * Affine::translate(origin) * Affine::scale(1. / resolution);
|
||||
|
||||
let frame_to_pixels = Affine::scale(resolution) * Affine::translate(-origin);
|
||||
let content_view = frame_to_pixels * document_to_frame;
|
||||
let effect_to_pixels = DAffine2::from_cols_array(&content_view.as_coeffs()) * effect_space;
|
||||
let effect_frame = effect_frame.map(|frame| frame.placed(DAffine2::from_cols_array(&frame_to_pixels.as_coeffs())));
|
||||
let Some(renderer) = self.effects_renderer.as_deref_mut() else { return };
|
||||
let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, effect_frame, capture, draw_paint, draw);
|
||||
let backdrop = backdrop.as_ref().map(|backdrop| (backdrop, texture_to_device));
|
||||
let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, effect_frame, backdrop, capture, draw_paint, draw);
|
||||
|
||||
// Draw each layer where the content was, blended onto what lies beneath, except a captured coverage, which is drawn as it is
|
||||
let area = Rect::new(0., 0., size.x as f64, size.y as f64);
|
||||
let texture_to_device = Affine::new(frame_to_device.to_cols_array()) * Affine::translate(origin) * Affine::scale(1. / resolution);
|
||||
for (texture, blend_mode) in results {
|
||||
let isolated = capture.is_none() && (opacity < 1. || blend_mode != core_types::blending::BlendMode::Normal);
|
||||
if isolated {
|
||||
@@ -526,22 +751,27 @@ 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_pencil_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,
|
||||
|
||||
@@ -2,6 +2,7 @@ use crate::clip::clipped_to;
|
||||
use crate::{bezpath, graphic_list};
|
||||
use core_types::Color;
|
||||
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, Item, List};
|
||||
use graphic_types::masks::{MaskMode, mask_coverage};
|
||||
use graphic_types::{Appearance, CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||
use usvg::tiny_skia_path::PathBuilder;
|
||||
|
||||
@@ -50,5 +51,5 @@ fn luminance_to_alpha(content: &mut List<Graphic>) {
|
||||
|
||||
fn luminance_as_alpha(color: Color) -> Color {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
Color::BLACK.with_alpha((0.2126 * red + 0.7152 * green + 0.0722 * blue) * alpha)
|
||||
Color::BLACK.with_alpha(mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::LuminanceSvg))
|
||||
}
|
||||
@@ -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.)))
|
||||
@@ -204,7 +211,7 @@ fn a_clip_path_becomes_a_hidden_clipper_beneath_the_content_it_clips() -> Result
|
||||
let content = converted(r#"<clipPath id="clip"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)"><rect width="8" height="8"/></g>"#)?;
|
||||
|
||||
let clipped = group(&content, 0);
|
||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
|
||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
|
||||
assert_eq!(clipped.and_then(|clipped| clipped.attribute::<f64>(ATTR_OPACITY_FILL, 0)), Some(&0.));
|
||||
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||
Ok(())
|
||||
@@ -282,11 +289,19 @@ fn a_stroked_even_odd_path_strokes_its_original_outline_above_the_converted_fill
|
||||
|
||||
#[test]
|
||||
fn a_luminance_mask_masks_by_the_luminance_of_its_paints_as_alpha() -> Result<(), Error> {
|
||||
let content = converted(r##"<mask id="mask"><rect width="8" height="8" fill="#808080"/></mask><g mask="url(#mask)"><rect width="8" height="8"/></g>"##)?;
|
||||
// Pure green takes SVG's own weight for it, as the Luminance (SVG) mask mode does
|
||||
for (fill, alpha) in [("#808080", 128. / 255.), ("#00ff00", 0.7154)] {
|
||||
let content = converted(&format!(
|
||||
r##"<mask id="mask"><rect width="8" height="8" fill="{fill}"/></mask><g mask="url(#mask)"><rect width="8" height="8"/></g>"##
|
||||
))?;
|
||||
|
||||
let masker = group(&content, 0).and_then(|masked| group(masked, 0));
|
||||
let masker_paint = masker.and_then(appearance_of).and_then(|appearance| appearance.first_paint_of(Cover::Fill));
|
||||
assert!(matches!(masker_paint, Some(Graphic::Color(color)) if color.element().with_alpha(1.) == Color::BLACK && (color.element().a() - 128. / 255.).abs() < 1e-5));
|
||||
let masker = group(&content, 0).and_then(|masked| group(masked, 0));
|
||||
let masker_paint = masker.and_then(appearance_of).and_then(|appearance| appearance.first_paint_of(Cover::Fill));
|
||||
assert!(
|
||||
matches!(masker_paint, Some(Graphic::Color(color)) if color.element().with_alpha(1.) == Color::BLACK && (color.element().a() - alpha).abs() < 1e-5),
|
||||
"{fill} masks by {masker_paint:?}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -299,7 +314,7 @@ fn a_mask_region_that_cuts_its_content_clips_the_masked_content() -> Result<(),
|
||||
let within_region = group(&content, 0).and_then(|masked| masked.element(1));
|
||||
assert!(within_region.is_some_and(Graphic::had_clip_enabled));
|
||||
let clipped = within_region.and_then(Graphic::as_graphic_list);
|
||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
|
||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
|
||||
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -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`).
|
||||
@@ -1437,8 +1471,20 @@ impl Gradient {
|
||||
/// of it, since a map that isn't linear in the gradient's own space bends the ramp between the stops. Read the result with
|
||||
/// [`GradientSpace::RgbGamma`] and [`GradientInterpolation::Linear`] in place of the space and interpolation in `settings`.
|
||||
pub fn map_ramp(&self, settings: GradientSettings, map: impl Fn(Color) -> Color) -> Self {
|
||||
self.map_ramp_anchored(settings, map, None::<fn(Color)>)
|
||||
}
|
||||
|
||||
/// Like [`Gradient::map_ramp`], for a map that jumps wherever the `region` of the ramp's colors changes, as a cutoff on their levels does.
|
||||
/// Scanning for each change at the finest spacing the resampling reaches keeps a region lying between its probes, and the colors on both sides anchor the change at one position.
|
||||
pub fn map_ramp_by_regions<R: PartialEq>(&self, settings: GradientSettings, map: impl Fn(Color) -> Color, region: impl Fn(Color) -> R) -> Self {
|
||||
self.map_ramp_anchored(settings, map, Some(region))
|
||||
}
|
||||
|
||||
fn map_ramp_anchored<R: PartialEq>(&self, settings: GradientSettings, map: impl Fn(Color) -> Color, region: Option<impl Fn(Color) -> R>) -> Self {
|
||||
/// Deeper than this, an interval is under 1/4096 of the ramp, too short to see a step in the mapped colors smear.
|
||||
const MAX_DEPTH: u32 = 12;
|
||||
/// How many times a change of region is narrowed down from the step of the scan it lies in, far closer than any renderer resolves.
|
||||
const REGION_BISECTIONS: u32 = 32;
|
||||
|
||||
fn subdivide(ramp: &impl Fn(f64) -> Color, left: f64, right: f64, color_left: Color, color_right: Color, result: &mut Vec<GradientStop>, depth: u32) {
|
||||
// Probe the quarter points as well as the center, since a map with a steep toe peaks its deviation off-center
|
||||
@@ -1466,14 +1512,55 @@ impl Gradient {
|
||||
let ramp = |position: f64| map(evaluator.evaluate(position));
|
||||
|
||||
// Each stop anchors its own color, keeping the jump between coincident stops, and a cyclic ramp's seam anchors at both ends
|
||||
let mut anchors: Vec<(f64, Color)> = stops.iter().map(|stop| (stop.position, map(stop.color))).collect();
|
||||
let mut anchors: Vec<(f64, Color)> = stops.iter().map(|stop| (stop.position, stop.color)).collect();
|
||||
if settings.cyclic && anchors.first().is_some_and(|&(position, _)| position > 0.) {
|
||||
anchors.insert(0, (0., ramp(0.)));
|
||||
anchors.insert(0, (0., evaluator.evaluate(0.)));
|
||||
}
|
||||
if settings.cyclic && anchors.last().is_some_and(|&(position, _)| position < 1.) {
|
||||
anchors.push((1., ramp(0.)));
|
||||
anchors.push((1., evaluator.evaluate(0.)));
|
||||
}
|
||||
|
||||
// Scanned for in steps of a 4096th of the ramp, each change of region anchors the colors on both its sides at one position
|
||||
if let Some(region) = region {
|
||||
let extent = anchors.first().zip(anchors.last()).map_or(0., |(&(first, _), &(last, _))| last - first);
|
||||
let mut anchored = Vec::with_capacity(anchors.len());
|
||||
|
||||
for (index, &(left, color_left)) in anchors.iter().enumerate() {
|
||||
anchored.push((left, color_left));
|
||||
let Some(&(right, color_right)) = anchors.get(index + 1).filter(|&&(right, _)| right > left) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let steps = ((right - left) / extent * f64::from(1_u32 << MAX_DEPTH)).ceil().max(1.) as usize;
|
||||
let (mut previous_position, mut previous_color, mut previous_region) = (left, color_left, region(color_left));
|
||||
for step in 1..=steps {
|
||||
let position = if step == steps { right } else { left + (right - left) * step as f64 / steps as f64 };
|
||||
let color = if step == steps { color_right } else { evaluator.evaluate(position) };
|
||||
let current_region = region(color);
|
||||
|
||||
if current_region != previous_region {
|
||||
let (mut low, mut color_low, mut high, mut color_high) = (previous_position, previous_color, position, color);
|
||||
for _ in 0..REGION_BISECTIONS {
|
||||
let middle = (low + high) / 2.;
|
||||
let color_middle = evaluator.evaluate(middle);
|
||||
if region(color_middle) == previous_region {
|
||||
(low, color_low) = (middle, color_middle);
|
||||
} else {
|
||||
(high, color_high) = (middle, color_middle);
|
||||
}
|
||||
}
|
||||
anchored.extend([(high, color_low), (high, color_high)]);
|
||||
}
|
||||
|
||||
(previous_position, previous_color, previous_region) = (position, color, current_region);
|
||||
}
|
||||
}
|
||||
|
||||
anchors = anchored;
|
||||
}
|
||||
|
||||
let anchors: Vec<(f64, Color)> = anchors.into_iter().map(|(position, color)| (position, map(color))).collect();
|
||||
|
||||
let mut result = Vec::new();
|
||||
for (index, &(position, color)) in anchors.iter().enumerate() {
|
||||
result.push(GradientStop { position, midpoint: 0.5, color });
|
||||
@@ -1756,6 +1843,19 @@ 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)]
|
||||
@@ -2010,6 +2110,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,530 @@
|
||||
//! 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)]
|
||||
struct Homogeneous {
|
||||
numerator: f64,
|
||||
denominator: f64,
|
||||
}
|
||||
|
||||
impl Homogeneous {
|
||||
const INFINITY: Self = Self { numerator: 1., denominator: 0. };
|
||||
|
||||
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.
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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);
|
||||
|
||||
// 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);
|
||||
let radical_x = -line.c / line.b;
|
||||
|
||||
return Self::with_band(start, end, CrossingSelection::SameSideAs { radical_x }, None, 0., 1., svg_stand_in);
|
||||
}
|
||||
|
||||
// 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()
|
||||
});
|
||||
|
||||
// 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,820 @@
|
||||
//! 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::{GradientForm, GradientModel, wrapped_curvature};
|
||||
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.
|
||||
#[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),
|
||||
}
|
||||
|
||||
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, transform: DAffine2) -> Self {
|
||||
let [start, end] = [start_curvature, end_curvature].map(|curvature| wrapped_curvature(curvature, 0.));
|
||||
|
||||
match GradientForm::from_curvatures([start, end]) {
|
||||
Some(GradientForm::Linear) => Self::Linear,
|
||||
Some(GradientForm::Radial) => Self::Radial,
|
||||
None if !transform.matrix2.determinant().recip().is_finite() => Self::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }),
|
||||
None 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 => Self::Standard(GradientStandard::new(start, end)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether its position can fall before the start, which only a radial gradient's can't since its distance from the center never goes below zero.
|
||||
pub fn reaches_before_start(&self) -> bool {
|
||||
!matches!(self, Self::Radial)
|
||||
}
|
||||
|
||||
/// 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(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn svg_draws_exactly(&self) -> bool {
|
||||
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, 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, 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, placement), GradientShape::Standard(plain_ramp));
|
||||
|
||||
// The forms stay native under either model
|
||||
assert_eq!(GradientShape::new(0., 0., GradientModel::Apollonian, placement), GradientShape::Linear);
|
||||
assert_eq!(GradientShape::new(-1., 0.5, GradientModel::Apollonian, 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, 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, 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,14 @@
|
||||
extern crate log;
|
||||
|
||||
pub mod gradient;
|
||||
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, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
|
||||
pub use math::QuadExt;
|
||||
pub use vector::Vector;
|
||||
pub use vector::reference_point::ReferencePoint;
|
||||
|
||||
@@ -3,7 +3,6 @@ use crate::vector::flatten::WorkingVector;
|
||||
use crate::vector::misc::{BezierHandles, HandleId, HandleType};
|
||||
use crate::vector::path::{CurveType, Path, curve_types_of};
|
||||
use core_types::list::{ATTR_ID, List};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DVec2;
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
@@ -1086,16 +1085,49 @@ impl VectorModification {
|
||||
}
|
||||
}
|
||||
|
||||
// Intentionally non-deterministic: fields contain HashMaps with non-deterministic iteration order,
|
||||
// so we use a UUID to always bust the cache and force re-evaluation when any modification is present.
|
||||
// This will not actually lead to a cache invalidation in most cases due to the
|
||||
// graph inputs being wrapped in a `MemoHash` wrapper.
|
||||
// Hash sets and maps are hashed in key order, so equal modifications hash equally regardless of iteration order
|
||||
impl graphene_hash::CacheHash for PointModification {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.add.cache_hash(state);
|
||||
sorted_set(&self.remove).cache_hash(state);
|
||||
sorted_map(&self.delta).cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl graphene_hash::CacheHash for SegmentModification {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.add.cache_hash(state);
|
||||
sorted_set(&self.remove).cache_hash(state);
|
||||
sorted_map(&self.start_point).cache_hash(state);
|
||||
sorted_map(&self.end_point).cache_hash(state);
|
||||
sorted_map(&self.handle_primary).cache_hash(state);
|
||||
sorted_map(&self.handle_end).cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl graphene_hash::CacheHash for VectorModification {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
core::hash::Hash::hash(&generate_uuid(), state);
|
||||
self.points.cache_hash(state);
|
||||
self.segments.cache_hash(state);
|
||||
sorted_set(&self.add_g1_continuous).cache_hash(state);
|
||||
sorted_set(&self.remove_g1_continuous).cache_hash(state);
|
||||
sorted_set(&self.path_breaks).cache_hash(state);
|
||||
sorted_set(&self.turned_on_load).cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted_set<T: Ord>(set: &HashSet<T>) -> Vec<&T> {
|
||||
let mut items: Vec<_> = set.iter().collect();
|
||||
items.sort_unstable();
|
||||
items
|
||||
}
|
||||
|
||||
fn sorted_map<K: Ord, V>(map: &HashMap<K, V>) -> Vec<(&K, &V)> {
|
||||
let mut entries: Vec<_> = map.iter().collect();
|
||||
entries.sort_unstable_by_key(|&(key, _)| key);
|
||||
entries
|
||||
}
|
||||
|
||||
// TODO: Do we want to enforce that all serialized/deserialized hashmaps are a vec of tuples?
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Serializes as sorted `[[key, value], ...]` (sequence of pairs)
|
||||
@@ -1263,6 +1295,23 @@ mod tests {
|
||||
format!("{anchors:?}\n{segments:?}\n{strokes:?}\n{pairs:?}")
|
||||
}
|
||||
|
||||
fn cache_hash(modification: &VectorModification) -> u64 {
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
graphene_hash::CacheHash::cache_hash(modification, &mut hasher);
|
||||
std::hash::Hasher::finish(&hasher)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_modifications_hash_equally() {
|
||||
let (vector, paths) = mixed_geometry();
|
||||
|
||||
let first = VectorModification::create_from_vector(&vector, &paths);
|
||||
let second = VectorModification::create_from_vector(&vector, &paths);
|
||||
|
||||
assert_eq!(cache_hash(&first), cache_hash(&first));
|
||||
assert_eq!(cache_hash(&first), cache_hash(&second));
|
||||
}
|
||||
|
||||
/// Every curve type, a weld where they change, a smooth anchor, and a second subpath.
|
||||
fn mixed_geometry() -> (Vector, List<Path>) {
|
||||
let mut bezpath = BezPath::new();
|
||||
|
||||
@@ -2,6 +2,7 @@ mod buffer;
|
||||
mod context;
|
||||
mod deferred_svg_images;
|
||||
mod pipeline;
|
||||
mod raster_readback;
|
||||
mod texture_cache;
|
||||
pub mod texture_conversion;
|
||||
mod vello_adjustments;
|
||||
@@ -75,6 +76,19 @@ impl WgpuExecutor {
|
||||
/// Renders the document scene `draw` draws, with its content placed by `view`, into a new texture of `size` with straight alpha.
|
||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
||||
pub fn render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
||||
Ok(self.render_vello_and_failure(size, view, draw)?.0)
|
||||
}
|
||||
|
||||
/// Like [`Self::render_vello`], but failing rather than leaving transparent a part Vello GPU fails to render, for a render read back as data.
|
||||
pub fn try_render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
||||
match self.render_vello_and_failure(size, view, draw)? {
|
||||
(_, Some(failure)) => anyhow::bail!("Vello GPU failed to render: {failure}"),
|
||||
(texture, None) => Ok(texture),
|
||||
}
|
||||
}
|
||||
|
||||
/// The texture [`Self::render_vello`] renders, with the first failure that left part of it transparent.
|
||||
fn render_vello_and_failure(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<(Texture, Option<String>)> {
|
||||
let limit = self.context().device.limits().max_texture_dimension_2d;
|
||||
if size.x > limit || size.y > limit {
|
||||
anyhow::bail!("Render size {size} exceeds the GPU's texture size limit of {limit}");
|
||||
@@ -84,11 +98,12 @@ 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
|
||||
let failure = self
|
||||
.inner
|
||||
.vello_renderer
|
||||
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
|
||||
|
||||
Ok(texture)
|
||||
Ok((texture, failure))
|
||||
}
|
||||
|
||||
/// Renders a scene drawn beforehand, on a canvas the caller owns, into a new texture of the scene's size with straight alpha.
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
use crate::WgpuExecutor;
|
||||
use crate::texture_conversion::download_row_bytes;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::effects::{EffectOperation, Effects};
|
||||
use raster_kernels::adjustments::preserves_alpha;
|
||||
use raster_kernels::raster_effects::adjusted_raster;
|
||||
use raster_types::{CPU, Image, Pixels, Raster};
|
||||
use rendering::{Render, RenderOutputType, RenderParams, leading_raster_adjustments};
|
||||
|
||||
/// The most pixels an image may grow to with the margin its effects paint into, beyond which the margin is cut short.
|
||||
const MAX_PIXELS_WITH_MARGIN: f64 = (1 << 24) as f64;
|
||||
|
||||
/// The GPU's limits that a readback's renders and downloads stay within.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ReadbackLimits {
|
||||
/// The most pixels across or down a texture may have, which an image larger than it is downscaled to when uploaded whole.
|
||||
texture_size: u32,
|
||||
/// The most bytes a download buffer may hold.
|
||||
buffer_size: u64,
|
||||
}
|
||||
|
||||
impl ReadbackLimits {
|
||||
fn of(executor: &WgpuExecutor) -> Self {
|
||||
let limits = executor.context().device.limits();
|
||||
Self {
|
||||
texture_size: limits.max_texture_dimension_2d,
|
||||
buffer_size: limits.max_buffer_size,
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest tile, at most `max` pixels across and down, that a texture and its download buffer can hold, or `None` if not even one pixel fits.
|
||||
fn tile_size(&self, max: UVec2) -> Option<UVec2> {
|
||||
// Each row's bytes are padded to 256, which 64 pixels fill
|
||||
let widest_row = (self.buffer_size / wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as u64 * 64).min(u32::MAX as u64) as u32;
|
||||
let width = max.x.min(self.texture_size).min(widest_row);
|
||||
if width == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let height = max.y.min(self.texture_size).min((self.buffer_size / download_row_bytes(width) as u64).min(u32::MAX as u64) as u32);
|
||||
(height > 0).then_some(UVec2::new(width, height))
|
||||
}
|
||||
}
|
||||
|
||||
impl WgpuExecutor {
|
||||
/// The image's pixels as it's drawn, with its effects and fill carried out at its own pixel grid, grown by whole pixels to hold what they paint past its edges.
|
||||
/// The opacity and blend mode stay for whatever draws the result.
|
||||
pub async fn read_back(&self, item: Item<Raster<CPU>>) -> anyhow::Result<Item<Pixels>> {
|
||||
self.read_back_within(item, ReadbackLimits::of(self)).await
|
||||
}
|
||||
|
||||
/// Like [`Self::read_back`], within the GPU `limits`.
|
||||
async fn read_back_within(&self, item: Item<Raster<CPU>>, limits: ReadbackLimits) -> anyhow::Result<Item<Pixels>> {
|
||||
let effects: Effects = item.attribute_cloned_or_default(ATTR_EFFECTS);
|
||||
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.);
|
||||
let size = UVec2::new(item.element().width, item.element().height);
|
||||
|
||||
// Nothing to carry out, or nothing to carry it out on
|
||||
if (effects.change_nothing() && fill >= 1.) || size.cmpeq(UVec2::ZERO).any() || !transform.matrix2.determinant().is_normal() || !transform.is_finite() {
|
||||
let raster = item.element().clone();
|
||||
return Ok(carried_out(item, raster));
|
||||
}
|
||||
|
||||
if let Some(adjusted) = adjusted_without_render(&item, &effects, fill) {
|
||||
return Ok(carried_out(item, adjusted));
|
||||
}
|
||||
|
||||
let reach = effects_reach(&effects, size.as_dvec2());
|
||||
if !reach.is_finite() {
|
||||
anyhow::bail!("The effects on a {} by {} image reach too far to render", size.x, size.y);
|
||||
}
|
||||
let margin = capped_margin(reach, size.as_dvec2());
|
||||
let raster = self.render_at_pixel_grid(&item, &effects, transform, margin, reach, limits).await?;
|
||||
|
||||
let unit_margin = margin / size.as_dvec2();
|
||||
let mut item = carried_out(item, raster);
|
||||
item.set_attribute(
|
||||
ATTR_TRANSFORM,
|
||||
transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin),
|
||||
);
|
||||
Ok(item)
|
||||
}
|
||||
|
||||
/// Renders the raster `item` placed by `transform` with its `effects`, one pixel of the render per pixel of its image, grown by `margin` pixels along each axis.
|
||||
/// A render larger than the GPU's `limits` allow is drawn in tiles. When the whole image is too large to upload, each is drawn from a crop holding the pixels the effects `reach` past it.
|
||||
async fn render_at_pixel_grid(&self, item: &Item<Raster<CPU>>, effects: &Effects, transform: DAffine2, margin: DVec2, reach: DVec2, limits: ReadbackLimits) -> anyhow::Result<Raster<CPU>> {
|
||||
let image = item.element();
|
||||
let size = UVec2::new(image.width, image.height);
|
||||
let grown_size = size + 2 * margin.as_uvec2();
|
||||
let document_to_pixels = DAffine2::from_translation(margin) * DAffine2::from_scale(size.as_dvec2()) * transform.inverse();
|
||||
|
||||
// The content on its own, without the opacity and blend mode that act on its effects' result as a whole
|
||||
let mut content = item.clone();
|
||||
content.remove_attribute::<f64>(ATTR_OPACITY);
|
||||
content.remove_attribute::<BlendMode>(ATTR_BLEND_MODE);
|
||||
|
||||
// Each tile draws a crop of an image too large to upload whole, holding the pixels its effects read, unless they depend on the whole image's extent
|
||||
let too_large_to_upload = size.cmpgt(UVec2::splat(limits.texture_size)).any();
|
||||
let crops = too_large_to_upload && !effects.any_takes_frame() && !effects.reach_depends_on_size();
|
||||
if too_large_to_upload && !crops {
|
||||
log::warn!(
|
||||
"A {} by {} image is read back at a lower resolution, since it's too large for the GPU and its effects depend on its whole extent",
|
||||
size.x,
|
||||
size.y
|
||||
);
|
||||
}
|
||||
// A crop holds what the effects reach on both sides of its tile, which has to leave a texture room for at least a pixel, checked before the reach becomes an integer
|
||||
let max_tile_size = match crops {
|
||||
true => {
|
||||
let room = DVec2::splat(limits.texture_size as f64) - 2. * reach;
|
||||
if !room.cmpge(DVec2::ONE).all() {
|
||||
anyhow::bail!("The effects on a {} by {} image reach too far past each pixel to render it in tiles the GPU can hold", size.x, size.y);
|
||||
}
|
||||
room.floor().as_uvec2()
|
||||
}
|
||||
false => grown_size,
|
||||
};
|
||||
let (margin, reach) = (margin.as_uvec2(), reach.as_uvec2());
|
||||
let Some(tile_size) = limits.tile_size(max_tile_size) else {
|
||||
anyhow::bail!("The GPU's textures and buffers can't hold a tile of a {} by {} image's render with its effects", size.x, size.y);
|
||||
};
|
||||
|
||||
// The raster's render carries out leading adjustments changing alpha on its image's own pixels, which a crop's group can't, so they're carried out first
|
||||
if crops {
|
||||
let leading_adjustments = leading_raster_adjustments(&content);
|
||||
if leading_adjustments.iter().any(|adjustment| !preserves_alpha(adjustment)) {
|
||||
let adjusted = adjusted_raster(content.element(), &leading_adjustments);
|
||||
let (_, attributes) = content.into_parts();
|
||||
content = Item::from_parts(adjusted, attributes);
|
||||
content.set_attribute(ATTR_EFFECTS, effects.after(leading_adjustments.len()));
|
||||
}
|
||||
}
|
||||
|
||||
let whole = List::new_from_item(content.clone());
|
||||
if !crops && grown_size.cmple(tile_size).all() {
|
||||
return self.render_tile(&whole, document_to_pixels, grown_size).await;
|
||||
}
|
||||
|
||||
let mut pixels = Image::try_new(grown_size.x, grown_size.y, Color::TRANSPARENT)?;
|
||||
for tile_y in (0..grown_size.y).step_by(tile_size.y as usize) {
|
||||
for tile_x in (0..grown_size.x).step_by(tile_size.x as usize) {
|
||||
let origin = UVec2::new(tile_x, tile_y);
|
||||
let size_in_tile = (grown_size - origin).min(tile_size);
|
||||
let tile_to_pixels = DAffine2::from_translation(-origin.as_dvec2()) * document_to_pixels;
|
||||
|
||||
let tile = match crops {
|
||||
// The tile spans the image's pixels from `origin - margin`, and its effects read up to their reach past it
|
||||
true => {
|
||||
let start = origin.saturating_sub(margin + reach);
|
||||
let end = (origin + size_in_tile + reach).saturating_sub(margin).min(size);
|
||||
self.render_tile(&cropped(&content, start, end), tile_to_pixels, size_in_tile).await?
|
||||
}
|
||||
false => self.render_tile(&whole, tile_to_pixels, size_in_tile).await?,
|
||||
};
|
||||
|
||||
for row in 0..size_in_tile.y as usize {
|
||||
let start = (origin.y as usize + row) * grown_size.x as usize + origin.x as usize;
|
||||
let tile_row = &tile.data[row * size_in_tile.x as usize..(row + 1) * size_in_tile.x as usize];
|
||||
pixels.data[start..start + size_in_tile.x as usize].copy_from_slice(tile_row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Raster::new_cpu(pixels))
|
||||
}
|
||||
|
||||
/// Renders the `content` into an image of `size` pixels, which `document_to_pixels` places the document in, and reads it back.
|
||||
async fn render_tile(&self, content: &(impl Render + Sync), document_to_pixels: DAffine2, size: UVec2) -> anyhow::Result<Raster<CPU>> {
|
||||
let render_params = RenderParams {
|
||||
render_output_type: RenderOutputType::Vello,
|
||||
footprint: Footprint {
|
||||
transform: document_to_pixels,
|
||||
resolution: size,
|
||||
..Default::default()
|
||||
},
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
};
|
||||
let texture = self.try_render_vello(size, document_to_pixels, &mut |scene| content.render_to_vello(scene, DAffine2::IDENTITY, &render_params))?;
|
||||
|
||||
self.try_download(Raster::new_gpu(texture)).await
|
||||
}
|
||||
}
|
||||
|
||||
/// The `item` with its image replaced by the `raster` its effects and fill are carried out in, without the attributes holding them.
|
||||
fn carried_out(item: Item<Raster<CPU>>, raster: Raster<CPU>) -> Item<Pixels> {
|
||||
let (_, attributes) = item.into_parts();
|
||||
let mut item = Item::from_parts(Pixels::new(raster), attributes);
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
|
||||
item
|
||||
}
|
||||
|
||||
/// The image with its `effects` and `fill` carried out on the CPU if the effects are all adjustments its render carries out on its own pixels, or `None` if any needs a render.
|
||||
/// The CPU keeps the adjustments' full precision, including values past 0 to 1 and colors beneath zero alpha, which an 8-bit download would lose.
|
||||
fn adjusted_without_render(item: &Item<Raster<CPU>>, effects: &Effects, fill: f64) -> Option<Raster<CPU>> {
|
||||
let adjustments = leading_raster_adjustments(item);
|
||||
if adjustments.len() < effects.operations().count() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Under a partial fill, the leading adjustments all keep alpha, so fading after them matches fading before
|
||||
let mut adjusted = adjusted_raster(item.element(), &adjustments);
|
||||
if fill < 1. {
|
||||
adjusted.data_mut().data.iter_mut().for_each(|color| *color = color.with_alpha(color.a() * fill as f32));
|
||||
}
|
||||
Some(adjusted)
|
||||
}
|
||||
|
||||
/// The raster `content` drawn from only its image's pixels from `start` up to `end`, at their own resolution where they lie in the whole image.
|
||||
/// The crop sits within a group taking the content's placement and effects, so the effects measure and place what they draw as for the whole image.
|
||||
fn cropped(content: &Item<Raster<CPU>>, start: UVec2, end: UVec2) -> List<Graphic> {
|
||||
let image = content.element();
|
||||
let (size, crop_size) = (UVec2::new(image.width, image.height), end.saturating_sub(start));
|
||||
if crop_size.cmpeq(UVec2::ZERO).any() {
|
||||
return List::new();
|
||||
}
|
||||
|
||||
let data = (start.y..end.y)
|
||||
.flat_map(|y| {
|
||||
let row = (y * size.x) as usize;
|
||||
image.data[row + start.x as usize..row + end.x as usize].iter().copied()
|
||||
})
|
||||
.collect();
|
||||
let crop = Image {
|
||||
width: crop_size.x,
|
||||
height: crop_size.y,
|
||||
data,
|
||||
};
|
||||
let placement = DAffine2::from_translation(start.as_dvec2() / size.as_dvec2()) * DAffine2::from_scale(crop_size.as_dvec2() / size.as_dvec2());
|
||||
let crop = Item::new_from_element(Raster::new_cpu(crop)).with_attribute(ATTR_TRANSFORM, placement);
|
||||
|
||||
let (_, attributes) = content.clone().into_parts();
|
||||
List::new_from_item(Item::from_parts(Graphic::RasterCPU(Box::new(crop)), attributes))
|
||||
}
|
||||
|
||||
/// How far, in whole pixels along each axis of an image of `size` pixels, its `effects` paint and read past each pixel and its edges.
|
||||
fn effects_reach(effects: &Effects, size: DVec2) -> DVec2 {
|
||||
// The content's unit square spans the image's pixels
|
||||
let content_to_pixels = DAffine2::from_scale(size);
|
||||
let reach = (effects.reach_around(content_to_pixels, [DVec2::ZERO, size], 0.) + effects.read_beyond_painted(content_to_pixels)).ceil();
|
||||
|
||||
// A feather fades the content toward its edges, finding them against the pixels past them
|
||||
match effects.operations().any(|operation| matches!(operation, EffectOperation::Feather { distance } if distance > 0.)) {
|
||||
true => reach.max(DVec2::ONE),
|
||||
false => reach,
|
||||
}
|
||||
}
|
||||
|
||||
/// The margin an image of `size` pixels grows by to hold its effects' `reach`, cut short evenly past [`MAX_PIXELS_WITH_MARGIN`].
|
||||
fn capped_margin(reach: DVec2, size: DVec2) -> DVec2 {
|
||||
if (size + 2. * reach).element_product() <= MAX_PIXELS_WITH_MARGIN {
|
||||
return reach;
|
||||
}
|
||||
|
||||
let margin = (reach * margin_fraction_that_fits(size, reach)).floor();
|
||||
if margin.max_element() < reach.max_element() {
|
||||
log::warn!(
|
||||
"The effects on a {} by {} image end at a hard edge {} pixels past it, short of the {} they reach, since the image can't grow past {MAX_PIXELS_WITH_MARGIN} pixels",
|
||||
size.x,
|
||||
size.y,
|
||||
margin.max_element(),
|
||||
reach.max_element()
|
||||
);
|
||||
}
|
||||
margin
|
||||
}
|
||||
|
||||
/// The fraction of `margin` that grows an image of `size` to [`MAX_PIXELS_WITH_MARGIN`], or 0 if the image alone already reaches it.
|
||||
fn margin_fraction_that_fits(size: DVec2, margin: DVec2) -> f64 {
|
||||
// The positive root of (width + 2 × fraction × margin width) × (height + 2 × fraction × margin height) = the limit
|
||||
let quadratic = 4. * margin.x * margin.y;
|
||||
let linear = 2. * (size.x * margin.y + size.y * margin.x);
|
||||
let constant = size.element_product() - MAX_PIXELS_WITH_MARGIN;
|
||||
if constant >= 0. || linear <= 0. {
|
||||
return 0.;
|
||||
}
|
||||
|
||||
let fraction = match quadratic > 0. {
|
||||
true => (-linear + (linear * linear - 4. * quadratic * constant).sqrt()) / (2. * quadratic),
|
||||
false => -constant / linear,
|
||||
};
|
||||
fraction.clamp(0., 1.)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::ATTR_APPEARANCE;
|
||||
use futures::executor::block_on;
|
||||
use graphic_types::vector_types::vector::style::StrokeAlign;
|
||||
use graphic_types::{Appearance, Coverage, Effect, Graphic, MaskMode, Vector, stamp_effect};
|
||||
use vello_gpu::kurbo::{Rect, Shape};
|
||||
|
||||
/// The executor these tests share, or `None` without a GPU.
|
||||
fn executor() -> Option<&'static WgpuExecutor> {
|
||||
static EXECUTOR: std::sync::OnceLock<Option<WgpuExecutor>> = std::sync::OnceLock::new();
|
||||
EXECUTOR.get_or_init(|| block_on(crate::WgpuContext::for_tests()).and_then(WgpuExecutor::with_context)).as_ref()
|
||||
}
|
||||
|
||||
/// The size in the document of the pixels of an image scaled unevenly, 1 unit wide and 4 tall.
|
||||
const TALL_PIXEL: DVec2 = DVec2::new(1., 4.);
|
||||
|
||||
/// An image of 20 by 20 pixels, each `pixel_size` in the document, colored by `color` at each pixel's column and row, with its corner at (100, 50).
|
||||
fn image_of_pixels(pixel_size: DVec2, color: impl Fn(u32, u32) -> Color, effects: &[EffectOperation]) -> Item<Raster<CPU>> {
|
||||
let data = (0..20 * 20).map(|index| color(index % 20, index / 20)).collect();
|
||||
let transform = DAffine2::from_translation(DVec2::new(100., 50.)) * DAffine2::from_scale(20. * pixel_size);
|
||||
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: 20, height: 20, data })).with_attribute(ATTR_TRANSFORM, transform);
|
||||
for effect in effects {
|
||||
stamp_effect(&mut item, Effect::new(effect));
|
||||
}
|
||||
item
|
||||
}
|
||||
|
||||
/// The read-back image's color at a `point` in the document, transparent past its edges.
|
||||
fn color_at(image: &Item<Pixels>, point: DVec2) -> Color {
|
||||
let raster = image.element();
|
||||
let transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let pixel = (transform.inverse().transform_point2(point) * DVec2::new(raster.width as f64, raster.height as f64)).floor();
|
||||
|
||||
let inside = pixel.cmpge(DVec2::ZERO).all() && pixel.x < raster.width as f64 && pixel.y < raster.height as f64;
|
||||
if !inside {
|
||||
return Color::TRANSPARENT;
|
||||
}
|
||||
raster.data[pixel.y as usize * raster.width as usize + pixel.x as usize]
|
||||
}
|
||||
|
||||
fn is_black(color: Color) -> bool {
|
||||
color.a() > 0.98 && color.r().max(color.g()).max(color.b()) < 0.02
|
||||
}
|
||||
|
||||
fn is_white(color: Color) -> bool {
|
||||
color.a() > 0.98 && color.r().min(color.g()).min(color.b()) > 0.98
|
||||
}
|
||||
|
||||
fn is_clear(color: Color) -> bool {
|
||||
color.a() < 0.02
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_without_effects_comes_back_as_it_is() {
|
||||
let Some(executor) = executor() else { return };
|
||||
|
||||
let image = image_of_pixels(TALL_PIXEL, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 0.25), &[]);
|
||||
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
||||
|
||||
assert_eq!(**read_back.element(), *image.element().data());
|
||||
assert_eq!(
|
||||
read_back.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM),
|
||||
image.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM)
|
||||
);
|
||||
}
|
||||
|
||||
/// A fill fades the pixels read back the same whether no effects or an empty list of them is stamped, and goes with the effects while the other attributes stay.
|
||||
#[test]
|
||||
fn a_fill_fades_the_pixels_with_or_without_effects() {
|
||||
let Some(executor) = executor() else { return };
|
||||
|
||||
let mut without_effects = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &[]);
|
||||
without_effects.set_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||
without_effects.set_attribute(ATTR_OPACITY, 0.25);
|
||||
without_effects.set_attribute(ATTR_BLEND_MODE, BlendMode::Multiply);
|
||||
without_effects.set_attribute("unrelated", 7.);
|
||||
let mut with_no_effects = without_effects.clone();
|
||||
with_no_effects.set_attribute(ATTR_EFFECTS, Effects::default());
|
||||
|
||||
for image in [without_effects, with_no_effects] {
|
||||
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
||||
|
||||
let faded: Vec<_> = image.element().data.iter().map(|color| color.with_alpha(0.5)).collect();
|
||||
assert_eq!(read_back.element().data, faded);
|
||||
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
||||
|
||||
assert_eq!(read_back.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 0.25);
|
||||
assert_eq!(read_back.attribute_cloned_or_default::<BlendMode>(ATTR_BLEND_MODE), BlendMode::Multiply);
|
||||
assert_eq!(read_back.attribute_cloned_or::<f64>("unrelated", 0.), 7.);
|
||||
assert_eq!(
|
||||
read_back.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM),
|
||||
image.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Levels adjustment bending each color channel its own way, and alpha by `alpha_midtones`.
|
||||
fn uneven_levels(alpha_midtones: f64) -> graphic_types::Adjustment {
|
||||
use graphic_types::adjustment::{LevelsRecord, LevelsSettings};
|
||||
|
||||
let record = |midtones, output_maximums| LevelsRecord {
|
||||
shadows: 0.,
|
||||
midtones,
|
||||
highlights: 100.,
|
||||
output_minimums: 0.,
|
||||
output_maximums,
|
||||
};
|
||||
graphic_types::Adjustment::Levels(Box::new(LevelsSettings {
|
||||
composite: record(1.4, 100.),
|
||||
red: record(0.7, 90.),
|
||||
green: record(1., 100.),
|
||||
blue: record(1.2, 100.),
|
||||
alpha: record(alpha_midtones, 100.),
|
||||
}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustments_carried_out_on_the_cpu_match_their_render() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// Opaque, so the render's straight alpha keeps every color
|
||||
let operations = [uneven_levels(1.), graphic_types::Adjustment::Invert].map(EffectOperation::Adjustment);
|
||||
let image = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &operations);
|
||||
let (effects, transform) = (image.attribute::<Effects>(ATTR_EFFECTS).unwrap().clone(), image.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||
|
||||
let on_the_cpu = adjusted_without_render(&image, &effects, 1.).expect("adjustments alone need no render");
|
||||
let rendered = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, DVec2::ZERO, limits)).unwrap();
|
||||
|
||||
// The render carries out leading adjustments on the image's own pixels too, then draws them into an 8-bit texture
|
||||
assert_alike(&on_the_cpu, &rendered, ADJUSTMENT_TOLERANCE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustments_alone_are_carried_out_on_the_cpu() {
|
||||
use graphic_types::Adjustment;
|
||||
|
||||
let Some(executor) = executor() else { return };
|
||||
|
||||
let adjustments = [uneven_levels(2.2), Adjustment::Invert];
|
||||
let operations: Vec<_> = adjustments.iter().cloned().map(EffectOperation::Adjustment).collect();
|
||||
|
||||
// A Levels stack bending alpha, with fine steps 8 bits can't hold
|
||||
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 1000., y as f32 / 20., 0.5, (x + y) as f32 / 40.);
|
||||
let image = image_of_pixels(DVec2::ONE, color, &operations);
|
||||
let expected = adjusted_raster(image.element(), &adjustments);
|
||||
let read_back = block_on(executor.read_back(image)).unwrap();
|
||||
assert_eq!(**read_back.element(), *expected.data());
|
||||
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||
|
||||
// Inverting keeps alpha, so a partial fill fades the inverted colors, which stay beneath zero alpha
|
||||
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 20., 0.25, 1., if y < 10 { 0. } else { 0.8 });
|
||||
let mut image = image_of_pixels(DVec2::ONE, color, &[EffectOperation::Adjustment(Adjustment::Invert)]);
|
||||
image.set_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||
let inverted = adjusted_raster(image.element(), &[Adjustment::Invert]);
|
||||
let read_back = block_on(executor.read_back(image)).unwrap();
|
||||
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
||||
for (index, (color, inverted)) in read_back.element().data.iter().zip(&inverted.data().data).enumerate() {
|
||||
assert_eq!(*color, inverted.with_alpha(inverted.a() * 0.5), "pixel {index}");
|
||||
assert!(color.r() + color.g() + color.b() > 0., "pixel {index} lost its color");
|
||||
}
|
||||
|
||||
// Effects past adjustments need a render
|
||||
let outlined = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[outline(2.)]);
|
||||
let effects = outlined.attribute::<Effects>(ATTR_EFFECTS).unwrap();
|
||||
assert!(adjusted_without_render(&outlined, effects, 1.).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_margin_holds_what_a_median_reads_past_the_image() {
|
||||
// A median reads its whole radius and the pixel past it, across the image's pixels of one unit each
|
||||
let image = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[EffectOperation::Median { radius: 2.5 }]);
|
||||
let effects = image.attribute::<Effects>(ATTR_EFFECTS).unwrap();
|
||||
assert_eq!(effects_reach(effects, DVec2::splat(20.)), DVec2::splat(3.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_measure_lengths_in_the_document_across_unevenly_scaled_pixels() {
|
||||
let Some(executor) = executor() else { return };
|
||||
|
||||
// An outline 8 units wide spans 8 of the image's pixels across, but only 2 of them down
|
||||
let outline = EffectOperation::Outline {
|
||||
paint: Color::BLACK.into(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
weight: 8.,
|
||||
align: StrokeAlign::Outside,
|
||||
contour_gradient: false,
|
||||
};
|
||||
let read_back = block_on(executor.read_back(image_of_pixels(TALL_PIXEL, |_, _| Color::WHITE, &[outline]))).unwrap();
|
||||
|
||||
// The content spans from (100, 50) to (120, 130)
|
||||
assert!(is_white(color_at(&read_back, DVec2::new(110., 90.))), "the content");
|
||||
assert!(is_black(color_at(&read_back, DVec2::new(94.5, 90.))), "within the outline, 5.5 units left of the content");
|
||||
assert!(is_clear(color_at(&read_back, DVec2::new(89.5, 90.))), "past the outline, 10.5 units left of the content");
|
||||
assert!(is_black(color_at(&read_back, DVec2::new(110., 44.))), "within the outline, 6 units above the content");
|
||||
assert!(is_clear(color_at(&read_back, DVec2::new(110., 40.))), "past the outline, 10 units above the content");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_masks_shape_the_pixels_read_back() {
|
||||
let Some(executor) = executor() else { return };
|
||||
|
||||
// A mask lies in the content's own space, where the left half of its unit square covers the image's left half
|
||||
let mut left_half = Vector::item_from_bezpath(&Rect::new(0., 0., 0.5, 1.).to_path(0.1));
|
||||
left_half.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE))));
|
||||
let mask = EffectOperation::Mask {
|
||||
mask: Graphic::Vector(Box::new(left_half)),
|
||||
mode: MaskMode::Alpha,
|
||||
density: 100.,
|
||||
feather: 0.,
|
||||
invert: false,
|
||||
};
|
||||
let read_back = block_on(executor.read_back(image_of_pixels(TALL_PIXEL, |_, _| Color::WHITE, &[mask]))).unwrap();
|
||||
|
||||
assert!(is_white(color_at(&read_back, DVec2::new(105.5, 90.))), "the left half, which the mask shows");
|
||||
assert!(is_clear(color_at(&read_back, DVec2::new(114.5, 90.))), "the right half, which the mask hides");
|
||||
}
|
||||
|
||||
/// An outline of `weight` outside the content, in black.
|
||||
fn outline(weight: f64) -> EffectOperation {
|
||||
EffectOperation::Outline {
|
||||
paint: Color::BLACK.into(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
weight,
|
||||
align: StrokeAlign::Outside,
|
||||
contour_gradient: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The limits of the shared GPU, and its executor, or `None` without a GPU.
|
||||
fn executor_and_limits() -> Option<(&'static WgpuExecutor, ReadbackLimits)> {
|
||||
let executor = executor()?;
|
||||
Some((executor, ReadbackLimits::of(executor)))
|
||||
}
|
||||
|
||||
/// How many 8-bit levels the CPU's adjustments and the render of them may part by, which is the render's rounding to its 8-bit texture.
|
||||
const ADJUSTMENT_TOLERANCE: u8 = 1;
|
||||
|
||||
/// Asserts that two images have the same size and 8-bit pixels within `tolerance` levels of each other.
|
||||
fn assert_alike(actual: &Image<Color>, expected: &Image<Color>, tolerance: u8) {
|
||||
assert_eq!((actual.width, actual.height), (expected.width, expected.height));
|
||||
for (index, (actual, expected)) in actual.data.iter().zip(&expected.data).enumerate() {
|
||||
let (SRGBA8 { red, green, blue, alpha }, wanted) = (SRGBA8::from(*actual), SRGBA8::from(*expected));
|
||||
let differences = [red.abs_diff(wanted.red), green.abs_diff(wanted.green), blue.abs_diff(wanted.blue), alpha.abs_diff(wanted.alpha)];
|
||||
assert!(
|
||||
differences.iter().all(|&difference| difference <= tolerance),
|
||||
"pixel {index} is {actual:?} but {expected:?} in the other"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiles_small_enough_for_the_download_buffer_match_one_render() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// Square pixels of the document's size keep the effects' working pixels on the render's, so neither render resamples them.
|
||||
// A 2048 byte buffer holds 8 rows of up to 64 pixels, each padded to 256 bytes, so this render is drawn in tiles 8 pixels tall.
|
||||
let image = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &[outline(2.)]);
|
||||
let small_buffer = ReadbackLimits { buffer_size: 2048, ..limits };
|
||||
assert_eq!(small_buffer.tile_size(UVec2::splat(100)), Some(UVec2::new(100, 2048 / 512)));
|
||||
|
||||
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
||||
let tiled = block_on(executor.read_back_within(image, small_buffer)).unwrap();
|
||||
assert_alike(tiled.element(), whole.element(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_too_large_to_upload_whole_keeps_its_own_pixels_in_crops() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// Alternating black and white columns, inverted and outlined, which a downscaled upload would average to gray
|
||||
let columns = |x: u32, _| if x.is_multiple_of(2) { Color::BLACK } else { Color::WHITE };
|
||||
let image = image_of_pixels(DVec2::ONE, columns, &[EffectOperation::Adjustment(graphic_types::Adjustment::Invert), outline(2.)]);
|
||||
let small_textures = ReadbackLimits { texture_size: 16, ..limits };
|
||||
|
||||
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
||||
let cropped = block_on(executor.read_back_within(image, small_textures)).unwrap();
|
||||
assert_alike(cropped.element(), whole.element(), 1);
|
||||
|
||||
for x in 0..20 {
|
||||
let color = color_at(&cropped, DVec2::new(100.5 + x as f64, 60.5));
|
||||
let inverted = if x % 2 == 0 { is_white(color) } else { is_black(color) };
|
||||
assert!(inverted, "column {x} is {color:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits_too_small_for_any_tile_fail_without_panicking() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
let image = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[outline(2.)]);
|
||||
let tiny_buffer = ReadbackLimits { buffer_size: 100, ..limits };
|
||||
assert!(block_on(executor.read_back_within(image, tiny_buffer)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reach_too_far_for_any_crop_fails_without_overflowing() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// A box blur reaching past 2^31 pixels, on an image too wide for the texture limit, at one document unit per pixel
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 2_147_483_647.,
|
||||
box_blur: true,
|
||||
gamma: false,
|
||||
};
|
||||
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(16_384, 64, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(16_384., 64.)));
|
||||
stamp_effect(&mut image, Effect::new(&blur));
|
||||
let small_textures = ReadbackLimits { texture_size: 8192, ..limits };
|
||||
|
||||
assert!(block_on(executor.read_back_within(image, small_textures)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crops_carry_out_leading_adjustments_on_transparent_pixels_as_the_whole_image_does() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// Make Opaque raises the alpha of fully transparent pixels, which only the image's own pixels can carry, and the outline needs a render
|
||||
let make_opaque = EffectOperation::Adjustment(graphic_types::Adjustment::MakeOpaque { strength: 100. });
|
||||
let image = image_of_pixels(DVec2::ONE, |_, _| Color::from_rgbaf32_unchecked(1., 0., 0., 0.), &[make_opaque, outline(2.)]);
|
||||
let small_textures = ReadbackLimits { texture_size: 16, ..limits };
|
||||
|
||||
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
||||
let cropped = block_on(executor.read_back_within(image, small_textures)).unwrap();
|
||||
assert_alike(cropped.element(), whole.element(), 1);
|
||||
let pixels = (0..20).flat_map(|y| (0..20).map(move |x| DVec2::new(100.5 + x as f64, 50.5 + y as f64)));
|
||||
assert!(pixels.map(|point| color_at(&cropped, point)).all(|color| color.a() > 0.99), "the transparent pixels became opaque");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crops_hold_the_pixels_effects_reach_past_a_margin_cut_short() {
|
||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
||||
|
||||
// A margin cut to nothing, as for an image too large to grow, still leaves the blur its neighbors across the tiles.
|
||||
// The tiles are wide enough next to the blur's reach that its effects group keeps their full resolution.
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 1.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(64, 64, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.)));
|
||||
stamp_effect(&mut image, Effect::new(&blur));
|
||||
let (effects, transform) = (image.attribute::<Effects>(ATTR_EFFECTS).unwrap().clone(), image.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||
let reach = effects_reach(&effects, DVec2::splat(64.));
|
||||
assert!(reach.min_element() > 0.);
|
||||
let small_textures = ReadbackLimits { texture_size: 60, ..limits };
|
||||
|
||||
let whole = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, reach, limits)).unwrap();
|
||||
let cropped = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, reach, small_textures)).unwrap();
|
||||
assert_alike(&cropped, &whole, 1);
|
||||
}
|
||||
}
|
||||
@@ -22,23 +22,35 @@ struct RasterGpuToRasterCpuConverter {
|
||||
padded_bytes_per_row: u32,
|
||||
_source: raster_types::Texture,
|
||||
}
|
||||
/// The bytes in each row of a download buffer for an image `width` pixels wide, padded to the alignment copies need.
|
||||
pub(crate) fn download_row_bytes(width: u32) -> u32 {
|
||||
let bytes_per_pixel = 4; // RGBA8
|
||||
(width * bytes_per_pixel).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT
|
||||
}
|
||||
|
||||
/// The buffer a texture of `width` by `height` pixels downloads into.
|
||||
fn download_buffer(executor: &WgpuExecutor, width: u32, height: u32) -> Buffer {
|
||||
executor.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("texture_download_buffer"),
|
||||
size: download_row_bytes(width) as u64 * height as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
|
||||
impl RasterGpuToRasterCpuConverter {
|
||||
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
|
||||
let buffer = download_buffer(executor, data_gpu.data().width(), data_gpu.data().height());
|
||||
Self::with_buffer(encoder, data_gpu, buffer)
|
||||
}
|
||||
|
||||
/// Copies the texture into the `buffer` made for its size, once the `encoder` is submitted.
|
||||
fn with_buffer(encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>, buffer: Buffer) -> Self {
|
||||
let texture = data_gpu.data();
|
||||
let width = texture.width();
|
||||
let height = texture.height();
|
||||
let bytes_per_pixel = 4; // RGBA8
|
||||
let unpadded_bytes_per_row = width * bytes_per_pixel;
|
||||
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
||||
let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
|
||||
let buffer_size = padded_bytes_per_row as u64 * height as u64;
|
||||
|
||||
let buffer = executor.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("texture_download_buffer"),
|
||||
size: buffer_size,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let unpadded_bytes_per_row = width * 4;
|
||||
let padded_bytes_per_row = download_row_bytes(width);
|
||||
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
@@ -73,7 +85,7 @@ impl RasterGpuToRasterCpuConverter {
|
||||
}
|
||||
}
|
||||
|
||||
async fn convert(self, device: &wgpu::Device) -> Result<Raster<CPU>, wgpu::BufferAsyncError> {
|
||||
async fn convert(self, device: &wgpu::Device) -> anyhow::Result<Raster<CPU>> {
|
||||
let buffer_slice = self.buffer.slice(..);
|
||||
let (sender, receiver) = futures::channel::oneshot::channel();
|
||||
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
||||
@@ -104,9 +116,12 @@ impl RasterGpuToRasterCpuConverter {
|
||||
}
|
||||
};
|
||||
|
||||
map_result.expect("Failed to receive map result")?;
|
||||
let Ok(map_result) = map_result else {
|
||||
anyhow::bail!("The download of a {} by {} image was canceled before the GPU mapped its buffer", self.width, self.height);
|
||||
};
|
||||
map_result?;
|
||||
|
||||
let view = buffer_slice.get_mapped_range().expect("Failed to get mapped range");
|
||||
let view = buffer_slice.get_mapped_range()?;
|
||||
|
||||
let row_stride = self.padded_bytes_per_row as usize;
|
||||
let row_bytes = self.unpadded_bytes_per_row as usize;
|
||||
@@ -230,3 +245,33 @@ impl ConvertAsync<Raster<CPU>, WgpuExecutor> for Raster<GPU> {
|
||||
converter.convert(device).await.expect("Failed to download texture data")
|
||||
}
|
||||
}
|
||||
|
||||
impl WgpuExecutor {
|
||||
/// Downloads the GPU raster's pixels, failing rather than panicking when the GPU can't make or map the buffer they're copied into.
|
||||
pub async fn try_download(&self, raster: Raster<GPU>) -> anyhow::Result<Raster<CPU>> {
|
||||
let device = &self.context().device;
|
||||
let (width, height) = (raster.data().width(), raster.data().height());
|
||||
let buffer_size = download_row_bytes(width) as u64 * height as u64;
|
||||
let limit = device.limits().max_buffer_size;
|
||||
if buffer_size > limit {
|
||||
anyhow::bail!("Downloading a {width} by {height} image takes a {buffer_size} byte buffer, past the GPU's limit of {limit} bytes");
|
||||
}
|
||||
|
||||
// Popped in the reverse order they're pushed, before awaiting either, since the scopes can't be held across an await
|
||||
let out_of_memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let buffer = download_buffer(self, width, height);
|
||||
let (validation, out_of_memory) = (validation.pop(), out_of_memory.pop());
|
||||
if let Some(error) = validation.await.or(out_of_memory.await) {
|
||||
anyhow::bail!("The GPU couldn't make the buffer to download a {width} by {height} image: {error}");
|
||||
}
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("fallible_texture_download_encoder"),
|
||||
});
|
||||
let converter = RasterGpuToRasterCpuConverter::with_buffer(&mut encoder, raster, buffer);
|
||||
self.context().queue.submit([encoder.finish()]);
|
||||
|
||||
converter.convert(device).await
|
||||
}
|
||||
}
|
||||
@@ -109,6 +109,7 @@ fn step_function(kind: StepKind) -> (&'static str, Option<[Encoding; 2]>) {
|
||||
StepKind::ColorLookup => ("color_lookup", Some([Gamma, Gamma])),
|
||||
StepKind::ColorOverlay => ("color_overlay", Some([Gamma, Gamma])),
|
||||
StepKind::Solarize => ("solarize", Some([Gamma, Gamma])),
|
||||
StepKind::AlphaToGray => ("alpha_to_gray", Some([Gamma, Gamma])),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -365,6 +365,11 @@ fn solarize(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||
return vec4<f32>(min(color.rgb, 1. - color.rgb), color.a);
|
||||
}
|
||||
|
||||
// The alpha as a gray of the same gamma-encoded level, keeping the alpha
|
||||
fn alpha_to_gray(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||
return vec4<f32>(vec3<f32>(color.a), color.a);
|
||||
}
|
||||
|
||||
// Matches `apply_levels` with the gamma of 1 that every caller here passes, so its power is left out
|
||||
fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, output_minimum: f32, output_maximum: f32) -> f32 {
|
||||
let highlights_minus_shadows = clamp(input_highlights - input_shadows, F32_EPSILON, 1.);
|
||||
@@ -1630,7 +1635,11 @@ fn blend_lighten(c_b: f32, c_s: f32) -> f32 {
|
||||
return max(c_s, c_b);
|
||||
}
|
||||
|
||||
// A black backdrop stays black, and any other turns white under a white source, as the W3C formula orders them
|
||||
fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
|
||||
if abs(c_b) <= BLEND_EDGE_TOLERANCE {
|
||||
return 0.;
|
||||
}
|
||||
if abs(c_s - 1.) <= BLEND_EDGE_TOLERANCE {
|
||||
return 1.;
|
||||
}
|
||||
@@ -1726,7 +1735,8 @@ fn blend_channel(mode: u32, c_b: f32, c_s: f32) -> f32 {
|
||||
return blend_pin_light(c_b, c_s);
|
||||
}
|
||||
case BLEND_HARD_MIX: {
|
||||
return select(1., 0., blend_linear_light(c_b, c_s) < 0.5);
|
||||
// A ramp a 256th wide around where the channels sum to 1, matching `blend_hard_mix`
|
||||
return (c_b - 255. / 256. * (1. - c_s)) * 256.;
|
||||
}
|
||||
case BLEND_DIFFERENCE: {
|
||||
return abs(c_b - c_s);
|
||||
@@ -1751,11 +1761,11 @@ fn blend_channel(mode: u32, c_b: f32, c_s: f32) -> f32 {
|
||||
fn apply_blend_mode(foreground: vec4<f32>, background: vec4<f32>, mode: u32) -> vec4<f32> {
|
||||
switch mode {
|
||||
case BLEND_DARKER_COLOR: {
|
||||
let background_is_darker = (background.r + background.g + background.b) / 3. <= (foreground.r + foreground.g + foreground.b) / 3.;
|
||||
let background_is_darker = luma_rec_601_rounded(background.rgb) <= luma_rec_601_rounded(foreground.rgb);
|
||||
return vec4<f32>(select(foreground.rgb, background.rgb, background_is_darker), foreground.a);
|
||||
}
|
||||
case BLEND_LIGHTER_COLOR: {
|
||||
let background_is_lighter = (background.r + background.g + background.b) / 3. >= (foreground.r + foreground.g + foreground.b) / 3.;
|
||||
let background_is_lighter = luma_rec_601_rounded(background.rgb) >= luma_rec_601_rounded(foreground.rgb);
|
||||
return vec4<f32>(select(foreground.rgb, background.rgb, background_is_lighter), foreground.a);
|
||||
}
|
||||
case BLEND_HUE, BLEND_SATURATION, BLEND_COLOR, BLEND_LUMINOSITY: {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// Blend If's passes, appended to the effect passes: ranges of each channel's levels that a pixel shows within, matching `graphic_types::blend_if`
|
||||
|
||||
// How near a cutoff a channel may lie and still count as reaching it, matching `CUTOFF_TOLERANCE`
|
||||
const BLEND_IF_CUTOFF_TOLERANCE: f32 = 1. / 1024.;
|
||||
|
||||
// Each channel's nearest of 256 levels, with halves rounding up, matching `channel_level`
|
||||
fn blend_if_levels(color: vec3<f32>) -> vec3<u32> {
|
||||
return vec3<u32>(floor(clamp(color, vec3<f32>(0.), vec3<f32>(1.)) * 255. + 0.5));
|
||||
}
|
||||
|
||||
// One side of a range, rising across the span between its falloff and range ends (or falling, if not `rising`), or cutting off sharply where they meet
|
||||
fn blend_if_side(value: f32, falloff: f32, range: f32, rising: bool) -> f32 {
|
||||
let low = min(falloff, range);
|
||||
let high = max(falloff, range);
|
||||
if high - low > BLEND_IF_CUTOFF_TOLERANCE {
|
||||
return clamp(select(high - value, value - low, rising) / (high - low), 0., 1.);
|
||||
}
|
||||
return select(f32(value <= high + BLEND_IF_CUTOFF_TOLERANCE), f32(value >= low - BLEND_IF_CUTOFF_TOLERANCE), rising);
|
||||
}
|
||||
|
||||
// How strongly a range of (falloff start, range start, range end, falloff end) shows a channel's value
|
||||
fn blend_if_range(value: f32, edges: vec4<f32>) -> f32 {
|
||||
return blend_if_side(value, edges.x, edges.y, true) * blend_if_side(value, edges.w, edges.z, false);
|
||||
}
|
||||
|
||||
// How strongly the ranges in the first four taps (gray, red, green, and blue) show a premultiplied pixel, by its straight color
|
||||
fn blend_if_weight(pixel: vec4<f32>) -> f32 {
|
||||
var color = vec3<f32>(0.);
|
||||
if pixel.a > 0. {
|
||||
color = pixel.rgb / pixel.a;
|
||||
}
|
||||
// The gray in whole numbers, rounding halves up, matching `gray_level`
|
||||
let levels = blend_if_levels(color);
|
||||
let channels = vec3<f32>(levels) / 255.;
|
||||
let gray = f32((30u * levels.r + 59u * levels.g + 11u * levels.b + 50u) / 100u) / 255.;
|
||||
|
||||
let gray_weight = blend_if_range(gray, parameters.taps[0]);
|
||||
let red_weight = blend_if_range(channels.r, parameters.taps[1]);
|
||||
let green_weight = blend_if_range(channels.g, parameters.taps[2]);
|
||||
let blue_weight = blend_if_range(channels.b, parameters.taps[3]);
|
||||
return gray_weight * red_weight * green_weight * blue_weight;
|
||||
}
|
||||
|
||||
// How strongly the ranges in the taps show each pixel of the content (`source`), by its own colors
|
||||
@fragment
|
||||
fn blend_if_content_weight(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(blend_if_weight(textureLoad(source, vec2<i32>(position.xy), 0)));
|
||||
}
|
||||
|
||||
// How strongly the ranges in the taps show each pixel by what lies beneath it, sampled from the scene's backdrop (`source`) where it lands as `sample_backdrop` places it.
|
||||
// With `values.z` 1 it multiplies the weight so far in `secondary`, and with `values.w` 1 it eases to full where nothing lies beneath, matching `underlying_weight`.
|
||||
@fragment
|
||||
fn blend_if_underlying_weight(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let point = backdrop_point(position.xy);
|
||||
let backdrop = textureSampleLevel(source, linear_sampler, point / vec2<f32>(textureDimensions(source)), 0.);
|
||||
|
||||
var weight = blend_if_weight(backdrop);
|
||||
if parameters.values.z > 0.5 {
|
||||
weight *= textureLoad(secondary, vec2<i32>(position.xy), 0).r;
|
||||
}
|
||||
if parameters.values.w > 0.5 {
|
||||
weight = 1. - backdrop.a * (1. - weight);
|
||||
}
|
||||
return vec4<f32>(weight);
|
||||
}
|
||||
|
||||
// An image (`source`) faded by the weight in `secondary`
|
||||
@fragment
|
||||
fn blend_if_fade(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
return textureLoad(source, pixel, 0) * textureLoad(secondary, pixel, 0).r;
|
||||
}
|
||||
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user