mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
9
Commits
distort-effects
...
spike
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2e2c7abcd | ||
|
|
f6804d9443 | ||
|
|
5471774764 | ||
|
|
f1ca7e7ab2 | ||
|
|
07ddc86fc2 | ||
|
|
3134753d07 | ||
|
|
cece2e9957 | ||
|
|
620f8d992b | ||
|
|
db2d8625a6 |
No files matched your search
Generated
+13
-3
@@ -588,6 +588,7 @@ dependencies = [
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -2664,6 +2665,7 @@ dependencies = [
|
||||
"math-nodes",
|
||||
"node-macro",
|
||||
"path-bool-nodes",
|
||||
"raster-kernels",
|
||||
"raster-nodes",
|
||||
"rendering",
|
||||
"repeat-nodes",
|
||||
@@ -2695,6 +2697,7 @@ dependencies = [
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -4163,6 +4166,7 @@ dependencies = [
|
||||
"math-parser",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"thiserror 2.0.21",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -6005,12 +6009,14 @@ dependencies = [
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
"vello_gpu",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7988,6 +7994,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"qrcodegen",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
@@ -8048,7 +8055,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -8063,7 +8070,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -8077,7 +8084,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
@@ -8538,8 +8545,11 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-application-io",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
+3
-3
@@ -311,6 +311,6 @@ debug = true
|
||||
[patch.crates-io]
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
@@ -21,7 +21,7 @@ pub(crate) struct RenderState {
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_scene: Option<VelloSceneBuilder>,
|
||||
overlays_scene: Option<VelloSceneBuilder<'static>>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_canvas: VelloCanvas,
|
||||
surface_outdated: bool,
|
||||
@@ -220,7 +220,7 @@ impl RenderState {
|
||||
self.viewport_offset = offset;
|
||||
}
|
||||
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder<'static>) {
|
||||
self.surface_outdated = true;
|
||||
self.overlays_scene = Some(scene);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ pub enum DesktopFrontendMessage {
|
||||
WindowUpdateDirectInput {
|
||||
enabled: bool,
|
||||
},
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder>),
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder<'static>>),
|
||||
PersistenceUpdatePreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod paint_overlay_from_color_overlay;
|
||||
mod renames;
|
||||
@@ -0,0 +1,43 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Node, migration};
|
||||
|
||||
/// 'Color Overlay' became the 'Paint Overlay' effect, which takes its color as a solid paint. A name it stored as its default would misname it.
|
||||
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => "blending_nodes::effects::PaintOverlayNode"@2)]
|
||||
pub fn paint_overlay_from_color_overlay(node: &Node, attributes: &mut Attributes) {
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Color Overlay") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::TimeStamp;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
let contract = SourceContract {
|
||||
display_names: &["Color Overlay"],
|
||||
..SourceContract::new(4, |random, _| literal(random.below(10) as f64))
|
||||
};
|
||||
check_commutation(&PaintOverlayFromColorOverlay, &contract);
|
||||
check_undo(&PaintOverlayFromColorOverlay, &contract);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_old_default_name_is_cleared() {
|
||||
for (name, kept) in [("Color Overlay", None), ("Tint", Some("Tint"))] {
|
||||
let mut fixture = Fixture::new(&PaintOverlayFromColorOverlay);
|
||||
let overlay = fixture.add(decl!("raster_nodes::blending_nodes::ColorOverlayNode"@1), Vec::new());
|
||||
let attributes = fixture.registry.node_instances.get_mut(&overlay).unwrap().attributes_mut();
|
||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let migrated = fixture.migrate(&PaintOverlayFromColorOverlay).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@2)));
|
||||
assert_eq!(migrated.node_instances[&overlay].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Nodes that only moved to a new identifier.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Node migrations, in a module per node crate and a file per step, each registering itself. Scaffold one with
|
||||
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
|
||||
|
||||
mod blending_nodes;
|
||||
mod graphene_core;
|
||||
mod math_nodes;
|
||||
mod raster_nodes;
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Inputs, MigrationError, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration uses.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
GradientForm(GradientForm),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GradientForm {
|
||||
Linear,
|
||||
Radial,
|
||||
}
|
||||
|
||||
const FORM: u32 = 1;
|
||||
|
||||
/// 'Gradient Form' became 'Gradient Curvature', whose start and end curvatures take the presets of the form it set: 0 and 0 for linear, 1 and 0.5 for
|
||||
/// radial. A wired form becomes linear, 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.],
|
||||
};
|
||||
|
||||
inputs.set(FORM, literal(Tagged::Number(start)));
|
||||
inputs.push(literal(Tagged::Number(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::{NodeInput, decl};
|
||||
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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forms_become_their_curvature_presets() {
|
||||
let gradient = literal(Tagged::Number(0.));
|
||||
for (old_form, [start, end]) in [
|
||||
(form(GradientForm::Linear), [0., 0.]),
|
||||
(form(GradientForm::Radial), [1., 0.5]),
|
||||
(NodeInput::Import { index: 0 }, [0., 0.]),
|
||||
] {
|
||||
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(), literal(Tagged::Number(start)), literal(Tagged::Number(end))]);
|
||||
}
|
||||
}
|
||||
|
||||
#[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;
|
||||
@@ -0,0 +1,104 @@
|
||||
use super::pattern_square::{SquareNodes, Tagged, fill_square_with_pattern};
|
||||
use migration_core::{Attributes, Downstream, Inputs, Node, decl, literal, migration};
|
||||
|
||||
/// The pattern fills the plane rather than being cut off at the unit square, so it's read through that square filled with it, and the node gained a
|
||||
/// primary input.
|
||||
#[migration("raster_nodes::std_nodes::MandelbrotNode"@1 => @2)]
|
||||
pub fn mandelbrot_v1(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) {
|
||||
inputs.insert(0, literal(Tagged::None));
|
||||
|
||||
let nodes = SquareNodes {
|
||||
rectangle: decl!("vector_nodes::generator_nodes::RectangleNode"@1),
|
||||
fill: decl!("graphene_core::vector::FillNode"@1),
|
||||
transform: decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
};
|
||||
fill_square_with_pattern(node, downstream, attributes, nodes, 1.);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::{ROOT_NETWORK, TimeStamp};
|
||||
use migration_core::attr::node::ui::{IS_LAYER, POSITION};
|
||||
use migration_core::{NodeInput, Position};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(0, |_, _| literal(Tagged::None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MandelbrotV1, &contract());
|
||||
check_undo(&MandelbrotV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_export_reads_a_unit_square_filled_with_the_pattern() {
|
||||
let mut fixture = Fixture::new(&MandelbrotV1);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@1), Vec::new());
|
||||
fixture.export(NodeInput::Node { id: mandelbrot, index: 0 });
|
||||
let migrated = fixture.migrate(&MandelbrotV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, mandelbrot), [literal(Tagged::None)]);
|
||||
|
||||
let Some(NodeInput::Node { id: placement, .. }) = migrated.networks[&ROOT_NETWORK].exports[0].target else {
|
||||
panic!("the export should read a node")
|
||||
};
|
||||
assert_eq!(fixture.declaration_of(&migrated, placement), Some(decl!("transform_nodes::transform_nodes::TransformNode"@1)));
|
||||
assert_eq!(fixture.inputs(&migrated, placement)[1], literal(Tagged::DVec2([0.5, 0.5])));
|
||||
}
|
||||
|
||||
/// The positions of the pattern, its paint, the rectangle, the fill, and the placement after migrating a pattern at `position`.
|
||||
fn placed_square(position: Position, layer: Option<[i32; 2]>) -> [Option<Position>; 5] {
|
||||
let mut fixture = Fixture::new(&MandelbrotV1);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@1), Vec::new());
|
||||
let place = |fixture: &mut Fixture, node, position: Position| {
|
||||
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
|
||||
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
|
||||
};
|
||||
place(&mut fixture, mandelbrot, position);
|
||||
|
||||
let reader = match layer {
|
||||
Some(layer_position) => {
|
||||
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::None), NodeInput::Node { id: mandelbrot, index: 0 }]);
|
||||
place(&mut fixture, layer, Position::Absolute(layer_position));
|
||||
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
|
||||
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
|
||||
layer
|
||||
}
|
||||
None => fixture.add(decl!("migration_testing::consumer"@1), vec![NodeInput::Node { id: mandelbrot, index: 0 }]),
|
||||
};
|
||||
|
||||
let migrated = fixture.migrate(&MandelbrotV1).unwrap();
|
||||
let reads = |node, slot: usize| match fixture.inputs(&migrated, node)[slot] {
|
||||
NodeInput::Node { id, .. } => id,
|
||||
_ => panic!("slot {slot} of {node:?} should read a node"),
|
||||
};
|
||||
let placement = reads(reader, if layer.is_some() { 1 } else { 0 });
|
||||
let fill = reads(placement, 0);
|
||||
let (rectangle, paint) = (reads(fill, 0), reads(fill, 1));
|
||||
|
||||
[mandelbrot, paint, rectangle, fill, placement].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chained_pattern_gives_its_place_to_the_filled_rectangle() {
|
||||
let [pattern, paint, rectangle, fill, placement] = placed_square(Position::Chain, Some([30, 10]));
|
||||
|
||||
assert_eq!([rectangle, fill, placement], [Some(Position::Chain); 3]);
|
||||
assert_eq!(pattern, Some(Position::Absolute([0, 0])));
|
||||
assert_eq!(paint, Some(Position::Absolute([7, 0])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_pattern_gets_its_square_to_the_right() {
|
||||
let [pattern, paint, rectangle, fill, placement] = placed_square(Position::Absolute([5, 5]), None);
|
||||
|
||||
assert_eq!(pattern, Some(Position::Absolute([5, 5])));
|
||||
assert_eq!(paint, Some(Position::Absolute([12, 5])));
|
||||
assert_eq!(rectangle, Some(Position::Absolute([12, 2])));
|
||||
assert_eq!(fill, Some(Position::Absolute([19, 5])));
|
||||
assert_eq!(placement, Some(Position::Absolute([26, 5])));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
//! Migrations of the nodes in `raster_nodes`.
|
||||
|
||||
mod mandelbrot_v1;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod pattern_square;
|
||||
mod renames;
|
||||
@@ -0,0 +1,97 @@
|
||||
use super::pattern_square::{SquareNodes, Tagged, fill_square_with_pattern};
|
||||
use migration_core::{Attributes, Downstream, Inputs, MigrationError, Node, decl, literal_of, migration};
|
||||
|
||||
const CLIP: u32 = 1;
|
||||
|
||||
/// The pattern fills the plane, so the Clip toggle that cut it off at a 100-unit square is gone, and a clipped pattern is read through that square
|
||||
/// filled with it. A wired toggle counts as clipped.
|
||||
#[migration("raster_nodes::std_nodes::NoisePatternNode"@1 => @2)]
|
||||
pub fn noise_pattern_v1(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) -> Result<(), MigrationError> {
|
||||
let Some(clip) = node.inputs().get(CLIP as usize) else {
|
||||
return Err(MigrationError::invariant("Noise Pattern has a Clip input"));
|
||||
};
|
||||
let clipped = !matches!(literal_of::<Tagged>(&clip.input), Some(Tagged::Bool(false)));
|
||||
|
||||
inputs.remove(CLIP);
|
||||
|
||||
if clipped {
|
||||
let nodes = SquareNodes {
|
||||
rectangle: decl!("vector_nodes::generator_nodes::RectangleNode"@1),
|
||||
fill: decl!("graphene_core::vector::FillNode"@1),
|
||||
transform: decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
};
|
||||
fill_square_with_pattern(node, downstream, attributes, nodes, 100.);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{Declaration, NodeInput, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@1);
|
||||
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract {
|
||||
// The toggle a clipped pattern's readers move off of can't be reading that pattern, since its own migration removes it
|
||||
reads_own_output: |slot| slot != CLIP as usize,
|
||||
..SourceContract::new(16, |random, slot| match slot {
|
||||
1 => literal(Tagged::Bool(random.below(2) == 0)),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn noise_inputs(clip: bool) -> Vec<NodeInput> {
|
||||
let mut inputs: Vec<NodeInput> = (0..16).map(|slot| literal(Tagged::Number(slot as f64))).collect();
|
||||
inputs[CLIP as usize] = literal(Tagged::Bool(clip));
|
||||
inputs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&NoisePatternV1, &contract());
|
||||
check_undo(&NoisePatternV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clipped_pattern_is_read_through_a_square_filled_with_it() {
|
||||
let mut fixture = Fixture::new(&NoisePatternV1);
|
||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs(true));
|
||||
let consumer = fixture.add(CONSUMER, vec![NodeInput::Node { id: noise, index: 0 }]);
|
||||
let migrated = fixture.migrate(&NoisePatternV1).unwrap();
|
||||
|
||||
// The settings after the removed toggle move down a slot
|
||||
let inputs = fixture.inputs(&migrated, noise);
|
||||
assert_eq!(inputs.len(), 15);
|
||||
assert_eq!(inputs[CLIP as usize], literal(Tagged::Number(2.)));
|
||||
|
||||
let reads = |node, slot: usize| match fixture.inputs(&migrated, node)[slot] {
|
||||
NodeInput::Node { id, .. } => id,
|
||||
_ => panic!("slot {slot} of {node:?} should read a node"),
|
||||
};
|
||||
let placement = reads(consumer, 0);
|
||||
let fill = reads(placement, 0);
|
||||
let paint = reads(fill, 1);
|
||||
assert_eq!(reads(paint, 0), noise);
|
||||
assert_eq!(fixture.declaration_of(&migrated, reads(fill, 0)), Some(decl!("vector_nodes::generator_nodes::RectangleNode"@1)));
|
||||
assert_eq!(fixture.inputs(&migrated, placement)[1], literal(Tagged::DVec2([50., 50.])));
|
||||
assert_eq!(fixture.inputs(&migrated, paint)[1], literal(Tagged::DVec2([-50., -50.])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclipped_pattern_keeps_its_readers() {
|
||||
let mut fixture = Fixture::new(&NoisePatternV1);
|
||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs(false));
|
||||
let consumer = fixture.add(CONSUMER, vec![NodeInput::Node { id: noise, index: 0 }]);
|
||||
let migrated = fixture.migrate(&NoisePatternV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, noise).len(), 15);
|
||||
assert_eq!(fixture.inputs(&migrated, consumer), [NodeInput::Node { id: noise, index: 0 }]);
|
||||
assert_eq!(migrated.node_instances.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! The square that Noise Pattern and Mandelbrot were cut off at before their patterns filled the plane, which their migrations keep.
|
||||
|
||||
use migration_core::attr::node::ui::POSITION;
|
||||
use migration_core::{Attributes, Declaration, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, literal};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants these migrations use.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
BoxCorners(Vec<f64>),
|
||||
Color(Color),
|
||||
GradientRamp(GradientRamp),
|
||||
GradientForm(GradientForm),
|
||||
DVec2([f64; 2]),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct Color {
|
||||
red: f32,
|
||||
green: f32,
|
||||
blue: f32,
|
||||
alpha: f32,
|
||||
linear: bool,
|
||||
}
|
||||
|
||||
impl Color {
|
||||
fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
|
||||
Self {
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
alpha,
|
||||
linear: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct GradientRamp {
|
||||
stops: GradientStops,
|
||||
gradient_space: GradientSpace,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct GradientStops {
|
||||
color: Vec<Color>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) enum GradientSpace {
|
||||
OkLab,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) enum GradientForm {
|
||||
Linear,
|
||||
}
|
||||
|
||||
/// The declarations the square is built from, which each migration names itself so the runner orders it against them.
|
||||
pub(super) struct SquareNodes {
|
||||
pub rectangle: Declaration,
|
||||
pub fill: Declaration,
|
||||
pub transform: Declaration,
|
||||
}
|
||||
|
||||
/// Makes everything reading the pattern read a rectangle filled with it instead, covering the square from the origin of the pattern's space out to `size`.
|
||||
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
|
||||
pub(super) fn fill_square_with_pattern(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes, nodes: SquareNodes, size: f64) {
|
||||
let consumers = downstream.consumers(0);
|
||||
if consumers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let number = |number| literal(Tagged::Number(number));
|
||||
let pair = |value| literal(Tagged::DVec2([value, value]));
|
||||
let wire = |id| NodeInput::Node { id, index: 0 };
|
||||
let transform = |content, translation| vec![content, pair(translation), number(0.), pair(1.), pair(0.)];
|
||||
|
||||
let rectangle = downstream.add_node(NewNode {
|
||||
declaration: nodes.rectangle,
|
||||
inputs: vec![
|
||||
literal(Tagged::None),
|
||||
number(size),
|
||||
number(size),
|
||||
literal(Tagged::BoxCorners(Vec::new())),
|
||||
literal(Tagged::Bool(true)),
|
||||
literal(Tagged::Bool(false)),
|
||||
],
|
||||
});
|
||||
let paint = downstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: nodes.transform,
|
||||
inputs: transform(wire(node.id()), -size / 2.),
|
||||
},
|
||||
"paint",
|
||||
);
|
||||
|
||||
// Past the rectangle and its paint, the Fill holds the defaults its definition gives a new node
|
||||
let backup_gradient = GradientRamp {
|
||||
stops: GradientStops {
|
||||
color: vec![Color::new(0., 0., 0., 1.), Color::new(1., 1., 1., 1.)],
|
||||
},
|
||||
gradient_space: GradientSpace::OkLab,
|
||||
};
|
||||
let fill = downstream.add_node(NewNode {
|
||||
declaration: nodes.fill,
|
||||
inputs: vec![
|
||||
wire(rectangle),
|
||||
wire(paint),
|
||||
literal(Tagged::Color(Color::new(0., 0., 0., 0.))),
|
||||
literal(Tagged::GradientRamp(backup_gradient)),
|
||||
literal(Tagged::GradientForm(GradientForm::Linear)),
|
||||
literal(Tagged::Bool(false)),
|
||||
literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
|
||||
],
|
||||
});
|
||||
|
||||
let placement = downstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: nodes.transform,
|
||||
inputs: transform(wire(fill), size / 2.),
|
||||
},
|
||||
"placement",
|
||||
);
|
||||
for consumer in consumers {
|
||||
downstream.connect(OutputConnector { node: placement, output: 0 }, consumer);
|
||||
}
|
||||
|
||||
// In a layer's chain, the filled rectangle takes the pattern's place. The pattern and its paint leave the chain with no coordinates to go by,
|
||||
// so they start at the graph's origin. Elsewhere the square sits to the pattern's right.
|
||||
let stored = node.attributes().get_typed::<Position>(POSITION);
|
||||
if stored == Some(Position::Chain) {
|
||||
for id in [placement, fill, rectangle] {
|
||||
attributes.set(id, POSITION, &Position::Chain);
|
||||
}
|
||||
|
||||
attributes.set(node.id(), POSITION, &Position::Absolute([0, 0]));
|
||||
attributes.set(paint, POSITION, &Position::Absolute([7, 0]));
|
||||
} else {
|
||||
let [x, y] = match stored {
|
||||
Some(Position::Absolute(coordinates)) => coordinates,
|
||||
_ => [0, 0],
|
||||
};
|
||||
for (id, [x_offset, y_offset]) in [(paint, [7, 0]), (rectangle, [7, -3]), (fill, [14, 0]), (placement, [21, 0])] {
|
||||
attributes.set(id, POSITION, &Position::Absolute([x + x_offset, y + y_offset]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::format_f64;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
@@ -32,7 +33,7 @@ use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Graphic};
|
||||
use graphene_std::{Appearance, Artboard, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::ops::Range;
|
||||
@@ -394,6 +395,7 @@ macro_rules! inspectable_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
@@ -450,6 +452,7 @@ macro_rules! inspectable_types {
|
||||
Item<Raster<GPU>>,
|
||||
Item<Color>,
|
||||
Item<Gradient>,
|
||||
Item<Generator>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<i64>,
|
||||
@@ -792,6 +795,45 @@ impl TableItemLayout for Coverage {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effects {
|
||||
fn type_name() -> &'static str {
|
||||
"Effects"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effects".to_string()
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
// Label the spreadsheet's element button with the inner list's identifier, like Appearance
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effect {
|
||||
fn type_name() -> &'static str {
|
||||
"Effect"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effect".to_string()
|
||||
}
|
||||
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for TransferCurve {
|
||||
fn type_name() -> &'static str {
|
||||
"TransferCurve"
|
||||
@@ -857,6 +899,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.identifier(),
|
||||
Self::Color(item) => item.identifier(),
|
||||
Self::Gradient(item) => item.identifier(),
|
||||
Self::Generator(item) => item.identifier(),
|
||||
Self::Text(item) => item.identifier(),
|
||||
Self::NoneList(list) => list.identifier(),
|
||||
Self::GraphicList(list) => list.identifier(),
|
||||
@@ -865,6 +908,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.identifier(),
|
||||
Self::ColorList(list) => list.identifier(),
|
||||
Self::GradientList(list) => list.identifier(),
|
||||
Self::GeneratorList(list) => list.identifier(),
|
||||
Self::TextList(list) => list.identifier(),
|
||||
Self::StrokeList(list) => list.identifier(),
|
||||
}
|
||||
@@ -882,6 +926,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Color(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Gradient(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Generator(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Text(item) => item.layout_with_breadcrumb(data),
|
||||
Self::NoneList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
|
||||
@@ -890,6 +935,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::ColorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GradientList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GeneratorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::TextList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
|
||||
}
|
||||
@@ -1213,6 +1259,11 @@ macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
Cover,
|
||||
BevelDirection,
|
||||
BevelStyle,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
@@ -1359,9 +1410,11 @@ macro_rules! known_item_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
Gradient,
|
||||
Generator,
|
||||
Color,
|
||||
NodeId,
|
||||
DAffine2,
|
||||
@@ -1383,6 +1436,12 @@ macro_rules! known_item_types {
|
||||
Appearance,
|
||||
Coverage,
|
||||
Cover,
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
|
||||
@@ -325,6 +325,9 @@ pub enum DocumentMessage {
|
||||
UpdateAppearanceAttributes {
|
||||
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
|
||||
},
|
||||
UpdateEffectsReach {
|
||||
effects_reach: HashMap<NodeId, f64>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
UngroupLayer {
|
||||
|
||||
@@ -1915,6 +1915,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||
}
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
||||
let layer_effects_reach = effects_reach
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
|
||||
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
||||
.collect();
|
||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
|
||||
@@ -761,20 +761,26 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
|
||||
/// from the default (`Linear`).
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||
let [start, end] = match gradient_form {
|
||||
GradientForm::Linear => LINEAR_DIALS,
|
||||
GradientForm::Radial => RADIAL_DIALS,
|
||||
};
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
}
|
||||
|
||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||
|
||||
@@ -760,6 +760,7 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
||||
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
||||
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
||||
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
|
||||
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
|
||||
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, Graphic, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
@@ -438,6 +439,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -3046,6 +3050,79 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
|
||||
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
||||
}
|
||||
|
||||
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::math_nodes::gradient_curvature::*;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
|
||||
let curvatures = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
|
||||
Some(&TaggedValue::Number(value)) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
|
||||
// Each form's button sets both curvatures to the form's own, and stands out while they're exactly those
|
||||
let mut form = vec![
|
||||
TextLabel::new("Form")
|
||||
.tooltip_label("Form")
|
||||
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
|
||||
.widget_instance(),
|
||||
];
|
||||
add_blank_assist(&mut form);
|
||||
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
for (label, [start, end], tooltip) in [
|
||||
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
|
||||
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
|
||||
] {
|
||||
form.push(
|
||||
TextButton::new(label)
|
||||
.tooltip_description(tooltip)
|
||||
.emphasized(curvatures == Some([start, end]))
|
||||
.disabled(curvatures.is_none())
|
||||
.on_update(move |_: &TextButton| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: StartCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(start).into(),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: EndCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(end).into(),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
// The same sliders the curvatures would get without this panel
|
||||
let options = ParameterOptions {
|
||||
soft_min: Some(-1.),
|
||||
soft_max: Some(1.),
|
||||
slider: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
|
||||
|
||||
let mut layout = vec![LayoutGroup::row(form)];
|
||||
layout.extend(curvature(StartCurvatureInput::INDEX));
|
||||
layout.extend(curvature(EndCurvatureInput::INDEX));
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
|
||||
@@ -34,6 +34,8 @@ impl FrontendGraphDataType {
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
// A generator draws pixels like an image, at whatever resolution is needed
|
||||
"Generator" => Self::Raster,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
|
||||
@@ -270,7 +270,7 @@ impl OverlayContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_scene(self) -> VelloSceneBuilder {
|
||||
pub fn take_scene(self) -> VelloSceneBuilder<'static> {
|
||||
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
|
||||
let empty_scene = overlay_scene(&internal.viewport);
|
||||
std::mem::replace(&mut internal.scene, empty_scene)
|
||||
@@ -486,13 +486,13 @@ pub enum DrawHandles {
|
||||
}
|
||||
|
||||
pub(super) struct OverlayContextInternal {
|
||||
scene: VelloSceneBuilder,
|
||||
scene: VelloSceneBuilder<'static>,
|
||||
viewport: ViewportMessageHandler,
|
||||
visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
|
||||
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder {
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static> {
|
||||
// The smallest texture size limit WebGL2 guarantees, which only matters for the overlays' tiny pattern images
|
||||
const MAX_TEXTURE_SIZE: u32 = 2048;
|
||||
|
||||
|
||||
@@ -51,6 +51,8 @@ pub struct DocumentMetadata {
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
|
||||
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
|
||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
|
||||
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
|
||||
/// Transform from document space to viewport space.
|
||||
pub document_to_viewport: DAffine2,
|
||||
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
||||
@@ -347,9 +349,9 @@ impl DocumentMetadata {
|
||||
}
|
||||
|
||||
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
|
||||
/// stroke geometry when the layer is a vector with a stroke style. Only the first item of a layer's vector data
|
||||
/// is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a
|
||||
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
||||
let stroke = self
|
||||
.layer_appearance_attributes
|
||||
@@ -359,8 +361,10 @@ impl DocumentMetadata {
|
||||
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
||||
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
|
||||
});
|
||||
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||
|
||||
[stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)
|
||||
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
||||
Some([min - reach, max + reach])
|
||||
}
|
||||
|
||||
/// Get the bounding box of the click target of the specified layer in viewport space
|
||||
@@ -732,7 +736,7 @@ mod tests {
|
||||
let later_item = ClickTarget::new_with_path(line(100., 110.), 0.);
|
||||
metadata.click_targets.insert(layer, vec![Arc::new(later_item)]);
|
||||
|
||||
let [min, max] = metadata.bounding_box_document_with_stroke(layer).unwrap();
|
||||
let [min, max] = metadata.bounding_box_document_with_stroke_and_effects(layer).unwrap();
|
||||
assert_eq!((min.x, max.x), (0., 110.));
|
||||
}
|
||||
|
||||
|
||||
@@ -1063,11 +1063,11 @@ impl NodeNetworkInterface {
|
||||
Some(transformed.bounding_box())
|
||||
}
|
||||
|
||||
/// Calculates the document bounds in document space, expanding vector layer bounds to include the rendered
|
||||
/// stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the document bounds in document space, expanding layer bounds to include the rendered stroke width and
|
||||
/// effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
self.document_metadata.document_bounds(include_artboards, true, || {
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke(layer))
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1084,17 +1084,17 @@ impl NodeNetworkInterface {
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Calculates the selected layer bounds in document space, expanding vector layer bounds to include the
|
||||
/// rendered stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the selected layer bounds in document space, expanding layer bounds to include the rendered stroke width
|
||||
/// and effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke_and_effects");
|
||||
return None;
|
||||
};
|
||||
selected_nodes
|
||||
.selected_layers(&self.document_metadata)
|
||||
.filter(|&layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
|
||||
@@ -200,4 +200,9 @@ impl NodeNetworkInterface {
|
||||
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
|
||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||
}
|
||||
|
||||
/// Update how far each layer's effects paint past its content.
|
||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
|
||||
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,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;
|
||||
@@ -295,10 +295,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"],
|
||||
@@ -512,8 +508,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::filter::blur::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
node: graphene_std::blending_nodes::effects::blur::IDENTIFIER,
|
||||
aliases: &["raster_nodes::filter::BlurNode", "graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
|
||||
@@ -533,8 +529,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ChannelMixerNode",
|
||||
],
|
||||
},
|
||||
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
node: graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::ColorOverlayNode",
|
||||
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
|
||||
@@ -542,6 +539,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::adjustments::ColorOverlayNode",
|
||||
"raster_nodes::generate_curves::ColorOverlayNode",
|
||||
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
"raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -1279,6 +1277,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if *new == graphene_std::math_nodes::math_function::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Math f(x)");
|
||||
}
|
||||
|
||||
if *new == graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1684,6 +1686,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take the presets of the form it set
|
||||
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
|
||||
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
|
||||
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path) in &gradient_form_nodes {
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
reset_default_display_name(document, node_id, network_path, "Gradient Form");
|
||||
|
||||
if let Some(input) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
|
||||
}
|
||||
|
||||
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::GradientForm(GradientForm::Radial)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
|
||||
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
|
||||
_ => {
|
||||
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
|
||||
graphene_std::renderer::dial_gradient::LINEAR_DIALS
|
||||
}
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
|
||||
}
|
||||
|
||||
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
|
||||
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
|
||||
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
||||
@@ -1862,6 +1907,52 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew images cut off at a square, 100 units for a clipped Noise Pattern and 1 for Mandelbrot, where their
|
||||
// patterns now fill the plane. An old Noise Pattern has a Clip toggle, after the primary input or first from before that input existed,
|
||||
// and an old Mandelbrot lacks the primary input. Each takes the current inputs, with a square filled by its pattern where it was cut off.
|
||||
let old_pattern_nodes = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let reference = document.network_interface.reference(node_id, &path)?;
|
||||
let clipped = |clip_index: usize| !matches!(node.inputs.get(clip_index).and_then(|input| input.as_value()), Some(TaggedValue::Bool(false)));
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
|
||||
let starts_with_clip = matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::Bool(_)));
|
||||
let clip_index = match node.inputs.len() {
|
||||
16 => 1,
|
||||
15 if starts_with_clip => 0,
|
||||
_ => return None,
|
||||
};
|
||||
return Some((*node_id, path, reference, Some(clip_index), clipped(clip_index).then_some(100.)));
|
||||
}
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) && node.inputs.is_empty() {
|
||||
return Some((*node_id, path, reference, None, Some(1.)));
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for (node_id, network_path, reference, clip_index, clipped_size) in &old_pattern_nodes {
|
||||
let Some(definition) = resolve_document_node_type(reference) 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;
|
||||
};
|
||||
|
||||
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
|
||||
if let Some(clip_index) = clip_index {
|
||||
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(size) = clipped_size {
|
||||
fill_square_with_pattern(document, node_id, network_path, *size);
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
|
||||
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
|
||||
@@ -1921,6 +2012,76 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.require_whole_document_stage();
|
||||
}
|
||||
|
||||
/// Splices a rectangle filled with the pattern node's output onto the wires leaving it, covering the square from the origin of the pattern's space out to `size`.
|
||||
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
|
||||
fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_id: &NodeId, network_path: &[NodeId], size: f64) -> Option<()> {
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
|
||||
|
||||
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
|
||||
let rectangle_template = template(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)?;
|
||||
let fill_template = template(graphene_std::vector_nodes::fill::IDENTIFIER)?;
|
||||
let transform_template = template(graphene_std::transform_nodes::transform::IDENTIFIER)?;
|
||||
|
||||
let [rectangle_id, fill_id, paint_transform_id, placement_transform_id] = [(); 4].map(|_| NodeId::new());
|
||||
document.network_interface.insert_node(rectangle_id, rectangle_template, network_path);
|
||||
document.network_interface.insert_node(fill_id, fill_template, network_path);
|
||||
document.network_interface.insert_node(paint_transform_id, transform_template.clone(), network_path);
|
||||
document.network_interface.insert_node(placement_transform_id, transform_template, network_path);
|
||||
|
||||
let set_value = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, value: TaggedValue| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(value, false), network_path);
|
||||
};
|
||||
let wire = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, source: NodeId| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::node(source, 0), network_path);
|
||||
};
|
||||
|
||||
// The rectangle's width and height, and the half-square translations of the paint and the filled rectangle
|
||||
set_value(document, rectangle_id, 1, TaggedValue::Number(size));
|
||||
set_value(document, rectangle_id, 2, TaggedValue::Number(size));
|
||||
set_value(document, paint_transform_id, 1, TaggedValue::DVec2(DVec2::splat(-size / 2.)));
|
||||
set_value(document, placement_transform_id, 1, TaggedValue::DVec2(DVec2::splat(size / 2.)));
|
||||
|
||||
wire(document, paint_transform_id, 0, *pattern_node_id);
|
||||
wire(document, fill_id, 0, rectangle_id);
|
||||
wire(document, fill_id, 1, paint_transform_id);
|
||||
wire(document, placement_transform_id, 0, fill_id);
|
||||
for consumer in &downstream_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(placement_transform_id, 0), network_path);
|
||||
}
|
||||
|
||||
// A pattern in a layer chain gives way to the filled rectangle there, moving below to paint it, and otherwise the new nodes sit beside it
|
||||
if was_in_chain {
|
||||
document.network_interface.force_set_upstream_to_chain(&placement_transform_id, network_path);
|
||||
|
||||
if let Some(fill_position) = document.network_interface.position(&fill_id, network_path) {
|
||||
document.network_interface.set_absolute_position(&paint_transform_id, fill_position + IVec2::new(-7, 3), network_path);
|
||||
document.network_interface.set_absolute_position(pattern_node_id, fill_position + IVec2::new(-14, 3), network_path);
|
||||
}
|
||||
} else if let Some(position) = document.network_interface.position(pattern_node_id, network_path) {
|
||||
let offsets = [
|
||||
(paint_transform_id, IVec2::new(7, 0)),
|
||||
(rectangle_id, IVec2::new(7, -3)),
|
||||
(fill_id, IVec2::new(14, 0)),
|
||||
(placement_transform_id, IVec2::new(21, 0)),
|
||||
];
|
||||
for (node_id, offset) in offsets {
|
||||
document.network_interface.shift_absolute_node_position(&node_id, position + offset, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -2452,7 +2613,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
|
||||
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
|
||||
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
|
||||
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
|
||||
];
|
||||
for (parameter, fallback) in conversions {
|
||||
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
|
||||
@@ -2773,20 +2933,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
|
||||
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), NodeInput::value(TaggedValue::None, false), network_path);
|
||||
for (i, input) in old_inputs.iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i + 1), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The Threshold node's luminance calculation input was retired
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -5105,6 +5251,54 @@ 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;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
||||
for (identifier, form, dials) in [
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
|
||||
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
|
||||
] {
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let placeholder = || NodeInput::value(TaggedValue::None, false);
|
||||
document.network_interface.insert_node(
|
||||
source_id,
|
||||
NodeTemplate {
|
||||
inputs: vec![placeholder()],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.insert_node(
|
||||
form_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![placeholder(); 2],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), false), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let 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)],
|
||||
dials.map(|dial| Some(TaggedValue::Number(dial))),
|
||||
"{form:?} should become its curvature presets"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
@@ -6054,4 +6248,79 @@ mod tests {
|
||||
assert!(converted > 0. && converted < 1., "bias {bias} became {converted}");
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew a square of their patterns, which now fill the plane, so the square becomes a rectangle filled with the pattern
|
||||
#[tokio::test]
|
||||
async fn clipped_patterns_become_rectangles_filled_with_them() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let noise = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER)).await;
|
||||
let mandelbrot = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER)).await;
|
||||
let noise_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
let mandelbrot_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
|
||||
let document = editor.active_document_mut();
|
||||
for (reader, pattern) in [(noise_reader, noise), (mandelbrot_reader, mandelbrot)] {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(pattern, 0), &[]);
|
||||
}
|
||||
|
||||
// Save them as an older editor did, the Noise Pattern with its Clip toggle on and the Mandelbrot without a primary input
|
||||
let mut noise_inputs = document.network_interface.document_node(&noise, &[]).unwrap().inputs.clone();
|
||||
noise_inputs.insert(1, NodeInput::value(TaggedValue::Bool(true), false));
|
||||
noise_inputs[2] = NodeInput::value(TaggedValue::Integer(7), false);
|
||||
for (node_id, inputs) in [(noise, noise_inputs), (mandelbrot, Vec::new())] {
|
||||
let mut legacy = NodeTemplate { inputs, ..Default::default() };
|
||||
legacy.normalize_input_metadata();
|
||||
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
|
||||
}
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
let input = |node_id: NodeId, index: usize| interface.document_node(&node_id, &[]).and_then(|node| node.inputs.get(index)).cloned();
|
||||
let upstream = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_node());
|
||||
let value = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_value().cloned());
|
||||
|
||||
// Each reader now reads a rectangle of the square's size, moved onto the square, filled with the pattern moved back by the same amount
|
||||
for (reader, pattern, size) in [(noise_reader, noise, 100.), (mandelbrot_reader, mandelbrot, 1.)] {
|
||||
let placement = upstream(reader, 0).expect("the reader should read the placement transform");
|
||||
assert_eq!(value(placement, 1), Some(TaggedValue::DVec2(DVec2::splat(size / 2.))));
|
||||
|
||||
let fill = upstream(placement, 0).expect("the placement should move the filled rectangle");
|
||||
let rectangle = upstream(fill, 0).expect("the fill should paint a rectangle");
|
||||
assert_eq!((value(rectangle, 1), value(rectangle, 2)), (Some(TaggedValue::Number(size)), Some(TaggedValue::Number(size))));
|
||||
|
||||
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
|
||||
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
|
||||
assert_eq!(upstream(paint, 0), Some(pattern));
|
||||
}
|
||||
|
||||
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
|
||||
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
|
||||
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
|
||||
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
|
||||
}
|
||||
|
||||
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
||||
#[tokio::test]
|
||||
async fn marbled_mandelbrot_renders_after_migration() {
|
||||
use crate::messages::portfolio::ingest::utility_types::{DataTransferItem, IngestAction};
|
||||
use crate::messages::prelude::IngestMessage;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
let data = std::fs::read("../demo-artwork/marbled-mandelbrot.graphite").unwrap();
|
||||
editor.dispatch(IngestMessage::Ingest {
|
||||
content: DataTransferItem::from_file("marbled-mandelbrot.graphite".into(), None, data).into(),
|
||||
action: IngestAction::Open,
|
||||
});
|
||||
if let Err(error) = editor.eval_graph_until_finished().await {
|
||||
panic!("The migrated demo failed to render: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -413,7 +413,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
||||
|
||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
|
||||
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
||||
let mut gradient_form: Option<GradientForm> = None;
|
||||
@@ -430,11 +430,14 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
|
||||
if reference == transform_reference {
|
||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||
} else if reference == gradient_form_reference
|
||||
&& gradient_form.is_none()
|
||||
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||
{
|
||||
gradient_form = Some(*value);
|
||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
||||
// Curvatures other than the radial form's are drawn with the linear form's controls
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::Number(value)) => value,
|
||||
_ => 0.,
|
||||
};
|
||||
let is_radial = [curvature(1), curvature(2)] == graphene_std::renderer::dial_gradient::RADIAL_DIALS;
|
||||
gradient_form = Some(if is_radial { GradientForm::Radial } else { GradientForm::Linear });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3366,7 +3369,7 @@ mod test_gradient {
|
||||
.await;
|
||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
||||
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
editor
|
||||
@@ -3375,7 +3378,7 @@ mod test_gradient {
|
||||
})
|
||||
.await;
|
||||
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let form_node_id = {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
network_interface
|
||||
@@ -3384,10 +3387,10 @@ mod test_gradient {
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
||||
.expect("Gradient Form node should have been inserted")
|
||||
.expect("Gradient Curvature node should have been inserted")
|
||||
};
|
||||
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
|
||||
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
||||
|
||||
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
||||
|
||||
@@ -448,11 +448,11 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
|
||||
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
|
||||
// `AllArtwork` and `Selection` expand vector layer bounds by the rendered stroke width so strokes
|
||||
// drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
// `AllArtwork` and `Selection` expand layer bounds by the rendered stroke width and effects reach so strokes
|
||||
// and shadows drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
let bounds = match export_config.bounds {
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke(true, &[]),
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke_and_effects(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke_and_effects(true, &[]),
|
||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
||||
}
|
||||
.ok_or_else(|| "No bounding box".to_string())?;
|
||||
@@ -1034,6 +1034,7 @@ impl NodeGraphExecutor {
|
||||
clip_targets,
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
effects_reach,
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
@@ -1050,6 +1051,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
@@ -588,31 +588,48 @@ mod tests {
|
||||
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
|
||||
}
|
||||
|
||||
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations.
|
||||
fn vectorize_layer(editor: &mut EditorTestUtils) {
|
||||
/// Adds a layer tracing an image of noise, which an export has to wait on over several evaluations.
|
||||
async fn add_traced_noise_layer(editor: &mut EditorTestUtils) {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::raster::color::Color;
|
||||
|
||||
// Pseudo-random grays from an xorshift sequence, so the trace finds many small regions
|
||||
let mut noise = Image::new(64, 64, Color::BLACK);
|
||||
let mut state = 0x2545_f491_u32;
|
||||
for pixel in &mut noise.data {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
let gray = (state % 256) as f32 / 255.;
|
||||
*pixel = Color::from_rgbaf32_unchecked(gray, gray, gray, 1.);
|
||||
}
|
||||
editor.create_raster_image(noise, None).await;
|
||||
|
||||
// Trace the image between the layer and the nodes feeding it
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
let mut create = |node_type| {
|
||||
let node_id = NodeId::new();
|
||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(node_id),
|
||||
node_type,
|
||||
xy: None,
|
||||
add_transaction: true,
|
||||
});
|
||||
node_id
|
||||
};
|
||||
let noise = create(DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER));
|
||||
let vectorize = create(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER));
|
||||
let content = InputConnector::node_at_index(layer.to_node(), 1);
|
||||
let image = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.upstream_output_connector(&content, &[])
|
||||
.expect("the image layer has content");
|
||||
|
||||
let vectorize = NodeId::new();
|
||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(vectorize),
|
||||
node_type: DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER),
|
||||
xy: None,
|
||||
add_transaction: true,
|
||||
});
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(noise),
|
||||
output_connector: image,
|
||||
input_connector: InputConnector::node_at_index(vectorize, 0),
|
||||
});
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(vectorize),
|
||||
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
|
||||
input_connector: content,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -659,8 +676,7 @@ mod tests {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||
editor.draw_rect(0., 0., 512., 512.).await;
|
||||
vectorize_layer(&mut editor);
|
||||
add_traced_noise_layer(&mut editor).await;
|
||||
|
||||
send_export(&mut editor);
|
||||
editor.runtime.update();
|
||||
|
||||
@@ -540,9 +540,10 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||
> .text-label:only-child {
|
||||
// A label with no expose button before it lines up with the parameter names that follow one
|
||||
> .text-label:first-child {
|
||||
margin-left: calc(20px + 8px + 8px);
|
||||
--wire-indent: 20px;
|
||||
}
|
||||
|
||||
> .separator.horizontal.unrelated {
|
||||
|
||||
@@ -577,6 +577,9 @@ tagged_value! {
|
||||
TonalRange(raster_nodes::adjustments::TonalRange),
|
||||
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
|
||||
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
|
||||
GlowSource(graphic_types::GlowSource),
|
||||
BevelStyle(graphic_types::BevelStyle),
|
||||
BevelDirection(graphic_types::BevelDirection),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -711,6 +714,25 @@ impl TaggedValue {
|
||||
None
|
||||
}
|
||||
|
||||
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
||||
let mut choices = input.split("::");
|
||||
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
||||
if first == "StrokeAlign" {
|
||||
return Some(match second {
|
||||
"Center" => vector::style::StrokeAlign::Center,
|
||||
"Inside" => vector::style::StrokeAlign::Inside,
|
||||
"Outside" => vector::style::StrokeAlign::Outside,
|
||||
_ => {
|
||||
log::error!("Invalid StrokeAlign default type variant: {input}");
|
||||
return None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
log::error!("Invalid StrokeAlign default type: {input}");
|
||||
None
|
||||
}
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
@@ -729,6 +751,7 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
_ => return None,
|
||||
|
||||
@@ -8,6 +8,7 @@ use graphene_animation::AnimationCurve;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::Stroke;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{AttributeValueDyn, Bundle, Item, List, ListDyn, NodeIdPath};
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -27,6 +28,7 @@ use graphene_std::vector::misc::{
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, GlowSource};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -56,6 +58,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
@@ -76,6 +79,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
@@ -285,6 +289,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
@@ -318,6 +325,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Graphic,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
String,
|
||||
f64,
|
||||
DVec2,
|
||||
@@ -350,6 +358,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
f64,
|
||||
i64,
|
||||
bool,
|
||||
@@ -390,6 +399,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
String,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
Artboard,
|
||||
));
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -441,6 +451,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// This is what lets a paint list zip element-wise against the content it paints.
|
||||
node_types.extend(embed_adapter_row!(from_element: Color, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Gradient, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Generator, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: String, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Vector, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Raster<CPU>, element: Graphic));
|
||||
@@ -498,6 +509,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(List<String>),
|
||||
attribute_value_node!(List<Color>),
|
||||
attribute_value_node!(List<Gradient>),
|
||||
attribute_value_node!(List<Generator>),
|
||||
attribute_value_node!(List<Vector>),
|
||||
attribute_value_node!(List<Raster<CPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -526,6 +538,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
transform_list_node!(element: Raster<GPU>),
|
||||
transform_list_node!(element: Color),
|
||||
transform_list_node!(element: Gradient),
|
||||
transform_list_node!(element: Generator),
|
||||
];
|
||||
node_types.extend(transform_list_rows);
|
||||
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
|
||||
|
||||
@@ -32,9 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
|
||||
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING,
|
||||
ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
|
||||
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
|
||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use num_traits;
|
||||
|
||||
@@ -61,6 +61,11 @@ pub const ATTR_CLIP: &str = "clip";
|
||||
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
||||
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||
/// Gradient's `f64` curvature dial for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
|
||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, the form decides it.
|
||||
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
|
||||
/// Gradient's `f64` curvature dial for the contour through its end, like `gradient_start_curvature` with the ends swapped.
|
||||
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
|
||||
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||
@@ -80,6 +85,9 @@ pub const ATTR_POSITION: &str = "position";
|
||||
pub const ATTR_MIDPOINT: &str = "midpoint";
|
||||
/// Item's ordered list of paint passes, of type `Appearance`. Earlier coverages paint first, compositing below later ones.
|
||||
pub const ATTR_APPEARANCE: &str = "appearance";
|
||||
/// Item's ordered list of effects, of type `Effects`, which the renderer applies in turn to the pixels the item renders to.
|
||||
/// Unlike the appearance, it doesn't cascade to descendants.
|
||||
pub const ATTR_EFFECTS: &str = "effects";
|
||||
// TODO: Add a "fill_rule" attribute as a sibling of "paint" on the coverage list (uniform across covers) once a FillRule type ships
|
||||
/// Coverage's `Graphic` paint (implicit default `Graphic::None`, painting nothing), on the
|
||||
/// `List<Coverage>` inside an `Appearance`.
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
//! Color adjustments as plain data, each holding its node's settings in the node's own units, carried out by the kernels of the `raster-kernels` crate.
|
||||
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::effects::EffectKind;
|
||||
use crate::parameters::ParameterVisitor;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
@@ -80,30 +84,204 @@ pub enum Adjustment {
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Adjustment {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Desaturate { .. } => "Desaturate",
|
||||
Self::GammaCorrection { .. } => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
Self::BrightnessContrast { .. } => "Brightness/Contrast",
|
||||
Self::Levels(_) => "Levels",
|
||||
Self::Curves(_) => "Curves",
|
||||
Self::BlackAndWhite(_) => "Black & White",
|
||||
Self::HueSaturation(_) => "Hue/Saturation",
|
||||
Self::Invert => "Invert",
|
||||
Self::Threshold { .. } => "Threshold",
|
||||
Self::GradientMap { .. } => "Gradient Map",
|
||||
Self::Vibrance { .. } => "Vibrance",
|
||||
Self::ChannelMixer(_) => "Channel Mixer",
|
||||
Self::SelectiveColor(_) => "Selective Color",
|
||||
Self::Posterize { .. } => "Posterize",
|
||||
Self::Exposure { .. } => "Exposure",
|
||||
Self::ColorBalance(_) => "Color Balance",
|
||||
Self::PhotoFilter { .. } => "Photo Filter",
|
||||
Self::ColorLookup { .. } => "Color Lookup",
|
||||
Self::ColorOverlay { .. } => "Color Overlay",
|
||||
})
|
||||
impl Adjustment {
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
match self {
|
||||
Self::Desaturate { .. } => EffectKind::Desaturate,
|
||||
Self::GammaCorrection { .. } => EffectKind::GammaCorrection,
|
||||
Self::MakeOpaque => EffectKind::MakeOpaque,
|
||||
Self::BrightnessContrast { .. } => EffectKind::BrightnessContrast,
|
||||
Self::Levels(_) => EffectKind::Levels,
|
||||
Self::Curves(_) => EffectKind::Curves,
|
||||
Self::BlackAndWhite(_) => EffectKind::BlackAndWhite,
|
||||
Self::HueSaturation(_) => EffectKind::HueSaturation,
|
||||
Self::Invert => EffectKind::Invert,
|
||||
Self::Threshold { .. } => EffectKind::Threshold,
|
||||
Self::GradientMap { .. } => EffectKind::GradientMap,
|
||||
Self::Vibrance { .. } => EffectKind::Vibrance,
|
||||
Self::ChannelMixer(_) => EffectKind::ChannelMixer,
|
||||
Self::SelectiveColor(_) => EffectKind::SelectiveColor,
|
||||
Self::Posterize { .. } => EffectKind::Posterize,
|
||||
Self::Exposure { .. } => EffectKind::Exposure,
|
||||
Self::ColorBalance(_) => EffectKind::ColorBalance,
|
||||
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether each channel of the result depends only on the same channel of the color, making the adjustment four curves.
|
||||
pub fn is_per_channel(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::GammaCorrection { .. }
|
||||
| Self::MakeOpaque
|
||||
| Self::BrightnessContrast { .. }
|
||||
| Self::Levels(_)
|
||||
| Self::Curves(_)
|
||||
| Self::Invert
|
||||
| Self::Posterize { .. }
|
||||
| Self::Exposure { .. }
|
||||
| Self::ColorBalance(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// Visits each parameter with the attribute it rides, named after the node's parameter, and its implicit default, which is the node's.
|
||||
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
match self {
|
||||
Self::Desaturate { method } => visitor.parameter("method", method, DesaturateMethod::default()),
|
||||
Self::GammaCorrection { gamma, inverse } => {
|
||||
visitor.parameter("gamma", gamma, 2.2);
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque | Self::Invert => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
use_classic,
|
||||
classic_pivot,
|
||||
} => {
|
||||
visitor.parameter("brightness", brightness, 0.);
|
||||
visitor.parameter("contrast", contrast, 0.);
|
||||
visitor.parameter("use_classic", use_classic, false);
|
||||
visitor.parameter("classic_pivot", classic_pivot, 127.);
|
||||
}
|
||||
Self::Levels(settings) => {
|
||||
let LevelsSettings { composite, red, green, blue, alpha } = settings.as_mut();
|
||||
composite.visit_parameters(visitor, "");
|
||||
red.visit_parameters(visitor, "red");
|
||||
green.visit_parameters(visitor, "green");
|
||||
blue.visit_parameters(visitor, "blue");
|
||||
alpha.visit_parameters(visitor, "alpha");
|
||||
}
|
||||
Self::Curves(settings) => {
|
||||
let CurvesSettings { composite, red, green, blue, alpha } = settings.as_mut();
|
||||
visitor.parameter("curve", composite, TransferCurve::default());
|
||||
visitor.parameter("red_curve", red, TransferCurve::default());
|
||||
visitor.parameter("green_curve", green, TransferCurve::default());
|
||||
visitor.parameter("blue_curve", blue, TransferCurve::default());
|
||||
visitor.parameter("alpha_curve", alpha, TransferCurve::default());
|
||||
}
|
||||
Self::BlackAndWhite(settings) => {
|
||||
visitor.parameter("use_tint", &mut settings.use_tint, false);
|
||||
visitor.parameter("tint", &mut settings.tint, Color::from(SRGBA8::new(0xe1, 0xd3, 0xb3, 0xff)));
|
||||
visitor.parameter("reds", &mut settings.reds, 40.);
|
||||
visitor.parameter("yellows", &mut settings.yellows, 60.);
|
||||
visitor.parameter("greens", &mut settings.greens, 40.);
|
||||
visitor.parameter("cyans", &mut settings.cyans, 60.);
|
||||
visitor.parameter("blues", &mut settings.blues, 20.);
|
||||
visitor.parameter("magentas", &mut settings.magentas, 80.);
|
||||
}
|
||||
Self::HueSaturation(settings) => {
|
||||
let HueSaturationSettings {
|
||||
master,
|
||||
colorize,
|
||||
colorize_sliders,
|
||||
reds,
|
||||
yellows,
|
||||
greens,
|
||||
cyans,
|
||||
blues,
|
||||
magentas,
|
||||
} = settings.as_mut();
|
||||
|
||||
master.visit_parameters(visitor, "", [0., 0., 0.]);
|
||||
visitor.parameter("colorize", colorize, false);
|
||||
colorize_sliders.visit_parameters(visitor, "colorize", [24., 25., 0.]);
|
||||
|
||||
reds.visit_parameters(visitor, "reds", [315., 345., 15., 45.]);
|
||||
yellows.visit_parameters(visitor, "yellows", [15., 45., 75., 105.]);
|
||||
greens.visit_parameters(visitor, "greens", [75., 105., 135., 165.]);
|
||||
cyans.visit_parameters(visitor, "cyans", [135., 165., 195., 225.]);
|
||||
blues.visit_parameters(visitor, "blues", [195., 225., 255., 285.]);
|
||||
magentas.visit_parameters(visitor, "magentas", [255., 285., 315., 345.]);
|
||||
}
|
||||
Self::Threshold { min_luminance, max_luminance } => {
|
||||
visitor.parameter("min_luminance", min_luminance, 50.);
|
||||
visitor.parameter("max_luminance", max_luminance, 100.);
|
||||
}
|
||||
Self::GradientMap { gradient, reverse } => {
|
||||
visitor.parameter("gradient", gradient, Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])));
|
||||
visitor.parameter("reverse", reverse, false);
|
||||
}
|
||||
Self::Vibrance { vibrance, saturation } => {
|
||||
visitor.parameter("vibrance", vibrance, 0.);
|
||||
visitor.parameter("saturation", saturation, 0.);
|
||||
}
|
||||
Self::ChannelMixer(settings) => {
|
||||
let ChannelMixerSettings {
|
||||
monochrome,
|
||||
monochrome_mix,
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
} = settings.as_mut();
|
||||
|
||||
visitor.parameter("monochrome", monochrome, false);
|
||||
monochrome_mix.visit_parameters(visitor, "monochrome", [40., 40., 20., 0.]);
|
||||
red.visit_parameters(visitor, "red", [100., 0., 0., 0.]);
|
||||
green.visit_parameters(visitor, "green", [0., 100., 0., 0.]);
|
||||
blue.visit_parameters(visitor, "blue", [0., 0., 100., 0.]);
|
||||
}
|
||||
Self::SelectiveColor(settings) => {
|
||||
let SelectiveColorSettings {
|
||||
mode,
|
||||
reds,
|
||||
yellows,
|
||||
greens,
|
||||
cyans,
|
||||
blues,
|
||||
magentas,
|
||||
whites,
|
||||
neutrals,
|
||||
blacks,
|
||||
} = settings.as_mut();
|
||||
|
||||
visitor.parameter("mode", mode, RelativeAbsolute::default());
|
||||
let groups = [
|
||||
("reds", reds),
|
||||
("yellows", yellows),
|
||||
("greens", greens),
|
||||
("cyans", cyans),
|
||||
("blues", blues),
|
||||
("magentas", magentas),
|
||||
("whites", whites),
|
||||
("neutrals", neutrals),
|
||||
("blacks", blacks),
|
||||
];
|
||||
for (name, inks) in groups {
|
||||
inks.visit_parameters(visitor, name);
|
||||
}
|
||||
}
|
||||
Self::Posterize { levels } => visitor.parameter("levels", levels, 4),
|
||||
Self::Exposure { exposure, offset, gamma_correction } => {
|
||||
visitor.parameter("exposure", exposure, 0.);
|
||||
visitor.parameter("offset", offset, 0.);
|
||||
visitor.parameter("gamma_correction", gamma_correction, 1.);
|
||||
}
|
||||
Self::ColorBalance(settings) => {
|
||||
settings.shadows.visit_parameters(visitor, "shadows");
|
||||
settings.midtones.visit_parameters(visitor, "midtones");
|
||||
settings.highlights.visit_parameters(visitor, "highlights");
|
||||
visitor.parameter("preserve_luminosity", &mut settings.preserve_luminosity, true);
|
||||
}
|
||||
Self::PhotoFilter { color, density, preserve_luminosity } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xec, 0x8a, 0x00, 0xff)));
|
||||
visitor.parameter("density", density, 25.);
|
||||
visitor.parameter("preserve_luminosity", preserve_luminosity, true);
|
||||
}
|
||||
Self::ColorLookup { lut_file } => visitor.parameter("lut_file", lut_file, Resource::default()),
|
||||
Self::ColorOverlay { color, blend_mode, opacity } => {
|
||||
// Rides the row as the paint of the Paint Overlay node, which stamps it
|
||||
let mut paint = Graphic::from(*color);
|
||||
visitor.parameter("paint", &mut paint, Graphic::from(Color::BLACK));
|
||||
if let Graphic::Color(paint) = paint {
|
||||
*color = *paint.element();
|
||||
}
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +340,7 @@ pub enum RelativeAbsolute {
|
||||
}
|
||||
|
||||
/// One channel's Levels record: percentage input and output points and the midtones gamma.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct LevelsRecord {
|
||||
pub shadows: f64,
|
||||
pub midtones: f64,
|
||||
@@ -172,7 +350,7 @@ pub struct LevelsRecord {
|
||||
}
|
||||
|
||||
/// The composite record that the three color channels pass through after their own, and the alpha record that stands apart.
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct LevelsSettings {
|
||||
pub composite: LevelsRecord,
|
||||
pub red: LevelsRecord,
|
||||
@@ -182,7 +360,7 @@ pub struct LevelsSettings {
|
||||
}
|
||||
|
||||
/// The composite curve that the three color channels pass through after their own, and the alpha curve that stands apart.
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct CurvesSettings {
|
||||
pub composite: TransferCurve,
|
||||
pub red: TransferCurve,
|
||||
@@ -192,7 +370,7 @@ pub struct CurvesSettings {
|
||||
}
|
||||
|
||||
/// The percentage each hue contributes to the gray, and the color tinting it when `use_tint` is set.
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct BlackAndWhiteSettings {
|
||||
pub use_tint: bool,
|
||||
pub tint: Color,
|
||||
@@ -205,7 +383,7 @@ pub struct BlackAndWhiteSettings {
|
||||
}
|
||||
|
||||
/// One set of Hue/Saturation sliders: a hue in degrees and saturation and lightness percentages.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueSaturationSliders {
|
||||
pub hue: f64,
|
||||
pub saturation: f64,
|
||||
@@ -213,7 +391,7 @@ pub struct HueSaturationSliders {
|
||||
}
|
||||
|
||||
/// The sliders for one range of hues, which apply fully from the range start to its end, fading out at the falloff ends. Edges are in degrees.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueRangeSettings {
|
||||
pub sliders: HueSaturationSliders,
|
||||
pub falloff_start: f64,
|
||||
@@ -223,7 +401,7 @@ pub struct HueRangeSettings {
|
||||
}
|
||||
|
||||
/// The master sliders shift every color, each hue range adds its own, and colorizing replaces them all with an absolute hue and saturation.
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct HueSaturationSettings {
|
||||
pub master: HueSaturationSliders,
|
||||
pub colorize: bool,
|
||||
@@ -237,7 +415,7 @@ pub struct HueSaturationSettings {
|
||||
}
|
||||
|
||||
/// The percentages of each source channel, plus a constant, that sum to one output channel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelMixerRow {
|
||||
pub red: f64,
|
||||
pub green: f64,
|
||||
@@ -246,7 +424,7 @@ pub struct ChannelMixerRow {
|
||||
}
|
||||
|
||||
/// A row for each output channel, or for the single gray channel when monochrome.
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelMixerSettings {
|
||||
pub monochrome: bool,
|
||||
pub monochrome_mix: ChannelMixerRow,
|
||||
@@ -265,7 +443,7 @@ pub struct SelectiveColorInks {
|
||||
}
|
||||
|
||||
/// The ink offsets of each group of colors, and whether they are relative to the inks already present.
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct SelectiveColorSettings {
|
||||
pub mode: RelativeAbsolute,
|
||||
pub reds: SelectiveColorInks,
|
||||
@@ -280,17 +458,76 @@ pub struct SelectiveColorSettings {
|
||||
}
|
||||
|
||||
/// Percentage shifts along the three opponent color axes for one tonal range.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ColorBalanceShifts {
|
||||
pub cyan_red: f64,
|
||||
pub magenta_green: f64,
|
||||
pub yellow_blue: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ColorBalanceSettings {
|
||||
pub shadows: ColorBalanceShifts,
|
||||
pub midtones: ColorBalanceShifts,
|
||||
pub highlights: ColorBalanceShifts,
|
||||
pub preserve_luminosity: bool,
|
||||
}
|
||||
|
||||
/// The attribute key of a parameter in one of a node's groups of parameters, which the node names with the group's prefix.
|
||||
fn grouped_key(group: &str, parameter: &str) -> String {
|
||||
if group.is_empty() { parameter.to_string() } else { format!("{group}_{parameter}") }
|
||||
}
|
||||
|
||||
impl LevelsRecord {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
||||
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
||||
visitor.parameter(&grouped_key(group, "highlights"), &mut self.highlights, 100.);
|
||||
visitor.parameter(&grouped_key(group, "output_minimums"), &mut self.output_minimums, 0.);
|
||||
visitor.parameter(&grouped_key(group, "output_maximums"), &mut self.output_maximums, 100.);
|
||||
}
|
||||
}
|
||||
|
||||
impl HueSaturationSliders {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [hue, saturation, lightness]: [f64; 3]) {
|
||||
visitor.parameter(&grouped_key(group, "hue"), &mut self.hue, hue);
|
||||
visitor.parameter(&grouped_key(group, "saturation"), &mut self.saturation, saturation);
|
||||
visitor.parameter(&grouped_key(group, "lightness"), &mut self.lightness, lightness);
|
||||
}
|
||||
}
|
||||
|
||||
impl HueRangeSettings {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [falloff_start, range_start, range_end, falloff_end]: [f64; 4]) {
|
||||
self.sliders.visit_parameters(visitor, group, [0.; 3]);
|
||||
visitor.parameter(&grouped_key(group, "falloff_start"), &mut self.falloff_start, falloff_start);
|
||||
visitor.parameter(&grouped_key(group, "range_start"), &mut self.range_start, range_start);
|
||||
visitor.parameter(&grouped_key(group, "range_end"), &mut self.range_end, range_end);
|
||||
visitor.parameter(&grouped_key(group, "falloff_end"), &mut self.falloff_end, falloff_end);
|
||||
}
|
||||
}
|
||||
|
||||
impl ChannelMixerRow {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [red, green, blue, constant]: [f64; 4]) {
|
||||
visitor.parameter(&grouped_key(group, "red"), &mut self.red, red);
|
||||
visitor.parameter(&grouped_key(group, "green"), &mut self.green, green);
|
||||
visitor.parameter(&grouped_key(group, "blue"), &mut self.blue, blue);
|
||||
visitor.parameter(&grouped_key(group, "constant"), &mut self.constant, constant);
|
||||
}
|
||||
}
|
||||
|
||||
impl SelectiveColorInks {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "cyan"), &mut self.cyan, 0.);
|
||||
visitor.parameter(&grouped_key(group, "magenta"), &mut self.magenta, 0.);
|
||||
visitor.parameter(&grouped_key(group, "yellow"), &mut self.yellow, 0.);
|
||||
visitor.parameter(&grouped_key(group, "black"), &mut self.black, 0.);
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorBalanceShifts {
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
visitor.parameter(&grouped_key(group, "cyan_red"), &mut self.cyan_red, 0.);
|
||||
visitor.parameter(&grouped_key(group, "magenta_green"), &mut self.magenta_green, 0.);
|
||||
visitor.parameter(&grouped_key(group, "yellow_blue"), &mut self.yellow_blue, 0.);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,684 @@
|
||||
//! An item's effects: an ordered list of image operations on the pixels the item renders to, stored in the `ATTR_EFFECTS` attribute.
|
||||
//! Each row is an [`EffectKind`] whose parameters ride its item as attributes, read as their defaults when absent.
|
||||
//! Each renderer decodes the rows into [`EffectOperation`]s and carries them out its own way, at the resolution of each render.
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
use std::fmt::Debug;
|
||||
use vector_types::vector::style::StrokeAlign;
|
||||
|
||||
/// The image operation an [`Effect`] carries out.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash)]
|
||||
pub enum EffectKind {
|
||||
/// Softens the content by blurring it.
|
||||
#[default]
|
||||
Blur,
|
||||
/// Casts the content's silhouette as a soft shadow beneath it.
|
||||
DropShadow,
|
||||
/// Casts a soft shadow inward from the content's edges, as if it were cut out of the surface.
|
||||
InnerShadow,
|
||||
/// Surrounds the content with a soft glow of its silhouette.
|
||||
OuterGlow,
|
||||
/// Glows inward from the content's edges, or outward from its center.
|
||||
InnerGlow,
|
||||
/// Shades the content's interior with soft bands from its silhouette cast two ways.
|
||||
Satin,
|
||||
/// Draws a band of color along the content's silhouette.
|
||||
Outline,
|
||||
/// Lights the content as if raised from the surface or pressed into it, with highlights and shadows along its edges.
|
||||
BevelAndEmboss,
|
||||
/// Paints over the content within its silhouette, mixing with its colors by a blend mode. A solid color paint is the color overlay adjustment.
|
||||
PaintOverlay,
|
||||
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
MakeOpaque,
|
||||
BrightnessContrast,
|
||||
Levels,
|
||||
Curves,
|
||||
BlackAndWhite,
|
||||
HueSaturation,
|
||||
Invert,
|
||||
Threshold,
|
||||
GradientMap,
|
||||
Vibrance,
|
||||
ChannelMixer,
|
||||
SelectiveColor,
|
||||
Posterize,
|
||||
Exposure,
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Blur => "Blur",
|
||||
Self::DropShadow => "Drop Shadow",
|
||||
Self::InnerShadow => "Inner Shadow",
|
||||
Self::OuterGlow => "Outer Glow",
|
||||
Self::InnerGlow => "Inner Glow",
|
||||
Self::Satin => "Satin",
|
||||
Self::Outline => "Outline",
|
||||
Self::BevelAndEmboss => "Bevel & Emboss",
|
||||
Self::PaintOverlay => "Paint Overlay",
|
||||
Self::Desaturate => "Desaturate",
|
||||
Self::GammaCorrection => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
Self::BrightnessContrast => "Brightness/Contrast",
|
||||
Self::Levels => "Levels",
|
||||
Self::Curves => "Curves",
|
||||
Self::BlackAndWhite => "Black & White",
|
||||
Self::HueSaturation => "Hue/Saturation",
|
||||
Self::Invert => "Invert",
|
||||
Self::Threshold => "Threshold",
|
||||
Self::GradientMap => "Gradient Map",
|
||||
Self::Vibrance => "Vibrance",
|
||||
Self::ChannelMixer => "Channel Mixer",
|
||||
Self::SelectiveColor => "Selective Color",
|
||||
Self::Posterize => "Posterize",
|
||||
Self::Exposure => "Exposure",
|
||||
Self::ColorBalance => "Color Balance",
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Where an inner glow starts from.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum GlowSource {
|
||||
/// Glows inward from the edges.
|
||||
#[default]
|
||||
Edge,
|
||||
/// Glows outward from the center.
|
||||
Center,
|
||||
}
|
||||
|
||||
/// Which slopes a bevel shapes from the content's edges.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum BevelStyle {
|
||||
/// Slopes up from the edges into the content.
|
||||
#[default]
|
||||
InnerBevel,
|
||||
/// Slopes down from the edges away from the content.
|
||||
OuterBevel,
|
||||
/// Slopes across the edges, half inside the content and half outside.
|
||||
Emboss,
|
||||
/// Slopes away from the edges both ways, as if pressed into the surface along them.
|
||||
PillowEmboss,
|
||||
}
|
||||
|
||||
/// Whether a bevel rises from the surface or sinks into it.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum BevelDirection {
|
||||
/// Raised from the surface.
|
||||
#[default]
|
||||
Up,
|
||||
/// Pressed into the surface.
|
||||
Down,
|
||||
}
|
||||
|
||||
/// The deviation of the blur that rounds a bevel's slopes of `size`, in the same units.
|
||||
pub fn bevel_smoothing(size: f64) -> f64 {
|
||||
size.max(0.) / 4.
|
||||
}
|
||||
|
||||
/// The unit vector toward a bevel's light from its `angle` and `altitude` in degrees, with `lengths_to_target` mapping document directions into the y-down space it's lit in.
|
||||
pub fn bevel_light(angle: f64, altitude: f64, lengths_to_target: DMat2) -> DVec3 {
|
||||
let (angle, altitude) = (angle.to_radians(), altitude.clamp(0., 90.).to_radians());
|
||||
let across = (lengths_to_target * DVec2::new(angle.cos(), -angle.sin())).try_normalize().unwrap_or(DVec2::X);
|
||||
(across * altitude.cos()).extend(altitude.sin())
|
||||
}
|
||||
|
||||
/// An overlay's paint with its unit square fitted to `content_bounds`, the content's extent in the space it's drawn in, if it's a gradient or image without its own placement.
|
||||
pub fn fitted_paint(paint: &Graphic, content_bounds: [DVec2; 2]) -> Option<Graphic> {
|
||||
let unplaced = match paint {
|
||||
Graphic::Gradient(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterCPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
Graphic::RasterGPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
|
||||
_ => false,
|
||||
};
|
||||
if !unplaced {
|
||||
return None;
|
||||
}
|
||||
|
||||
let fit = DAffine2::from_translation(content_bounds[0]) * DAffine2::from_scale(content_bounds[1] - content_bounds[0]);
|
||||
let mut paint = paint.clone();
|
||||
match &mut paint {
|
||||
Graphic::Gradient(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterCPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
Graphic::RasterGPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
|
||||
_ => {}
|
||||
}
|
||||
Some(paint)
|
||||
}
|
||||
|
||||
/// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item.
|
||||
/// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored.
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct Effect(pub Item<EffectKind>);
|
||||
|
||||
impl Effect {
|
||||
/// Creates an effect row carrying out the given operation, stamping only the parameters that differ from their implicit defaults.
|
||||
pub fn new(operation: &EffectOperation) -> Self {
|
||||
let mut item = Item::new_from_element(operation.kind());
|
||||
operation.clone().visit_parameters(&mut WriteParameters(&mut item));
|
||||
Self(item)
|
||||
}
|
||||
|
||||
/// This effect's kind.
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
*self.0.element()
|
||||
}
|
||||
|
||||
/// Decodes the parameters into an [`EffectOperation`], falling back to the default for any absent attribute.
|
||||
pub fn operation(&self) -> EffectOperation {
|
||||
let mut operation = EffectOperation::placeholder(self.kind());
|
||||
operation.visit_parameters(&mut ReadParameters(&|key| self.0.attributes().get_any(key)));
|
||||
|
||||
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
|
||||
match operation {
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: Graphic::Color(color),
|
||||
blend_mode,
|
||||
opacity,
|
||||
} => EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: *color.element(),
|
||||
blend_mode,
|
||||
opacity,
|
||||
}),
|
||||
operation => operation,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An item's ordered list of effects. A blur acts on the result of those before it, while shadows and glows are cast from the content and stack in order beneath it (or within it, for an inner shadow).
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct Effects(pub List<Effect>);
|
||||
|
||||
impl Effects {
|
||||
/// Creates the list of rows carrying out the given operations in order.
|
||||
pub fn from_operations(operations: impl IntoIterator<Item = EffectOperation>) -> Self {
|
||||
let mut effects = Self::default();
|
||||
for operation in operations {
|
||||
effects.0.push(Item::new_from_element(Effect::new(&operation)));
|
||||
}
|
||||
effects
|
||||
}
|
||||
|
||||
/// The effects in the order they're carried out.
|
||||
pub fn effects(&self) -> impl Iterator<Item = &Effect> {
|
||||
self.0.iter_element_values()
|
||||
}
|
||||
|
||||
/// The effects after the first `count`.
|
||||
pub fn after(&self, count: usize) -> Self {
|
||||
let mut remaining = Self::default();
|
||||
for effect in self.effects().skip(count) {
|
||||
remaining.0.push(Item::new_from_element(effect.clone()));
|
||||
}
|
||||
remaining
|
||||
}
|
||||
|
||||
/// The effects decoded into the operations renderers carry out, in order.
|
||||
pub fn operations(&self) -> impl Iterator<Item = EffectOperation> + '_ {
|
||||
self.effects().map(Effect::operation)
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint, in document pixels.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.reach()).sum()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// How far an outline of `weight` reaches outside the silhouette's edge and inside it, by where it's aligned.
|
||||
pub fn outline_extents(weight: f64, align: StrokeAlign) -> (f64, f64) {
|
||||
match align {
|
||||
StrokeAlign::Outside => (weight, 0.),
|
||||
StrokeAlign::Inside => (0., weight),
|
||||
StrokeAlign::Center => (weight / 2., weight / 2.),
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends an effect to the item's list, after those already applied to it.
|
||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS).0.push(Item::new_from_element(effect));
|
||||
}
|
||||
|
||||
/// An effect's parameters decoded from its row, the form that renderers carry it out from. Lengths are in document pixels.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EffectOperation {
|
||||
Blur {
|
||||
/// The standard deviation of the Gaussian, or the half width of the box.
|
||||
radius: f64,
|
||||
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
|
||||
box_blur: bool,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
DropShadow {
|
||||
color: Color,
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
InnerShadow {
|
||||
color: Color,
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
OuterGlow {
|
||||
color: Color,
|
||||
blur: f64,
|
||||
spread: f64,
|
||||
},
|
||||
InnerGlow {
|
||||
color: Color,
|
||||
blur: f64,
|
||||
/// How far the glow grows into the content before it softens.
|
||||
choke: f64,
|
||||
source: GlowSource,
|
||||
},
|
||||
Satin {
|
||||
color: Color,
|
||||
/// How far each of the two casts of the silhouette is moved, in opposite directions.
|
||||
offset: DVec2,
|
||||
blur: f64,
|
||||
invert: bool,
|
||||
},
|
||||
Outline {
|
||||
color: Color,
|
||||
weight: f64,
|
||||
align: StrokeAlign,
|
||||
},
|
||||
BevelAndEmboss {
|
||||
style: BevelStyle,
|
||||
/// How steep the slopes are, as a percentage.
|
||||
depth: f64,
|
||||
direction: BevelDirection,
|
||||
/// How wide the slopes are.
|
||||
size: f64,
|
||||
/// How much the highlights and shadows are blurred.
|
||||
soften: f64,
|
||||
/// The direction the light comes from, in degrees counterclockwise from the right.
|
||||
angle: f64,
|
||||
/// How high the light is above the surface, in degrees from flat to straight overhead.
|
||||
altitude: f64,
|
||||
highlight_color: Color,
|
||||
shadow_color: Color,
|
||||
},
|
||||
/// Paints over the content with a paint other than a solid color, since a solid one decodes into the color overlay adjustment instead.
|
||||
PaintOverlay {
|
||||
/// Placed in the space the content's item is, or fitted to the content's bounds if it's a gradient or image without its own placement.
|
||||
paint: Graphic,
|
||||
blend_mode: BlendMode,
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
Adjustment(Adjustment),
|
||||
}
|
||||
|
||||
impl EffectOperation {
|
||||
/// The operation an effect of this kind carries out when its row gives none of its parameters, matching the defaults of the node that stamps it.
|
||||
pub fn default_for(kind: EffectKind) -> Self {
|
||||
Effect(Item::new_from_element(kind)).operation()
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
match self {
|
||||
Self::Blur { .. } => EffectKind::Blur,
|
||||
Self::DropShadow { .. } => EffectKind::DropShadow,
|
||||
Self::InnerShadow { .. } => EffectKind::InnerShadow,
|
||||
Self::OuterGlow { .. } => EffectKind::OuterGlow,
|
||||
Self::InnerGlow { .. } => EffectKind::InnerGlow,
|
||||
Self::Satin { .. } => EffectKind::Satin,
|
||||
Self::Outline { .. } => EffectKind::Outline,
|
||||
Self::BevelAndEmboss { .. } => EffectKind::BevelAndEmboss,
|
||||
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Adjustment(adjustment) => adjustment.kind(),
|
||||
}
|
||||
}
|
||||
|
||||
/// How far past the content this operation can paint, or reads from, in document pixels.
|
||||
pub fn reach(&self) -> f64 {
|
||||
// A Gaussian is negligible past three standard deviations
|
||||
match self {
|
||||
Self::Blur { radius, .. } => 3. * radius.max(0.),
|
||||
Self::DropShadow { offset, blur, spread, .. } => offset.length() + spread.max(0.) + 3. * blur.max(0.),
|
||||
Self::InnerShadow { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
|
||||
Self::OuterGlow { blur, spread, .. } => spread.max(0.) + 3. * blur.max(0.),
|
||||
Self::InnerGlow { blur, choke, .. } => choke.max(0.) + 3. * blur.max(0.),
|
||||
Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
|
||||
Self::Outline { weight, .. } => weight.max(0.),
|
||||
Self::BevelAndEmboss { size, soften, .. } => size.max(0.) + 3. * (soften.max(0.) + bevel_smoothing(*size)),
|
||||
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
/// An operation of this kind with arbitrary parameters, for a visitor to fill in.
|
||||
fn placeholder(kind: EffectKind) -> Self {
|
||||
match kind {
|
||||
EffectKind::Blur => Self::Blur {
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
},
|
||||
EffectKind::DropShadow => Self::DropShadow {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::InnerShadow => Self::InnerShadow {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::OuterGlow => Self::OuterGlow {
|
||||
color: Color::TRANSPARENT,
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
},
|
||||
EffectKind::InnerGlow => Self::InnerGlow {
|
||||
color: Color::TRANSPARENT,
|
||||
blur: 0.,
|
||||
choke: 0.,
|
||||
source: GlowSource::default(),
|
||||
},
|
||||
EffectKind::Satin => Self::Satin {
|
||||
color: Color::TRANSPARENT,
|
||||
offset: DVec2::ZERO,
|
||||
blur: 0.,
|
||||
invert: false,
|
||||
},
|
||||
EffectKind::Outline => Self::Outline {
|
||||
color: Color::TRANSPARENT,
|
||||
weight: 0.,
|
||||
align: StrokeAlign::default(),
|
||||
},
|
||||
EffectKind::BevelAndEmboss => Self::BevelAndEmboss {
|
||||
style: BevelStyle::default(),
|
||||
depth: 0.,
|
||||
direction: BevelDirection::default(),
|
||||
size: 0.,
|
||||
soften: 0.,
|
||||
angle: 0.,
|
||||
altitude: 0.,
|
||||
highlight_color: Color::TRANSPARENT,
|
||||
shadow_color: Color::TRANSPARENT,
|
||||
},
|
||||
EffectKind::PaintOverlay => Self::PaintOverlay {
|
||||
paint: Graphic::default(),
|
||||
blend_mode: BlendMode::default(),
|
||||
opacity: 0.,
|
||||
},
|
||||
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
|
||||
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
|
||||
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque),
|
||||
EffectKind::BrightnessContrast => Self::Adjustment(Adjustment::BrightnessContrast {
|
||||
brightness: 0.,
|
||||
contrast: 0.,
|
||||
use_classic: false,
|
||||
classic_pivot: 0.,
|
||||
}),
|
||||
EffectKind::Levels => Self::Adjustment(Adjustment::Levels(Default::default())),
|
||||
EffectKind::Curves => Self::Adjustment(Adjustment::Curves(Default::default())),
|
||||
EffectKind::BlackAndWhite => Self::Adjustment(Adjustment::BlackAndWhite(Default::default())),
|
||||
EffectKind::HueSaturation => Self::Adjustment(Adjustment::HueSaturation(Default::default())),
|
||||
EffectKind::Invert => Self::Adjustment(Adjustment::Invert),
|
||||
EffectKind::Threshold => Self::Adjustment(Adjustment::Threshold { min_luminance: 0., max_luminance: 0. }),
|
||||
EffectKind::GradientMap => Self::Adjustment(Adjustment::GradientMap {
|
||||
gradient: Default::default(),
|
||||
reverse: false,
|
||||
}),
|
||||
EffectKind::Vibrance => Self::Adjustment(Adjustment::Vibrance { vibrance: 0., saturation: 0. }),
|
||||
EffectKind::ChannelMixer => Self::Adjustment(Adjustment::ChannelMixer(Default::default())),
|
||||
EffectKind::SelectiveColor => Self::Adjustment(Adjustment::SelectiveColor(Default::default())),
|
||||
EffectKind::Posterize => Self::Adjustment(Adjustment::Posterize { levels: 0 }),
|
||||
EffectKind::Exposure => Self::Adjustment(Adjustment::Exposure {
|
||||
exposure: 0.,
|
||||
offset: 0.,
|
||||
gamma_correction: 0.,
|
||||
}),
|
||||
EffectKind::ColorBalance => Self::Adjustment(Adjustment::ColorBalance(Default::default())),
|
||||
EffectKind::PhotoFilter => Self::Adjustment(Adjustment::PhotoFilter {
|
||||
color: Color::TRANSPARENT,
|
||||
density: 0.,
|
||||
preserve_luminosity: false,
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Visits each parameter with the attribute it rides and its implicit default, the one listing that writing and reading rows share.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
match self {
|
||||
Self::Blur { radius, box_blur, gamma } => {
|
||||
visitor.parameter("radius", radius, 0.);
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::DropShadow { color, offset, blur, spread } | Self::InnerShadow { color, offset, blur, spread } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
|
||||
visitor.parameter("offset", offset, DVec2::splat(4.));
|
||||
visitor.parameter("blur", blur, 4.);
|
||||
visitor.parameter("spread", spread, 0.);
|
||||
}
|
||||
Self::OuterGlow { color, blur, spread } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
|
||||
visitor.parameter("blur", blur, 8.);
|
||||
visitor.parameter("spread", spread, 0.);
|
||||
}
|
||||
Self::InnerGlow { color, blur, choke, source } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
|
||||
visitor.parameter("blur", blur, 8.);
|
||||
visitor.parameter("choke", choke, 0.);
|
||||
visitor.parameter("source", source, GlowSource::default());
|
||||
}
|
||||
Self::Satin { color, offset, blur, invert } => {
|
||||
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
|
||||
visitor.parameter("offset", offset, DVec2::new(10., 4.));
|
||||
visitor.parameter("blur", blur, 14.);
|
||||
visitor.parameter("invert", invert, true);
|
||||
}
|
||||
Self::Outline { color, weight, align } => {
|
||||
visitor.parameter("color", color, Color::BLACK);
|
||||
visitor.parameter("weight", weight, 3.);
|
||||
visitor.parameter("align", align, StrokeAlign::Outside);
|
||||
}
|
||||
Self::BevelAndEmboss {
|
||||
style,
|
||||
depth,
|
||||
direction,
|
||||
size,
|
||||
soften,
|
||||
angle,
|
||||
altitude,
|
||||
highlight_color,
|
||||
shadow_color,
|
||||
} => {
|
||||
visitor.parameter("style", style, BevelStyle::default());
|
||||
visitor.parameter("depth", depth, 100.);
|
||||
visitor.parameter("direction", direction, BevelDirection::default());
|
||||
visitor.parameter("size", size, 5.);
|
||||
visitor.parameter("soften", soften, 0.);
|
||||
visitor.parameter("angle", angle, 120.);
|
||||
visitor.parameter("altitude", altitude, 30.);
|
||||
visitor.parameter("highlight_color", highlight_color, Color::from(SRGBA8::new(0xff, 0xff, 0xff, 0xbf)));
|
||||
visitor.parameter("shadow_color", shadow_color, Color::from(SRGBA8::new(0, 0, 0, 0xbf)));
|
||||
}
|
||||
Self::PaintOverlay { paint, blend_mode, opacity } => {
|
||||
visitor.parameter("paint", paint, Graphic::from(Color::BLACK));
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
|
||||
visitor.parameter("opacity", opacity, 100.);
|
||||
}
|
||||
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vector_types::{Gradient, GradientStop};
|
||||
|
||||
#[test]
|
||||
fn rows_round_trip_their_operations_eliding_defaults() {
|
||||
let operations = [
|
||||
EffectOperation::Blur {
|
||||
radius: 6.,
|
||||
box_blur: true,
|
||||
gamma: false,
|
||||
},
|
||||
EffectOperation::default_for(EffectKind::DropShadow),
|
||||
EffectOperation::InnerShadow {
|
||||
color: Color::RED,
|
||||
offset: DVec2::new(-2., 3.),
|
||||
blur: 1.,
|
||||
spread: 5.,
|
||||
},
|
||||
EffectOperation::OuterGlow {
|
||||
color: Color::BLUE,
|
||||
blur: 8.,
|
||||
spread: 2.,
|
||||
},
|
||||
EffectOperation::InnerGlow {
|
||||
color: Color::GREEN,
|
||||
blur: 3.,
|
||||
choke: 1.,
|
||||
source: GlowSource::Center,
|
||||
},
|
||||
EffectOperation::Satin {
|
||||
color: Color::BLACK,
|
||||
offset: DVec2::new(5., -6.),
|
||||
blur: 2.,
|
||||
invert: false,
|
||||
},
|
||||
EffectOperation::Outline {
|
||||
color: Color::RED,
|
||||
weight: 7.,
|
||||
align: StrokeAlign::Center,
|
||||
},
|
||||
EffectOperation::BevelAndEmboss {
|
||||
style: BevelStyle::PillowEmboss,
|
||||
depth: 250.,
|
||||
direction: BevelDirection::Down,
|
||||
size: 12.,
|
||||
soften: 2.,
|
||||
angle: -45.,
|
||||
altitude: 60.,
|
||||
highlight_color: Color::YELLOW,
|
||||
shadow_color: Color::BLUE,
|
||||
},
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: Graphic::from(Gradient::new([0., 1.].map(|position| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: Color::from_rgbaf32_unchecked(position as f32, 0., 1., 1.),
|
||||
}))),
|
||||
blend_mode: BlendMode::Multiply,
|
||||
opacity: 60.,
|
||||
},
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::GREEN,
|
||||
blend_mode: BlendMode::Screen,
|
||||
opacity: 100.,
|
||||
}),
|
||||
];
|
||||
|
||||
for operation in operations {
|
||||
assert_eq!(Effect::new(&operation).operation(), operation);
|
||||
}
|
||||
|
||||
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
|
||||
let solid = EffectOperation::PaintOverlay {
|
||||
paint: Graphic::from(Color::RED),
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
};
|
||||
let solid_row = Effect::new(&solid);
|
||||
assert_eq!(solid_row.kind(), EffectKind::PaintOverlay);
|
||||
assert_eq!(
|
||||
solid_row.operation(),
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 50.,
|
||||
})
|
||||
);
|
||||
|
||||
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
|
||||
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() {
|
||||
use EffectKind::*;
|
||||
let kinds = [
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
MakeOpaque,
|
||||
BrightnessContrast,
|
||||
Levels,
|
||||
Curves,
|
||||
BlackAndWhite,
|
||||
HueSaturation,
|
||||
Invert,
|
||||
Threshold,
|
||||
GradientMap,
|
||||
Vibrance,
|
||||
ChannelMixer,
|
||||
SelectiveColor,
|
||||
Posterize,
|
||||
Exposure,
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
let operation = EffectOperation::default_for(kind);
|
||||
assert_eq!(operation.kind(), kind);
|
||||
assert_eq!(Effect::new(&operation).0.attributes().iter_any().count(), 0, "{kind} stamps no defaults");
|
||||
}
|
||||
|
||||
// A parameter in one of the node's groups rides the attribute named with the group's prefix
|
||||
let mut levels = EffectOperation::default_for(Levels);
|
||||
if let EffectOperation::Adjustment(Adjustment::Levels(settings)) = &mut levels {
|
||||
settings.blue.midtones = 1.5;
|
||||
}
|
||||
let row = Effect::new(&levels);
|
||||
assert_eq!(row.0.attribute::<f64>("blue_midtones"), Some(&1.5));
|
||||
assert_eq!(row.operation(), levels);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DAffine2;
|
||||
use std::any::Any;
|
||||
|
||||
/// Style of noise pattern.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -86,7 +91,7 @@ pub enum DomainWarpType {
|
||||
}
|
||||
|
||||
/// The settings of a noise pattern, with lengths measured in the document units of the space it's sampled in.
|
||||
#[derive(Debug, Clone, PartialEq, CacheHash)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, CacheHash)]
|
||||
pub struct NoiseSettings {
|
||||
pub seed: i64,
|
||||
pub scale: f64,
|
||||
@@ -111,3 +116,82 @@ pub enum GeneratorPattern {
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
/// A procedural pattern filling the whole plane, which renderers draw at whatever resolution they need across whatever part they see.
|
||||
/// The item's transform places the pattern's own space, and a noise pattern's settings ride the item as attributes named after the Noise Pattern node's parameters.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny)]
|
||||
pub enum Generator {
|
||||
#[default]
|
||||
Noise,
|
||||
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
|
||||
Mandelbrot,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Generator {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Noise => "Noise",
|
||||
Self::Mandelbrot => "Mandelbrot",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl BoundingBox for Generator {
|
||||
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
|
||||
match transform.matrix2.determinant() == 0. {
|
||||
true => RenderBoundingBox::None,
|
||||
false => RenderBoundingBox::Infinite,
|
||||
}
|
||||
}
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
self.bounding_box(transform, include_stroke)
|
||||
}
|
||||
}
|
||||
|
||||
impl NoiseSettings {
|
||||
/// Stamps every setting onto the generator's item, whatever its value, so which attributes the item carries doesn't depend on them.
|
||||
pub fn stamp(&self, item: &mut Item<Generator>) {
|
||||
self.clone().visit_parameters(&mut StampParameters(item));
|
||||
}
|
||||
|
||||
/// Visits each setting with the attribute it rides, named after the Noise Pattern node's parameter, and its default, which is the node's.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
visitor.parameter("seed", &mut self.seed, 0);
|
||||
visitor.parameter("scale", &mut self.scale, 10.);
|
||||
visitor.parameter("noise_type", &mut self.noise_type, NoiseType::default());
|
||||
visitor.parameter("domain_warp_type", &mut self.domain_warp_type, DomainWarpType::default());
|
||||
visitor.parameter("domain_warp_amplitude", &mut self.domain_warp_amplitude, 100.);
|
||||
visitor.parameter("fractal_type", &mut self.fractal_type, FractalType::default());
|
||||
visitor.parameter("fractal_octaves", &mut self.fractal_octaves, 3);
|
||||
visitor.parameter("fractal_lacunarity", &mut self.fractal_lacunarity, 2.);
|
||||
visitor.parameter("fractal_gain", &mut self.fractal_gain, 0.5);
|
||||
visitor.parameter("fractal_weighted_strength", &mut self.fractal_weighted_strength, 0.);
|
||||
visitor.parameter("fractal_ping_pong_strength", &mut self.fractal_ping_pong_strength, 2.);
|
||||
visitor.parameter("cellular_distance_function", &mut self.cellular_distance_function, CellularDistanceFunction::default());
|
||||
visitor.parameter("cellular_return_type", &mut self.cellular_return_type, CellularReturnType::default());
|
||||
visitor.parameter("cellular_jitter", &mut self.cellular_jitter, 1.);
|
||||
}
|
||||
}
|
||||
|
||||
impl GeneratorPattern {
|
||||
/// The pattern a generator draws, reading a noise pattern's settings with `attribute`, which looks one of the item's attributes up by key.
|
||||
/// Each setting the item lacks takes its default.
|
||||
pub fn decode<'a>(generator: Generator, attribute: &'a dyn Fn(&str) -> Option<&'a dyn Any>) -> Self {
|
||||
match generator {
|
||||
Generator::Noise => {
|
||||
let mut settings = NoiseSettings::default();
|
||||
settings.visit_parameters(&mut ReadParameters(attribute));
|
||||
Self::Noise(settings)
|
||||
}
|
||||
Generator::Mandelbrot => Self::Mandelbrot,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern a generator item draws.
|
||||
pub fn of_item(item: &Item<Generator>) -> Self {
|
||||
Self::decode(*item.element(), &|key| item.attributes().get_any(key))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::appearance::{Appearance, Cover, Coverage};
|
||||
use crate::generator::Generator;
|
||||
use brush_types::Stroke;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
@@ -26,6 +27,7 @@ pub enum Graphic {
|
||||
RasterGPU(Item<Raster<GPU>>),
|
||||
Color(Item<Color>),
|
||||
Gradient(Item<Gradient>),
|
||||
Generator(Item<Generator>),
|
||||
Text(Item<String>),
|
||||
NoneList(List<none::None>),
|
||||
GraphicList(List<Graphic>),
|
||||
@@ -34,6 +36,7 @@ pub enum Graphic {
|
||||
RasterGPUList(List<Raster<GPU>>),
|
||||
ColorList(List<Color>),
|
||||
GradientList(List<Gradient>),
|
||||
GeneratorList(List<Generator>),
|
||||
TextList(List<String>),
|
||||
StrokeList(List<Stroke>),
|
||||
}
|
||||
@@ -137,6 +140,23 @@ impl From<List<Gradient>> for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
// Generator
|
||||
impl From<Generator> for Graphic {
|
||||
fn from(generator: Generator) -> Self {
|
||||
Graphic::Generator(Item::new_from_element(generator))
|
||||
}
|
||||
}
|
||||
impl From<Item<Generator>> for Graphic {
|
||||
fn from(generator: Item<Generator>) -> Self {
|
||||
Graphic::Generator(generator)
|
||||
}
|
||||
}
|
||||
impl From<List<Generator>> for Graphic {
|
||||
fn from(generator: List<Generator>) -> Self {
|
||||
Graphic::GeneratorList(generator)
|
||||
}
|
||||
}
|
||||
|
||||
// Stroke
|
||||
impl From<Stroke> for Graphic {
|
||||
fn from(stroke: Stroke) -> Self {
|
||||
@@ -312,12 +332,14 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
|
||||
Graphic::RasterCPU(item) => bake_item_transform(item, transform),
|
||||
Graphic::RasterGPU(item) => bake_item_transform(item, transform),
|
||||
Graphic::Gradient(item) => bake_item_transform(item, transform),
|
||||
Graphic::Generator(item) => bake_item_transform(item, transform),
|
||||
Graphic::Text(item) => bake_item_transform(item, transform),
|
||||
Graphic::GraphicList(list) => bake_list_transform(list, transform),
|
||||
Graphic::VectorList(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterCPUList(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterGPUList(list) => bake_list_transform(list, transform),
|
||||
Graphic::GradientList(list) => bake_list_transform(list, transform),
|
||||
Graphic::GeneratorList(list) => bake_list_transform(list, transform),
|
||||
Graphic::TextList(list) => bake_list_transform(list, transform),
|
||||
Graphic::StrokeList(list) => bake_list_transform(list, transform),
|
||||
// A color has no spatial extent, so there is no placement for a transform to move
|
||||
@@ -380,6 +402,16 @@ impl TryFromGraphic for Gradient {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Generator {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
match graphic {
|
||||
Graphic::Generator(item) => Some(List::new_from_item(item)),
|
||||
Graphic::GeneratorList(list) => Some(list),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for String {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
match graphic {
|
||||
@@ -447,6 +479,12 @@ impl IntoGraphicList for List<Gradient> {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Generator> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
List::new_from_element(Graphic::GeneratorList(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Stroke> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
let layer_path: NodeIdPath = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
@@ -560,6 +598,7 @@ impl Graphic {
|
||||
Graphic::RasterGPU(item) => item_clipped(item),
|
||||
Graphic::Color(item) => item_clipped(item),
|
||||
Graphic::Gradient(item) => item_clipped(item),
|
||||
Graphic::Generator(item) => item_clipped(item),
|
||||
Graphic::Text(item) => item_clipped(item),
|
||||
Graphic::NoneList(list) => all_clipped(list),
|
||||
Graphic::VectorList(list) => all_clipped(list),
|
||||
@@ -568,6 +607,7 @@ impl Graphic {
|
||||
Graphic::RasterGPUList(list) => all_clipped(list),
|
||||
Graphic::ColorList(list) => all_clipped(list),
|
||||
Graphic::GradientList(list) => all_clipped(list),
|
||||
Graphic::GeneratorList(list) => all_clipped(list),
|
||||
Graphic::TextList(list) => all_clipped(list),
|
||||
Graphic::StrokeList(list) => all_clipped(list),
|
||||
}
|
||||
@@ -606,6 +646,7 @@ 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
|
||||
@@ -652,9 +693,11 @@ impl Graphic {
|
||||
// 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),
|
||||
Graphic::Generator(item) => item_opacity_is_zero(item),
|
||||
Graphic::Text(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterCPUList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::RasterGPUList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::GeneratorList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::TextList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::StrokeList(list) => every_item_has_zero_opacity(list),
|
||||
}
|
||||
@@ -670,11 +713,12 @@ impl Graphic {
|
||||
match self {
|
||||
// A leaf always holds exactly one element, so only the none-typed content is truly empty
|
||||
Graphic::None(_) | Graphic::NoneList(_) => true,
|
||||
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Text(_) => false,
|
||||
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) | Graphic::Text(_) => false,
|
||||
Graphic::GraphicList(list) => list.is_empty(),
|
||||
Graphic::VectorList(list) => list.is_empty(),
|
||||
Graphic::ColorList(list) => list.is_empty(),
|
||||
Graphic::GradientList(list) => list.is_empty(),
|
||||
Graphic::GeneratorList(list) => list.is_empty(),
|
||||
Graphic::RasterCPUList(list) => list.is_empty(),
|
||||
Graphic::RasterGPUList(list) => list.is_empty(),
|
||||
Graphic::TextList(list) => list.is_empty(),
|
||||
@@ -831,6 +875,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::RasterGPU(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Color(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Generator(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Text(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::VectorList(list) => vector_list_bounding_box(list, transform, include_stroke),
|
||||
Graphic::RasterCPUList(list) => list.bounding_box(transform, include_stroke),
|
||||
@@ -838,6 +883,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::GraphicList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::ColorList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::GradientList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::GeneratorList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::TextList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::StrokeList(list) => list.bounding_box(transform, include_stroke),
|
||||
}
|
||||
@@ -852,6 +898,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::RasterGPU(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Color(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Generator(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Text(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::VectorList(vector) => vector_list_bounding_box(vector, transform, include_stroke),
|
||||
Graphic::RasterCPUList(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
@@ -859,6 +906,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::GraphicList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::ColorList(color) => color.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::GradientList(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::GeneratorList(generator) => generator.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::TextList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::StrokeList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
pub mod adjustment;
|
||||
pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod effects;
|
||||
pub mod generator;
|
||||
pub mod graphic;
|
||||
pub(crate) mod parameters;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
pub use core_types;
|
||||
@@ -13,6 +15,8 @@ pub use vector_types;
|
||||
pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
|
||||
pub use generator::Generator;
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
|
||||
pub mod migrations {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Parameters riding an item as attributes, each read as its default when absent, which one listing per operation both writes and reads.
|
||||
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use std::any::Any;
|
||||
use std::fmt::Debug;
|
||||
|
||||
/// What a value needs to ride an attribute.
|
||||
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
|
||||
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
|
||||
|
||||
/// Handles each parameter of an operation, given the attribute key it rides and its default.
|
||||
pub(crate) trait ParameterVisitor {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
|
||||
}
|
||||
|
||||
/// Stamps each parameter that differs from its default onto an item, for rows whose attributes are part of their value.
|
||||
pub(crate) struct WriteParameters<'a, T>(pub &'a mut Item<T>);
|
||||
|
||||
impl<T> ParameterVisitor for WriteParameters<'_, T> {
|
||||
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, default: U) {
|
||||
if *value != default {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stamps every parameter onto an item, for an item on a wire, whose attributes mustn't come and go with their values.
|
||||
pub(crate) struct StampParameters<'a, T>(pub &'a mut Item<T>);
|
||||
|
||||
impl<T> ParameterVisitor for StampParameters<'_, T> {
|
||||
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, _default: U) {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads each parameter from the attribute that the lookup finds by key, or its default where there's none.
|
||||
pub(crate) struct ReadParameters<'a>(pub &'a dyn Fn(&str) -> Option<&'a dyn Any>);
|
||||
|
||||
impl ParameterVisitor for ReadParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
*value = (self.0)(key).and_then(|value| value.downcast_ref::<T>()).cloned().unwrap_or(default);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Bakes runs of adjustments into the lookup tables the GPU carries them out with, sampling the CPU kernels so the two agree by construction.
|
||||
|
||||
use crate::adjustments::adjust_colors;
|
||||
use core_types::Color;
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
|
||||
/// Entries in a one-dimensional table, enough that interpolating between them strays less than a level from even a steep curve.
|
||||
pub const CURVE_TABLE_SIZE: usize = 4096;
|
||||
|
||||
/// Grid points along each axis of a color cube, enough that interpolating within its tetrahedra stays within a few levels of the smooth kernels.
|
||||
pub const CUBE_SIZE: usize = 65;
|
||||
|
||||
/// Grid points along each axis of a draft color cube, an eighth the work of [`CUBE_SIZE`] for settings changing every frame, at about three times its error.
|
||||
pub const DRAFT_CUBE_SIZE: usize = 33;
|
||||
|
||||
/// One pass of the GPU's adjustment shader, with the tables it looks colors up in. Values are gamma-encoded.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AdjustmentPass {
|
||||
/// The red, green, blue, and alpha channels each through their own curve, sampled at [`CURVE_TABLE_SIZE`] values from 0 to 1.
|
||||
Curves(Vec<[f32; 4]>),
|
||||
/// Colors through a cube of `size` samples along each of red, green, and blue, with red varying fastest and blue slowest.
|
||||
/// Alpha passes through its own curve of [`CURVE_TABLE_SIZE`] samples.
|
||||
Cube { size: usize, colors: Vec<[f32; 3]>, alpha: Vec<f32> },
|
||||
/// Each color replaced by the entry of [`CURVE_TABLE_SIZE`] its luma (the weighted sum of its channels) picks, keeping its alpha.
|
||||
Luma { weights: [f32; 3], colors: Vec<[f32; 3]> },
|
||||
/// Vibrance, whose steep toe near black no table captures, computed directly from its amounts in -1..1 and its saturation scale.
|
||||
Vibrance { vibrance: f32, saturation_scale: f32 },
|
||||
}
|
||||
|
||||
impl AdjustmentPass {
|
||||
/// The passes that carry out `adjustments` in order, merging each run of those a table can capture into one pass, with cubes of `cube_size` along each side.
|
||||
pub fn plan(adjustments: &[Adjustment], cube_size: usize) -> Vec<Self> {
|
||||
let mut passes = Vec::new();
|
||||
let mut run: Vec<&Adjustment> = Vec::new();
|
||||
|
||||
for adjustment in adjustments {
|
||||
let own_pass = match adjustment {
|
||||
Adjustment::Vibrance { vibrance, saturation } => Some(Self::Vibrance {
|
||||
vibrance: (vibrance / 100.) as f32,
|
||||
saturation_scale: (1. + saturation / 100.) as f32,
|
||||
}),
|
||||
// A step in luma, which a table of luma keeps sharp where a cube would blur it
|
||||
Adjustment::Threshold { .. } => Some(Self::Luma {
|
||||
weights: [4915., 9667., 1802.].map(|weight| weight / 16384.),
|
||||
colors: luma_table(adjustment, [4915., 9667., 1802.].map(|weight| weight / 16384.)),
|
||||
}),
|
||||
// A gradient's hard stops are steps too
|
||||
Adjustment::GradientMap { .. } => Some(Self::Luma {
|
||||
weights: [0.3, 0.59, 0.11],
|
||||
colors: luma_table(adjustment, [0.3, 0.59, 0.11]),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
match own_pass {
|
||||
Some(pass) => {
|
||||
passes.extend(Self::from_run(&run, cube_size));
|
||||
run.clear();
|
||||
passes.push(pass);
|
||||
}
|
||||
None => run.push(adjustment),
|
||||
}
|
||||
}
|
||||
passes.extend(Self::from_run(&run, cube_size));
|
||||
|
||||
passes
|
||||
}
|
||||
|
||||
/// Whether any of the passes looks colors up in a cube, the only table whose size varies.
|
||||
pub fn any_cube(passes: &[Self]) -> bool {
|
||||
passes.iter().any(|pass| matches!(pass, Self::Cube { .. }))
|
||||
}
|
||||
|
||||
/// One pass carrying out a run of adjustments in order, as four curves if each acts on the channels separately, or else as a cube.
|
||||
fn from_run(run: &[&Adjustment], cube_size: usize) -> Option<Self> {
|
||||
if run.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let apply_run = |colors: &mut [Color]| run.iter().for_each(|adjustment| adjust_colors(adjustment, colors));
|
||||
|
||||
// The color channels never read alpha, and alpha depends on alpha alone, so one ramp feeds every channel at once
|
||||
let mut ramp: Vec<Color> = (0..CURVE_TABLE_SIZE)
|
||||
.map(|index| {
|
||||
let value = index as f32 / (CURVE_TABLE_SIZE - 1) as f32;
|
||||
Color::from_gamma_srgb_channels(value, value, value, value)
|
||||
})
|
||||
.collect();
|
||||
apply_run(&mut ramp);
|
||||
let ramp: Vec<[f32; 4]> = ramp.iter().map(Color::to_gamma_srgb_channels).collect();
|
||||
|
||||
if run.iter().all(|adjustment| adjustment.is_per_channel()) {
|
||||
return Some(Self::Curves(ramp));
|
||||
}
|
||||
|
||||
let step = |index: usize| index as f32 / (cube_size - 1) as f32;
|
||||
let mut cube = Vec::with_capacity(cube_size.pow(3));
|
||||
for blue in 0..cube_size {
|
||||
for green in 0..cube_size {
|
||||
for red in 0..cube_size {
|
||||
cube.push(Color::from_gamma_srgb_channels(step(red), step(green), step(blue), 1.));
|
||||
}
|
||||
}
|
||||
}
|
||||
apply_run(&mut cube);
|
||||
|
||||
Some(Self::Cube {
|
||||
size: cube_size,
|
||||
colors: cube.iter().map(|color| color.to_gamma_srgb_channels()).map(|[red, green, blue, _]| [red, green, blue]).collect(),
|
||||
alpha: ramp.iter().map(|channels| channels[3]).collect(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The adjustment's results for grays of each luma, which stand for every color of that luma when the adjustment reads only its luma.
|
||||
fn luma_table(adjustment: &Adjustment, weights: [f32; 3]) -> Vec<[f32; 3]> {
|
||||
let total: f32 = weights.iter().sum();
|
||||
let mut grays: Vec<Color> = (0..CURVE_TABLE_SIZE)
|
||||
.map(|index| {
|
||||
let value = index as f32 / (CURVE_TABLE_SIZE - 1) as f32 / total;
|
||||
Color::from_gamma_srgb_channels(value, value, value, 1.)
|
||||
})
|
||||
.collect();
|
||||
adjust_colors(adjustment, &mut grays);
|
||||
|
||||
grays.iter().map(|color| color.to_gamma_srgb_channels()).map(|[red, green, blue, _]| [red, green, blue]).collect()
|
||||
}
|
||||
@@ -80,6 +80,36 @@ impl PreparedAdjustment {
|
||||
}
|
||||
}
|
||||
|
||||
/// The red, green, blue, and alpha curves of a per-channel adjustment, each sampled at `size` evenly spaced gamma-encoded values from 0 to 1.
|
||||
pub fn channel_curves(adjustment: &Adjustment, size: usize) -> Option<[Vec<f32>; 4]> {
|
||||
if !adjustment.is_per_channel() || size < 2 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Each sample feeds the same value to every channel, which the curves map independently
|
||||
let mut samples: Vec<Color> = (0..size)
|
||||
.map(|index| {
|
||||
let value = index as f32 / (size - 1) as f32;
|
||||
Color::from_gamma_srgb_channels(value, value, value, value)
|
||||
})
|
||||
.collect();
|
||||
adjust_colors(adjustment, &mut samples);
|
||||
|
||||
let channels: Vec<[f32; 4]> = samples.iter().map(Color::to_gamma_srgb_channels).collect();
|
||||
Some(std::array::from_fn(|channel| channels.iter().map(|values| values[channel]).collect()))
|
||||
}
|
||||
|
||||
/// Whether every color keeps its alpha to within half an 8-bit level.
|
||||
/// Only a per-channel adjustment's alpha curve can change it, since the kernels of the others all keep alpha.
|
||||
pub fn preserves_alpha(adjustment: &Adjustment) -> bool {
|
||||
const LEVELS: usize = 256;
|
||||
|
||||
channel_curves(adjustment, LEVELS).is_none_or(|[.., alpha]| {
|
||||
let identity = |index: usize| index as f32 / (LEVELS - 1) as f32;
|
||||
alpha.iter().enumerate().all(|(index, value)| (value - identity(index)).abs() <= 0.5 / 255.)
|
||||
})
|
||||
}
|
||||
|
||||
/// Receives the kernel carrying out an [`Adjustment`], which has its own type for each adjustment.
|
||||
pub trait AdjustmentVisitor {
|
||||
type Output;
|
||||
|
||||
@@ -12,9 +12,15 @@ pub(crate) struct ColorOverlay {
|
||||
|
||||
impl MapColor for ColorOverlay {
|
||||
fn map_cpu(&self, pixel: Color) -> Color {
|
||||
let overlay = apply_blend_mode(self.color, pixel, self.blend_mode);
|
||||
let mix = |image: f32, overlay: f32| image + (overlay - image) * self.opacity;
|
||||
|
||||
Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a())
|
||||
overlay_paint(pixel, self.color, self.blend_mode, self.opacity)
|
||||
}
|
||||
}
|
||||
|
||||
/// The color with `paint` mixed over it by the blend mode, as much as the paint's alpha times `opacity` (from 0 to 1), keeping the color's own alpha.
|
||||
pub fn overlay_paint(color: Color, paint: Color, blend_mode: BlendMode, opacity: f32) -> Color {
|
||||
let overlay = apply_blend_mode(paint, color, blend_mode);
|
||||
let amount = opacity * paint.a();
|
||||
let mix = |under: f32, over: f32| under + (over - under) * amount;
|
||||
|
||||
Color::from_rgbaf32_unchecked(mix(color.r(), overlay.r()), mix(color.g(), overlay.g()), mix(color.b(), overlay.b()), color.a())
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
//! The image operations that effects are built from, on the CPU: blurring, growing shapes, and shifting.
|
||||
//! They mirror the renderer's GPU passes, so a raster's effects read the same in a node that needs its pixels as on the canvas.
|
||||
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// Blurs and spreads shorter than this, in pixels, leave no visible trace.
|
||||
pub const NEGLIGIBLE_LENGTH: f64 = 0.01;
|
||||
|
||||
/// The largest Gaussian standard deviation, in pixels, convolved on the image itself rather than a halved copy.
|
||||
pub const MAX_DIRECT_GAUSSIAN_SIGMA: f64 = 8.;
|
||||
|
||||
/// The largest box half width, in pixels, convolved on the image itself rather than a halved copy.
|
||||
pub const MAX_DIRECT_BOX_RADIUS: f64 = 24.;
|
||||
|
||||
/// The farthest texel from the center a kernel weighs, which fits both direct limits.
|
||||
pub const MAX_KERNEL_REACH: usize = 24;
|
||||
|
||||
/// The most times an image is halved for a blur, by which point it is one pixel across.
|
||||
const MAX_LEVELS: u32 = 16;
|
||||
|
||||
/// A blur's kernel along one axis, sized in pixels.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum BlurKernel {
|
||||
Gaussian { sigma: f64 },
|
||||
Box { radius: f64 },
|
||||
}
|
||||
|
||||
impl BlurKernel {
|
||||
/// How many times the image is halved before the kernel runs, so the kernel stays within [`MAX_KERNEL_REACH`].
|
||||
pub fn levels(self) -> u32 {
|
||||
let (length, direct_limit) = match self {
|
||||
Self::Gaussian { sigma } => (sigma, MAX_DIRECT_GAUSSIAN_SIGMA),
|
||||
Self::Box { radius } => (radius, MAX_DIRECT_BOX_RADIUS),
|
||||
};
|
||||
|
||||
(length / direct_limit).log2().ceil().clamp(0., MAX_LEVELS as f64) as u32
|
||||
}
|
||||
|
||||
/// The weights of the texels from the center outward for an image halved `levels` times, normalized so the symmetric kernel sums to 1.
|
||||
pub fn weights(self, levels: u32) -> Vec<f64> {
|
||||
let level_scale = (1 << levels) as f64;
|
||||
|
||||
let weights: Vec<f64> = match self {
|
||||
Self::Gaussian { sigma } => {
|
||||
// Halving the image and doubling it back blur it too, so the kernel makes up only the rest of the variance
|
||||
let pyramid_variance = (4_f64.powi(levels as i32) - 1.) / 3.;
|
||||
let sigma = (sigma * sigma - pyramid_variance).max(0.).sqrt() / level_scale;
|
||||
if sigma < NEGLIGIBLE_LENGTH {
|
||||
return vec![1.];
|
||||
}
|
||||
|
||||
let reach = ((3. * sigma).ceil() as usize).min(MAX_KERNEL_REACH);
|
||||
(0..=reach).map(|i| (-((i * i) as f64) / (2. * sigma * sigma)).exp()).collect()
|
||||
}
|
||||
// The texels at the ends weigh only the fraction of them the box covers, so the blur grows smoothly with its radius
|
||||
Self::Box { radius } => {
|
||||
let radius = radius / level_scale;
|
||||
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
||||
(0..=reach).map(|i| (radius + 1. - i as f64).clamp(0., 1.)).collect()
|
||||
}
|
||||
};
|
||||
|
||||
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
||||
weights.into_iter().map(|weight| weight / total).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A pixel value the operations can weigh, sum, and compare: one coverage channel, or premultiplied color channels.
|
||||
pub trait Sample: Copy + Default + Send + Sync {
|
||||
fn scaled(self, factor: f32) -> Self;
|
||||
fn plus(self, other: Self) -> Self;
|
||||
fn max(self, other: Self) -> Self;
|
||||
}
|
||||
|
||||
impl Sample for f32 {
|
||||
fn scaled(self, factor: f32) -> Self {
|
||||
self * factor
|
||||
}
|
||||
fn plus(self, other: Self) -> Self {
|
||||
self + other
|
||||
}
|
||||
fn max(self, other: Self) -> Self {
|
||||
f32::max(self, other)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sample for [f32; 4] {
|
||||
fn scaled(self, factor: f32) -> Self {
|
||||
self.map(|channel| channel * factor)
|
||||
}
|
||||
fn plus(self, other: Self) -> Self {
|
||||
std::array::from_fn(|channel| self[channel] + other[channel])
|
||||
}
|
||||
fn max(self, other: Self) -> Self {
|
||||
std::array::from_fn(|channel| self[channel].max(other[channel]))
|
||||
}
|
||||
}
|
||||
|
||||
/// An image of [`Sample`]s in rows, which the operations read and write.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Plane<T> {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub data: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T: Sample> Plane<T> {
|
||||
pub fn new(width: usize, height: usize) -> Self {
|
||||
Self {
|
||||
width,
|
||||
height,
|
||||
data: vec![T::default(); width * height],
|
||||
}
|
||||
}
|
||||
|
||||
/// A plane of the same size whose pixels are `map` of this one's.
|
||||
pub fn map<U: Sample>(&self, map: impl Fn(T) -> U + Sync) -> Plane<U> {
|
||||
let mut mapped = Plane::new(self.width, self.height);
|
||||
fill_rows(&mut mapped.data, self.width, |y, row| {
|
||||
let source = &self.data[y * self.width..(y + 1) * self.width];
|
||||
row.iter_mut().zip(source).for_each(|(target, &value)| *target = map(value));
|
||||
});
|
||||
mapped
|
||||
}
|
||||
|
||||
/// Combines this plane with `other`, of the same size, pixel by pixel.
|
||||
pub fn zip<U: Sample, V: Sample>(&self, other: &Plane<U>, combine: impl Fn(T, U) -> V + Sync) -> Plane<V> {
|
||||
let mut combined = Plane::new(self.width, self.height);
|
||||
fill_rows(&mut combined.data, self.width, |y, row| {
|
||||
let range = y * self.width..(y + 1) * self.width;
|
||||
let pairs = self.data[range.clone()].iter().zip(&other.data[range]);
|
||||
row.iter_mut().zip(pairs).for_each(|(target, (&a, &b))| *target = combine(a, b));
|
||||
});
|
||||
combined
|
||||
}
|
||||
|
||||
/// The plane with its rows and columns swapped, so a horizontal operation can work vertically. O(width × height).
|
||||
fn transposed(&self) -> Self {
|
||||
let mut transposed = Self::new(self.height, self.width);
|
||||
fill_rows(&mut transposed.data, self.height, |x, row| {
|
||||
row.iter_mut().enumerate().for_each(|(y, target)| *target = self.data[y * self.width + x]);
|
||||
});
|
||||
transposed
|
||||
}
|
||||
|
||||
/// Runs `operation` on each row, which it reads in full and writes as a new row of `width` pixels.
|
||||
fn map_rows(&self, width: usize, operation: impl Fn(&[T], &mut [T]) + Sync) -> Self {
|
||||
let mut result = Self::new(width, self.height);
|
||||
fill_rows(&mut result.data, width, |y, row| operation(&self.data[y * self.width..(y + 1) * self.width], row));
|
||||
result
|
||||
}
|
||||
|
||||
/// Runs `along_rows` on the plane's rows, then on its columns by way of one transpose there and back.
|
||||
fn along_both_axes<P>(self, horizontal: P, vertical: P, along_rows: impl Fn(Self, P) -> Self) -> Self {
|
||||
let plane = along_rows(self, horizontal);
|
||||
along_rows(plane.transposed(), vertical).transposed()
|
||||
}
|
||||
|
||||
/// Blurs the plane by a kernel along each axis. Kernels too wide to convolve directly run on a copy halved along their axis enough times
|
||||
/// for them to fit, then doubled back. O(width × height) per pass, with a pass for each halving and doubling.
|
||||
pub fn blurred(self, horizontal: BlurKernel, vertical: BlurKernel) -> Self {
|
||||
self.along_both_axes(horizontal, vertical, |mut plane, kernel| {
|
||||
let levels = kernel.levels();
|
||||
let length = plane.width;
|
||||
let level_length = |level: u32| length.div_ceil(1 << level);
|
||||
|
||||
for level in 1..=levels {
|
||||
plane = plane.map_rows(level_length(level), halve_row);
|
||||
}
|
||||
|
||||
let weights = kernel.weights(levels);
|
||||
plane = plane.map_rows(level_length(levels), |source, target| convolve_row(source, target, &weights));
|
||||
|
||||
for level in (0..levels).rev() {
|
||||
plane = plane.map_rows(level_length(level), double_row);
|
||||
}
|
||||
plane
|
||||
})
|
||||
}
|
||||
|
||||
/// Grows the shapes by a distance in pixels along each axis, in a square like SVG's `feMorphology`.
|
||||
pub fn dilated(self, horizontal: f64, vertical: f64) -> Self {
|
||||
self.along_both_axes(horizontal, vertical, |mut plane, distance| {
|
||||
let length = plane.width;
|
||||
|
||||
// Steps that double, then the remainder, so each step grows the shapes by up to as much as all the steps before it
|
||||
let (mut covered, mut step) = (0., 1.);
|
||||
while covered + step <= distance {
|
||||
plane = plane.map_rows(length, |source, target| dilate_row(source, target, step));
|
||||
covered += step;
|
||||
step *= 2.;
|
||||
}
|
||||
if distance - covered >= NEGLIGIBLE_LENGTH {
|
||||
plane = plane.map_rows(length, |source, target| dilate_row(source, target, distance - covered));
|
||||
}
|
||||
plane
|
||||
})
|
||||
}
|
||||
|
||||
/// Moves the image by a fractional offset in pixels, interpolating between pixels and leaving transparency where it uncovers the edges.
|
||||
pub fn shifted(self, offset_x: f64, offset_y: f64) -> Self {
|
||||
self.along_both_axes(offset_x, offset_y, |plane, offset| plane.map_rows(plane.width, |source, target| shift_row(source, target, offset)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Plane<f32> {
|
||||
/// The coverage of the band reaching `width` pixels from the silhouette's edge, outward or (if `inward`) inward, measured in straight lines so it rounds corners.
|
||||
pub fn edge_band(&self, width: f64, inward: bool) -> Self {
|
||||
// The edge lies about half a pixel short of the nearest pixel across it, and the band fades out over one pixel
|
||||
let distances = self.distances_across_edge(width, inward);
|
||||
let width = width as f32;
|
||||
distances.map(|distance| (width + 1. - distance).clamp(0., 1.))
|
||||
}
|
||||
|
||||
/// Each pixel's distance to the nearest pixel across the silhouette's edge: outside it if `inward`, or inside it otherwise, with those pixels at zero.
|
||||
/// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, so farther pixels may find none and lie at infinity. O(width × height × log(reach)).
|
||||
pub fn distances_across_edge(&self, reach: f64, inward: bool) -> Self {
|
||||
// The side of the edge that distances are measured from, whose pixels are their own nearest
|
||||
let is_seed = |coverage: f32| (coverage >= 0.5) != inward;
|
||||
let mut nearest: Vec<Option<[i32; 2]>> = self.data.iter().map(|&coverage| is_seed(coverage).then_some([0, 0])).collect();
|
||||
|
||||
let (columns, rows) = (self.width as i32, self.height as i32);
|
||||
let length_squared = |[x, y]: [i32; 2]| x * x + y * y;
|
||||
let mut step = (reach.max(0.).ceil() as u32 + 1).next_power_of_two();
|
||||
while step >= 1 {
|
||||
let previous = nearest.clone();
|
||||
let step_length = step as i32;
|
||||
|
||||
// Each pixel keeps the nearest of the seeds that it and its eight neighbors a step away have found so far
|
||||
fill_rows(&mut nearest, self.width, |y, row| {
|
||||
for (x, best) in row.iter_mut().enumerate() {
|
||||
for neighbor_y in -1..=1 {
|
||||
for neighbor_x in -1..=1 {
|
||||
let (x, y) = (x as i32 + neighbor_x * step_length, y as i32 + neighbor_y * step_length);
|
||||
if x < 0 || y < 0 || x >= columns || y >= rows {
|
||||
continue;
|
||||
}
|
||||
let Some([offset_x, offset_y]) = previous[(y * columns + x) as usize] else { continue };
|
||||
|
||||
let candidate = [offset_x + neighbor_x * step_length, offset_y + neighbor_y * step_length];
|
||||
if best.is_none_or(|best| length_squared(candidate) < length_squared(best)) {
|
||||
*best = Some(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
step /= 2;
|
||||
}
|
||||
|
||||
let data = nearest
|
||||
.into_iter()
|
||||
.map(|offset| offset.map_or(f32::INFINITY, |offset| (length_squared(offset) as f32).sqrt()))
|
||||
.collect();
|
||||
Self {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
data,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The row's value at a position measured in pixels from the first pixel's center, interpolating linearly and holding the end pixels beyond the ends.
|
||||
fn sample_row<T: Sample>(row: &[T], position: f64) -> T {
|
||||
let last = row.len() as f64 - 1.;
|
||||
let position = position.clamp(0., last.max(0.));
|
||||
let index = position.floor() as usize;
|
||||
let fraction = (position - index as f64) as f32;
|
||||
|
||||
match row.get(index + 1) {
|
||||
Some(&next) if fraction > 0. => row[index].scaled(1. - fraction).plus(next.scaled(fraction)),
|
||||
_ => row[index],
|
||||
}
|
||||
}
|
||||
|
||||
/// Halves the row by averaging each pair of pixels, the last pixel of an odd row pairing with itself.
|
||||
fn halve_row<T: Sample>(source: &[T], target: &mut [T]) {
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let first = source[2 * index];
|
||||
let second = source.get(2 * index + 1).copied().unwrap_or(first);
|
||||
*value = first.plus(second).scaled(0.5);
|
||||
}
|
||||
}
|
||||
|
||||
/// Doubles a halved row back to its length, interpolating at each pixel's center within the pair it was averaged into.
|
||||
fn double_row<T: Sample>(source: &[T], target: &mut [T]) {
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
*value = sample_row(source, index as f64 / 2. - 0.25);
|
||||
}
|
||||
}
|
||||
|
||||
/// Weighs each pixel's neighbors by the symmetric kernel `weights`, from the center outward, holding the end pixels beyond the ends.
|
||||
fn convolve_row<T: Sample>(source: &[T], target: &mut [T], weights: &[f64]) {
|
||||
let last = source.len() as isize - 1;
|
||||
let at = |index: isize| source[index.clamp(0, last) as usize];
|
||||
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let index = index as isize;
|
||||
let mut sum = at(index).scaled(weights[0] as f32);
|
||||
for (distance, &weight) in weights.iter().enumerate().skip(1) {
|
||||
let pair = at(index - distance as isize).plus(at(index + distance as isize));
|
||||
sum = sum.plus(pair.scaled(weight as f32));
|
||||
}
|
||||
*value = sum;
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes each pixel's maximum with the row's values `step` pixels to either side.
|
||||
fn dilate_row<T: Sample>(source: &[T], target: &mut [T], step: f64) {
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let position = index as f64;
|
||||
*value = source[index].max(sample_row(source, position - step)).max(sample_row(source, position + step));
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the row by `offset` pixels, with nothing beyond its ends.
|
||||
fn shift_row<T: Sample>(source: &[T], target: &mut [T], offset: f64) {
|
||||
let length = source.len() as f64;
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let position = index as f64 - offset;
|
||||
let floor = position.floor();
|
||||
let fraction = (position - floor) as f32;
|
||||
|
||||
let at = |index: f64| if index >= 0. && index < length { source[index as usize] } else { T::default() };
|
||||
*value = at(floor).scaled(1. - fraction).plus(at(floor + 1.).scaled(fraction));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn kernel_weights_sum_to_one() {
|
||||
for kernel in [
|
||||
BlurKernel::Gaussian { sigma: 3. },
|
||||
BlurKernel::Gaussian { sigma: 40. },
|
||||
BlurKernel::Box { radius: 5.5 },
|
||||
BlurKernel::Box { radius: 100. },
|
||||
] {
|
||||
let levels = kernel.levels();
|
||||
let weights = kernel.weights(levels);
|
||||
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
||||
|
||||
assert!((total - 1.).abs() < 1e-9, "{kernel:?} weights sum to {total}");
|
||||
assert!(weights.len() <= MAX_KERNEL_REACH + 1, "{kernel:?} reaches {} texels", weights.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_kernels_run_without_halving() {
|
||||
assert_eq!(BlurKernel::Gaussian { sigma: MAX_DIRECT_GAUSSIAN_SIGMA }.levels(), 0);
|
||||
assert_eq!(
|
||||
BlurKernel::Gaussian {
|
||||
sigma: MAX_DIRECT_GAUSSIAN_SIGMA * 1.01
|
||||
}
|
||||
.levels(),
|
||||
1
|
||||
);
|
||||
assert_eq!(BlurKernel::Box { radius: 1. }.levels(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaussian_blur_spreads_a_point_with_the_requested_deviation() {
|
||||
// A single bright pixel blurs into the Gaussian itself, whose variance the pyramid must preserve at every level count
|
||||
for sigma in [2., 20.] {
|
||||
let size = 401;
|
||||
let mut plane = Plane::<f32>::new(size, 1);
|
||||
plane.data[size / 2] = 1.;
|
||||
|
||||
let blurred = plane.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma: 0. });
|
||||
let total: f32 = blurred.data.iter().sum();
|
||||
let variance: f64 = blurred.data.iter().enumerate().map(|(x, &value)| value as f64 * (x as f64 - (size / 2) as f64).powi(2)).sum::<f64>() / total as f64;
|
||||
|
||||
assert!((total - 1.).abs() < 1e-3, "sigma {sigma} keeps the total at {total}");
|
||||
assert!((variance.sqrt() - sigma).abs() / sigma < 0.05, "sigma {sigma} spreads to a deviation of {}", variance.sqrt());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dilation_grows_shapes_by_the_distance() {
|
||||
let mut plane = Plane::<f32>::new(21, 21);
|
||||
plane.data[10 * 21 + 10] = 1.;
|
||||
|
||||
let dilated = plane.dilated(3., 3.);
|
||||
let covered = dilated.data.iter().filter(|&&value| value >= 0.999).count();
|
||||
|
||||
assert_eq!(covered, 7 * 7, "a point grows into a 7 by 7 square");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edge_bands_round_the_corners_they_grow_around() {
|
||||
// A single pixel grows into a disk the band's width across, rather than a square
|
||||
let mut point = Plane::<f32>::new(21, 21);
|
||||
point.data[10 * 21 + 10] = 1.;
|
||||
let outward = point.edge_band(5., false);
|
||||
let at = |plane: &Plane<f32>, x: usize, y: usize| plane.data[y * 21 + x];
|
||||
|
||||
assert_eq!(at(&outward, 15, 10), 1., "the full width along an axis");
|
||||
assert_eq!(at(&outward, 17, 10), 0., "past the width");
|
||||
assert_eq!(at(&outward, 15, 14), 0., "past the width diagonally, where a square would still reach");
|
||||
|
||||
// Inward, only the pixels near the edge are covered
|
||||
let mut square = Plane::<f32>::new(21, 21);
|
||||
for y in 2..19 {
|
||||
square.data[y * 21 + 2..y * 21 + 19].fill(1.);
|
||||
}
|
||||
let inward = square.edge_band(3., true);
|
||||
|
||||
assert_eq!(at(&inward, 2, 10), 1., "at the edge");
|
||||
assert_eq!(at(&inward, 10, 10), 0., "deep inside");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shifting_moves_by_fractions_of_a_pixel() {
|
||||
let mut plane = Plane::<f32>::new(4, 1);
|
||||
plane.data[1] = 1.;
|
||||
|
||||
let shifted = plane.shifted(0.25, 0.);
|
||||
|
||||
assert_eq!(shifted.data, vec![0., 0.75, 0.25, 0.]);
|
||||
}
|
||||
}
|
||||
@@ -17,27 +17,30 @@ pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32,
|
||||
let pixel_size = (area[1] - area[0]) / DVec2::new(width as f64, height as f64);
|
||||
let pixel_center = |x: usize, y: usize| area[0] + (DVec2::new(x as f64, y as f64) + 0.5) * pixel_size;
|
||||
|
||||
match pattern {
|
||||
GeneratorPattern::Noise(settings) => {
|
||||
let noise = NoiseSampler::new(settings);
|
||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = Color::from_luminance(noise.sample(pixel_center(x, y))));
|
||||
});
|
||||
}
|
||||
GeneratorPattern::Mandelbrot => {
|
||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| {
|
||||
let c = pixel_center(x, y) * 3. - DVec2::new(2., 1.5);
|
||||
let value = mandelbrot_escape_iterations(c) as f32 / MANDELBROT_ITERATIONS as f32;
|
||||
*pixel = Color::from_rgbaf32_unchecked(value, value, value, 1.);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
let sample = pattern_sampler(pattern);
|
||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = sample(pixel_center(x, y)));
|
||||
});
|
||||
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
/// Samples the pattern's color at points in its own space, after the setup shared by every sample.
|
||||
pub fn pattern_sampler(pattern: &GeneratorPattern) -> impl Fn(DVec2) -> Color + Sync + use<> {
|
||||
let noise = match pattern {
|
||||
GeneratorPattern::Noise(settings) => Some(NoiseSampler::new(settings)),
|
||||
GeneratorPattern::Mandelbrot => None,
|
||||
};
|
||||
|
||||
move |point| match &noise {
|
||||
Some(noise) => Color::from_luminance(noise.sample(point)),
|
||||
None => {
|
||||
let value = mandelbrot_escape_iterations(point * 3. - DVec2::new(2., 1.5)) as f32 / MANDELBROT_ITERATIONS as f32;
|
||||
Color::from_rgbaf32_unchecked(value, value, value, 1.)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples a noise pattern's luminance, from 0 to 1, at positions in its space.
|
||||
struct NoiseSampler {
|
||||
noise: fastnoise_lite::FastNoiseLite,
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
//! The kernels carrying out raster operations, such as color adjustments and procedural patterns, each worked out once from its settings.
|
||||
|
||||
pub mod adjustment_tables;
|
||||
pub mod adjustments;
|
||||
mod blending;
|
||||
pub mod color_lookup_table;
|
||||
pub mod effect_kernels;
|
||||
pub mod generators;
|
||||
mod kernel;
|
||||
pub mod raster_effects;
|
||||
pub mod value_effects;
|
||||
|
||||
pub use kernel::*;
|
||||
pub use raster_effects::evaluate_raster_effects;
|
||||
pub use value_effects::{evaluate_color_effects, evaluate_gradient_effects};
|
||||
@@ -0,0 +1,486 @@
|
||||
//! Carries out a raster's effects on the CPU at the raster's own resolution, for the nodes that read its pixels.
|
||||
//! Each step mirrors the renderer's GPU passes, working on premultiplied gamma-encoded channels as they do.
|
||||
|
||||
use crate::adjustments::adjust_colors;
|
||||
use crate::blending::overlay_paint;
|
||||
use crate::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, Plane};
|
||||
use crate::generators::pattern_sampler;
|
||||
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_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_START_CURVATURE, Item};
|
||||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::effects::{BevelDirection, BevelStyle, EffectOperation, Effects, GlowSource, bevel_light, bevel_smoothing, fitted_paint, outline_extents};
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{CPU, Image, Raster};
|
||||
use vector_types::gradient::{Gradient, GradientForm, GradientSettings, LINEAR_DIALS, RADIAL_DIALS, wrapped_dial};
|
||||
|
||||
/// The most pixels an image may grow to with the margin its effects cast into, beyond which the margin is cut short.
|
||||
const MAX_PIXELS_WITH_MARGIN: f64 = (1 << 24) as f64;
|
||||
|
||||
/// The raster with its effects carried out into its pixels, grown to hold what they cast past its edges, and with the effects and the fill opacity they used removed.
|
||||
/// A raster without the effects attribute is returned as it is.
|
||||
pub fn evaluate_raster_effects(item: Item<Raster<CPU>>) -> Item<Raster<CPU>> {
|
||||
let Some(operations) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| effects.operations().collect::<Vec<_>>()) else {
|
||||
return item;
|
||||
};
|
||||
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
||||
|
||||
let (raster, attributes) = item.into_parts();
|
||||
let (raster, transform) = match evaluate(&raster, transform, &operations, fill) {
|
||||
Some((image, grown_transform)) => (Raster::new_cpu(image), grown_transform),
|
||||
None => (raster, transform),
|
||||
};
|
||||
|
||||
// Which attributes come out depends only on whether the effects attribute came in, not on what it holds
|
||||
let mut item = Item::from_parts(raster, attributes);
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
|
||||
item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
item
|
||||
}
|
||||
|
||||
/// The raster with `adjustments` carried out on its colors, even those of transparent pixels, as for the adjustments leading its effects.
|
||||
/// The result is kept with the raster's pixels, so adjusting them the same way again reuses it, ID and all.
|
||||
pub fn adjusted_raster(raster: &Raster<CPU>, adjustments: &[Adjustment]) -> Raster<CPU> {
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
adjustments.iter().for_each(|adjustment| core_types::graphene_hash::CacheHash::cache_hash(adjustment, &mut hasher));
|
||||
let key = std::hash::Hasher::finish(&hasher);
|
||||
|
||||
raster.derived(key, |raster| {
|
||||
let mut image = raster.data().clone();
|
||||
adjustments.iter().for_each(|adjustment| adjust_colors(adjustment, &mut image.data));
|
||||
Raster::new_cpu(image)
|
||||
})
|
||||
}
|
||||
|
||||
/// The image of the effects carried out on `raster`, which `transform` places in the document, with the transform placing that larger image.
|
||||
/// `None` when there's nothing to carry out, or the image is empty or its transform can't be inverted.
|
||||
fn evaluate(raster: &Raster<CPU>, transform: DAffine2, operations: &[EffectOperation], fill: f32) -> Option<(Image<Color>, DAffine2)> {
|
||||
let (width, height) = (raster.width as usize, raster.height as usize);
|
||||
if (operations.is_empty() && fill >= 1.) || width == 0 || height == 0 || transform.matrix2.determinant() == 0. {
|
||||
return None;
|
||||
}
|
||||
let size = DVec2::new(width as f64, height as f64);
|
||||
|
||||
// Unless a fill fades them first, leading adjustments change the image's own colors, keeping even transparent pixels' colors
|
||||
let leading_adjustments = operations.iter().take_while(|_| fill == 1.).map_while(|operation| match operation {
|
||||
EffectOperation::Adjustment(adjustment) => Some(adjustment),
|
||||
_ => None,
|
||||
});
|
||||
let mut colors = std::borrow::Cow::Borrowed(raster.data.as_slice());
|
||||
let mut remaining = operations;
|
||||
for adjustment in leading_adjustments {
|
||||
adjust_colors(adjustment, colors.to_mut());
|
||||
remaining = &remaining[1..];
|
||||
}
|
||||
if remaining.is_empty() {
|
||||
let data = colors.iter().map(|color| color.with_alpha(color.a() * fill)).collect();
|
||||
return Some((
|
||||
Image {
|
||||
width: raster.width,
|
||||
height: raster.height,
|
||||
data,
|
||||
},
|
||||
transform,
|
||||
));
|
||||
}
|
||||
let operations = remaining;
|
||||
|
||||
// Document lengths become pixels along each of the image's axes, and offsets map through the inverse of its pixel placement
|
||||
let pixels_to_document = transform.matrix2 * DMat2::from_diagonal(size.recip());
|
||||
let document_to_pixels = pixels_to_document.inverse();
|
||||
let pixels_per_length = DVec2::new(pixels_to_document.x_axis.length(), pixels_to_document.y_axis.length()).recip();
|
||||
|
||||
// A margin around the image to hold the blur and shadows cast past its edges, cut short for an image that would grow too large
|
||||
let reach: f64 = operations.iter().map(EffectOperation::reach).sum();
|
||||
let mut margin = (reach * pixels_per_length).ceil();
|
||||
let grown_size = size + 2. * margin;
|
||||
if grown_size.x * grown_size.y > MAX_PIXELS_WITH_MARGIN {
|
||||
let shrunk_size = grown_size * (MAX_PIXELS_WITH_MARGIN / (grown_size.x * grown_size.y)).sqrt();
|
||||
margin = ((shrunk_size - size) / 2.).max(DVec2::ZERO).floor();
|
||||
}
|
||||
let (margin_x, margin_y) = (margin.x as usize, margin.y as usize);
|
||||
|
||||
// The content at full strength, which casts every silhouette, and the content faded by the fill, which shows in the result
|
||||
let mut full = Plane::<[f32; 4]>::new(width + 2 * margin_x, height + 2 * margin_y);
|
||||
for (y, row) in colors.chunks_exact(width).enumerate() {
|
||||
let start = (y + margin_y) * full.width + margin_x;
|
||||
full.data[start..start + width]
|
||||
.iter_mut()
|
||||
.zip(row)
|
||||
.for_each(|(target, &color)| *target = premultiplied_gamma_channels(color));
|
||||
}
|
||||
let mut filled = (fill < 1.).then(|| full.map(|pixel| pixel.map(|channel| channel * fill)));
|
||||
// The shadows and glows stacked beneath the content
|
||||
let mut beneath: Option<Plane<[f32; 4]>> = None;
|
||||
|
||||
for operation in operations {
|
||||
match *operation {
|
||||
EffectOperation::Blur { radius, box_blur, gamma } => {
|
||||
let radius = radius * pixels_per_length;
|
||||
if radius.max_element() < NEGLIGIBLE_LENGTH {
|
||||
continue;
|
||||
}
|
||||
|
||||
// What lies beneath blurs together with the content
|
||||
if let Some(beneath) = beneath.take() {
|
||||
filled = filled.map(|filled| composite_beneath(&filled, &beneath, &full));
|
||||
full = composite_beneath(&full, &beneath, &full);
|
||||
}
|
||||
|
||||
let kernels = match box_blur {
|
||||
true => (BlurKernel::Box { radius: radius.x }, BlurKernel::Box { radius: radius.y }),
|
||||
false => (BlurKernel::Gaussian { sigma: radius.x }, BlurKernel::Gaussian { sigma: radius.y }),
|
||||
};
|
||||
full = blur(full, kernels, !gamma);
|
||||
filled = filled.map(|filled| blur(filled, kernels, !gamma));
|
||||
}
|
||||
EffectOperation::DropShadow { color, offset, blur, spread } => {
|
||||
let coverage = cast(&full, document_to_pixels * offset, blur * pixels_per_length, spread * pixels_per_length, false);
|
||||
beneath = Some(accumulate(beneath, &coverage, color));
|
||||
}
|
||||
EffectOperation::OuterGlow { color, blur, spread } => {
|
||||
let coverage = cast(&full, DVec2::ZERO, blur * pixels_per_length, spread * pixels_per_length, false);
|
||||
beneath = Some(accumulate(beneath, &coverage, color));
|
||||
}
|
||||
EffectOperation::InnerShadow { color, offset, blur, spread } => {
|
||||
let coverage = cast(&full, document_to_pixels * offset, blur * pixels_per_length, spread * pixels_per_length, true);
|
||||
filled = filled.map(|filled| composite_within(&filled, &coverage, &full, color));
|
||||
full = composite_within(&full, &coverage, &full, color);
|
||||
}
|
||||
EffectOperation::InnerGlow { color, blur, choke, source } => {
|
||||
let mut coverage = cast(&full, DVec2::ZERO, blur * pixels_per_length, choke * pixels_per_length, true);
|
||||
if source == GlowSource::Center {
|
||||
coverage = coverage.map(|coverage| 1. - coverage);
|
||||
}
|
||||
filled = filled.map(|filled| composite_within(&filled, &coverage, &full, color));
|
||||
full = composite_within(&full, &coverage, &full, color);
|
||||
}
|
||||
EffectOperation::Satin { color, offset, blur, invert } => {
|
||||
let offset = document_to_pixels * offset;
|
||||
let forward = cast(&full, offset, blur * pixels_per_length, DVec2::ZERO, false);
|
||||
let backward = cast(&full, -offset, blur * pixels_per_length, DVec2::ZERO, false);
|
||||
let coverage = forward.zip(&backward, |forward, backward| satin_coverage(forward, backward, invert));
|
||||
|
||||
filled = filled.map(|filled| composite_within(&filled, &coverage, &full, color));
|
||||
full = composite_within(&full, &coverage, &full, color);
|
||||
}
|
||||
EffectOperation::Outline { color, weight, align } => {
|
||||
// Straight-line distances can't stretch along one axis, so an image scaled unevenly takes the mean of its two scales
|
||||
let pixels_per_length = (pixels_per_length.x * pixels_per_length.y).sqrt();
|
||||
let (outside, inside) = outline_extents(weight * pixels_per_length, align);
|
||||
let silhouette = full.map(|[_, _, _, alpha]| alpha);
|
||||
|
||||
if outside >= NEGLIGIBLE_LENGTH {
|
||||
beneath = Some(accumulate(beneath, &silhouette.edge_band(outside, false), color));
|
||||
}
|
||||
if inside >= NEGLIGIBLE_LENGTH {
|
||||
let coverage = silhouette.edge_band(inside, true);
|
||||
filled = filled.map(|filled| composite_within(&filled, &coverage, &full, color));
|
||||
full = composite_within(&full, &coverage, &full, color);
|
||||
}
|
||||
}
|
||||
EffectOperation::BevelAndEmboss {
|
||||
style,
|
||||
depth,
|
||||
direction,
|
||||
size,
|
||||
soften,
|
||||
angle,
|
||||
altitude,
|
||||
highlight_color,
|
||||
shadow_color,
|
||||
} => {
|
||||
let pixels_per_length = (pixels_per_length.x * pixels_per_length.y).sqrt();
|
||||
let (size, soften) = (size * pixels_per_length, soften * pixels_per_length);
|
||||
if size < NEGLIGIBLE_LENGTH {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The surface's height, rounded by a blur, lit from the light's direction into its highlights and shadows
|
||||
let height = soften_by(bevel_height(&full.map(|[_, _, _, alpha]| alpha), size, style), bevel_smoothing(size));
|
||||
let slope = depth / 100. * size * if direction == BevelDirection::Down { -1. } else { 1. };
|
||||
let light = bevel_light(angle, altitude, document_to_pixels);
|
||||
|
||||
// Their parts outside the content lie beneath it, and those inside are placed over it
|
||||
for (shadow, color) in [(false, highlight_color), (true, shadow_color)] {
|
||||
let coverage = soften_by(bevel_shading(&height, slope, light, shadow), soften);
|
||||
beneath = Some(accumulate(beneath, &coverage, color));
|
||||
filled = filled.map(|filled| composite_within(&filled, &coverage, &full, color));
|
||||
full = composite_within(&full, &coverage, &full, color);
|
||||
}
|
||||
}
|
||||
EffectOperation::PaintOverlay { ref paint, blend_mode, opacity } => {
|
||||
let corners = [DVec2::ZERO, DVec2::X, DVec2::Y, DVec2::ONE].map(|corner| transform.transform_point2(corner));
|
||||
let content_bounds = [corners.into_iter().reduce(DVec2::min).unwrap(), corners.into_iter().reduce(DVec2::max).unwrap()];
|
||||
let fitted = fitted_paint(paint, content_bounds);
|
||||
let Some(sample_paint) = paint_sampler(fitted.as_ref().unwrap_or(paint)) else { continue };
|
||||
|
||||
// The paint at each pixel's center, in the space the image is placed in
|
||||
let pixels_to_placement = transform * DAffine2::from_scale(size.recip()) * DAffine2::from_translation(-DVec2::new(margin_x as f64, margin_y as f64));
|
||||
let mut paint_colors = vec![Color::TRANSPARENT; full.data.len()];
|
||||
fill_rows(&mut paint_colors, full.width, |y, row| {
|
||||
for (x, color) in row.iter_mut().enumerate() {
|
||||
*color = sample_paint(pixels_to_placement.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)));
|
||||
}
|
||||
});
|
||||
|
||||
let opacity = (opacity / 100.) as f32;
|
||||
filled = filled.map(|filled| overlay(&filled, &paint_colors, blend_mode, opacity));
|
||||
full = overlay(&full, &paint_colors, blend_mode, opacity);
|
||||
}
|
||||
EffectOperation::Adjustment(ref adjustment) => {
|
||||
full = adjust(&full, adjustment);
|
||||
filled = filled.map(|filled| adjust(&filled, adjustment));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let result = match (filled, beneath) {
|
||||
(filled, Some(beneath)) => composite_beneath(filled.as_ref().unwrap_or(&full), &beneath, &full),
|
||||
(Some(filled), None) => filled,
|
||||
(None, None) => full,
|
||||
};
|
||||
let image = Image {
|
||||
width: result.width as u32,
|
||||
height: result.height as u32,
|
||||
data: result.data.into_iter().map(straight_linear_color).collect(),
|
||||
};
|
||||
|
||||
// The grown image spans the margin on each side of the original's unit square
|
||||
let unit_margin = DVec2::new(margin_x as f64, margin_y as f64) / size;
|
||||
let grown_transform = transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin);
|
||||
|
||||
Some((image, grown_transform))
|
||||
}
|
||||
|
||||
/// A color as the premultiplied, gamma-encoded channels the effects work with.
|
||||
fn premultiplied_gamma_channels(color: Color) -> [f32; 4] {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||
}
|
||||
|
||||
/// Premultiplied, gamma-encoded channels back as a color.
|
||||
fn straight_linear_color([red, green, blue, alpha]: [f32; 4]) -> Color {
|
||||
if alpha <= 0. {
|
||||
return Color::TRANSPARENT;
|
||||
}
|
||||
Color::from_gamma_srgb_channels(red / alpha, green / alpha, blue / alpha, alpha.min(1.))
|
||||
}
|
||||
|
||||
/// Adjusts premultiplied gamma-encoded pixels by way of their straight colors, leaving fully transparent pixels empty since they keep no color to adjust.
|
||||
fn adjust(plane: &Plane<[f32; 4]>, adjustment: &Adjustment) -> Plane<[f32; 4]> {
|
||||
let mut colors: Vec<Color> = plane.data.iter().copied().map(straight_linear_color).collect();
|
||||
adjust_colors(adjustment, &mut colors);
|
||||
|
||||
let data = plane
|
||||
.data
|
||||
.iter()
|
||||
.zip(colors)
|
||||
.map(|(pixel, color)| if pixel[3] <= 0. { [0.; 4] } else { premultiplied_gamma_channels(color) })
|
||||
.collect();
|
||||
Plane {
|
||||
width: plane.width,
|
||||
height: plane.height,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
/// Premultiplied channels with `transfer` applied to their straight color.
|
||||
fn transferred(transfer: fn(f32) -> f32) -> impl Fn([f32; 4]) -> [f32; 4] + Sync {
|
||||
move |[red, green, blue, alpha]| {
|
||||
if alpha <= 0. {
|
||||
return [0.; 4];
|
||||
}
|
||||
let channel = |value: f32| transfer((value / alpha).max(0.)) * alpha;
|
||||
[channel(red), channel(green), channel(blue), alpha]
|
||||
}
|
||||
}
|
||||
|
||||
/// Blurs premultiplied gamma-encoded pixels by a kernel along each axis, in linear light if `linear`.
|
||||
fn blur(plane: Plane<[f32; 4]>, (horizontal, vertical): (BlurKernel, BlurKernel), linear: bool) -> Plane<[f32; 4]> {
|
||||
match linear {
|
||||
true => plane.map(transferred(srgb_to_linear)).blurred(horizontal, vertical).map(transferred(linear_to_srgb)),
|
||||
false => plane.blurred(horizontal, vertical),
|
||||
}
|
||||
}
|
||||
|
||||
/// The coverage of the content's silhouette (or of the area outside it, if `inverse`), cast by `offset`, grown by `spread` and softened by a Gaussian of deviation `blur`, all in pixels along each axis.
|
||||
fn cast(content: &Plane<[f32; 4]>, offset: DVec2, blur: DVec2, spread: DVec2, inverse: bool) -> Plane<f32> {
|
||||
let mut coverage = content.map(|[_, _, _, alpha]| alpha).shifted(offset.x, offset.y);
|
||||
if inverse {
|
||||
coverage = coverage.map(|alpha| 1. - alpha);
|
||||
}
|
||||
|
||||
if spread.max_element() >= NEGLIGIBLE_LENGTH {
|
||||
coverage = coverage.dilated(spread.x, spread.y);
|
||||
}
|
||||
if blur.max_element() >= NEGLIGIBLE_LENGTH {
|
||||
coverage = coverage.blurred(BlurKernel::Gaussian { sigma: blur.x }, BlurKernel::Gaussian { sigma: blur.y });
|
||||
}
|
||||
coverage
|
||||
}
|
||||
|
||||
/// Stacks a silhouette's coverage, tinted `color`, over what lies `beneath` the content so far.
|
||||
fn accumulate(beneath: Option<Plane<[f32; 4]>>, coverage: &Plane<f32>, color: Color) -> Plane<[f32; 4]> {
|
||||
let color = premultiplied_gamma_channels(color);
|
||||
let tinted = coverage.map(|coverage| color.map(|channel| channel * coverage));
|
||||
|
||||
match beneath {
|
||||
Some(beneath) => tinted.zip(&beneath, |tinted, beneath| std::array::from_fn(|channel| tinted[channel] + beneath[channel] * (1. - tinted[3]))),
|
||||
None => tinted,
|
||||
}
|
||||
}
|
||||
|
||||
/// The image with a silhouette's coverage, tinted `color`, placed over it within the full-strength content.
|
||||
fn composite_within(image: &Plane<[f32; 4]>, coverage: &Plane<f32>, full_content: &Plane<[f32; 4]>, color: Color) -> Plane<[f32; 4]> {
|
||||
let color = premultiplied_gamma_channels(color);
|
||||
let coverages = coverage.zip(full_content, |coverage, content| [coverage, content[3], 0., 0.]);
|
||||
|
||||
image.zip(&coverages, |image, [coverage, content_alpha, _, _]| {
|
||||
let tinted = color.map(|channel| channel * coverage);
|
||||
std::array::from_fn(|channel| tinted[channel] * content_alpha + image[channel] * (1. - tinted[3]))
|
||||
})
|
||||
}
|
||||
|
||||
/// The image with the shadows and glows `beneath` placed under it, knocked out by the full-strength content.
|
||||
fn composite_beneath(image: &Plane<[f32; 4]>, beneath: &Plane<[f32; 4]>, full_content: &Plane<[f32; 4]>) -> Plane<[f32; 4]> {
|
||||
let knocked_out = beneath.zip(full_content, |beneath, content| beneath.map(|channel| channel * (1. - content[3])));
|
||||
image.zip(&knocked_out, |image, beneath| std::array::from_fn(|channel| image[channel] + beneath[channel]))
|
||||
}
|
||||
|
||||
/// Satin's shading where the two casts of the silhouette cover `forward` and `backward`: how much one covers without the other, or how much they agree if `invert`.
|
||||
fn satin_coverage(forward: f32, backward: f32, invert: bool) -> f32 {
|
||||
let difference = (forward - backward).abs();
|
||||
if invert { 1. - difference } else { difference }
|
||||
}
|
||||
|
||||
/// The plane blurred by a Gaussian of deviation `sigma` pixels, or left as it is for one too small to see.
|
||||
fn soften_by(plane: Plane<f32>, sigma: f64) -> Plane<f32> {
|
||||
match sigma >= NEGLIGIBLE_LENGTH {
|
||||
true => plane.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma }),
|
||||
false => plane,
|
||||
}
|
||||
}
|
||||
|
||||
/// A bevel's height from 0 to 1, from each pixel's signed distance to the silhouette's edge (positive inside), shaped by the `style` over `size` pixels.
|
||||
fn bevel_height(silhouette: &Plane<f32>, size: f64, style: BevelStyle) -> Plane<f32> {
|
||||
let to_inside = silhouette.distances_across_edge(size, false);
|
||||
let to_outside = silhouette.distances_across_edge(size, true);
|
||||
|
||||
// The pixels inside the silhouette are those at no distance from it, and the edge lies about half a pixel short of the nearest pixel across it
|
||||
to_inside.zip(&to_outside, |to_inside, to_outside| {
|
||||
let signed_distance = if to_inside == 0. { to_outside - 0.5 } else { 0.5 - to_inside };
|
||||
bevel_profile(signed_distance, size as f32, style)
|
||||
})
|
||||
}
|
||||
|
||||
/// The height from 0 to 1 at a signed distance from the edge (positive inside), rising smoothly across the `style`'s slope `size` pixels wide.
|
||||
fn bevel_profile(signed_distance: f32, size: f32, style: BevelStyle) -> f32 {
|
||||
let progress = match style {
|
||||
BevelStyle::InnerBevel => signed_distance / size,
|
||||
BevelStyle::OuterBevel => (signed_distance + size) / size,
|
||||
BevelStyle::Emboss => (signed_distance + size / 2.) / size,
|
||||
BevelStyle::PillowEmboss => signed_distance.abs() / (size / 2.),
|
||||
};
|
||||
let progress = progress.clamp(0., 1.);
|
||||
progress * progress * (3. - 2. * progress)
|
||||
}
|
||||
|
||||
/// How far the `light` brightens the bevel's surface past a flat surface's brightness, or if `shadow`, how far it falls short, from 0 to 1.
|
||||
/// `slope` scales the height's gradient into the surface's steepness, and is negative for a bevel pressed into the surface. O(width × height).
|
||||
fn bevel_shading(height: &Plane<f32>, slope: f64, light: DVec3, shadow: bool) -> Plane<f32> {
|
||||
let (width, rows) = (height.width as isize, height.height as isize);
|
||||
let at = |x: isize, y: isize| height.data[(y.clamp(0, rows - 1) * width + x.clamp(0, width - 1)) as usize];
|
||||
let (slope, light) = (slope as f32, light.as_vec3());
|
||||
|
||||
let mut shading = Plane::new(height.width, height.height);
|
||||
fill_rows(&mut shading.data, height.width, |y, row| {
|
||||
for (x, value) in row.iter_mut().enumerate() {
|
||||
let (x, y) = (x as isize, y as isize);
|
||||
let gradient = glam::Vec2::new(at(x + 1, y) - at(x - 1, y), at(x, y + 1) - at(x, y - 1)) / 2.;
|
||||
let shade = (-slope * gradient).extend(1.).normalize().dot(light);
|
||||
|
||||
*value = match shadow {
|
||||
true => (light.z - shade) / light.z.max(1e-4),
|
||||
false => (shade - light.z) / (1. - light.z).max(1e-4),
|
||||
}
|
||||
.clamp(0., 1.);
|
||||
}
|
||||
});
|
||||
shading
|
||||
}
|
||||
|
||||
/// Mixes the paint's color at each premultiplied gamma-encoded pixel over it by the blend mode, keeping the pixel's alpha.
|
||||
fn overlay(plane: &Plane<[f32; 4]>, paint: &[Color], blend_mode: BlendMode, opacity: f32) -> Plane<[f32; 4]> {
|
||||
let data = plane
|
||||
.data
|
||||
.iter()
|
||||
.zip(paint)
|
||||
.map(|(&pixel, &paint)| match pixel[3] > 0. {
|
||||
true => premultiplied_gamma_channels(overlay_paint(straight_linear_color(pixel), paint, blend_mode, opacity)),
|
||||
false => [0.; 4],
|
||||
})
|
||||
.collect();
|
||||
Plane {
|
||||
width: plane.width,
|
||||
height: plane.height,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples the paint's color at points in the space its placement maps into, for the paints the CPU can draw: colors, images, generators, and linear or radial gradients.
|
||||
fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync + '_>> {
|
||||
let inverse = |placement: DAffine2| (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
|
||||
|
||||
match paint {
|
||||
Graphic::Color(color) => {
|
||||
let color = *color.element();
|
||||
Some(Box::new(move |_| color))
|
||||
}
|
||||
Graphic::RasterCPU(item) => {
|
||||
let image = item.element();
|
||||
let to_pixels = DAffine2::from_scale(DVec2::new(image.width as f64, image.height as f64)) * inverse(item.attribute_cloned_or_default(ATTR_TRANSFORM))?;
|
||||
Some(Box::new(move |point| image.sample_bilinear(to_pixels.transform_point2(point))))
|
||||
}
|
||||
Graphic::Generator(item) => {
|
||||
let to_pattern = inverse(item.attribute_cloned_or_default(ATTR_TRANSFORM))?;
|
||||
let sample = pattern_sampler(&GeneratorPattern::of_item(item));
|
||||
Some(Box::new(move |point| sample(to_pattern.transform_point2(point))))
|
||||
}
|
||||
Graphic::Gradient(item) => {
|
||||
let position = gradient_position(item)?;
|
||||
let evaluator = item.element().evaluator(GradientSettings::from_item_attributes(item));
|
||||
Some(Box::new(move |point| evaluator.evaluate(position(point))))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far along a linear or radial gradient each point lies, or `None` for the other shapes its curvature dials make, which only the renderers draw.
|
||||
fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> f64 + Sync>> {
|
||||
let placement: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let preset = item.attribute_cloned_or_default::<GradientForm>(ATTR_GRADIENT_FORM).dials();
|
||||
let dial = |key: &str, preset: f64| wrapped_dial(item.attribute_cloned_or(key, preset), preset);
|
||||
|
||||
match [dial(ATTR_GRADIENT_START_CURVATURE, preset[0]), dial(ATTR_GRADIENT_END_CURVATURE, preset[1])] {
|
||||
// Measured along the line across the bands, which stay parallel to the placement's sheared y axis as the renderers draw them
|
||||
LINEAR_DIALS => {
|
||||
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>)
|
||||
}
|
||||
RADIAL_DIALS => {
|
||||
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse())?;
|
||||
Some(Box::new(move |point| to_unit.transform_point2(point).length()))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Carries out the adjustments among a color's or gradient's effects, for the nodes and paints that read the value rather than render it.
|
||||
//! A value read on its own has no pixels for the image operations among the effects (like blurs and shadows) to act on, so those are skipped.
|
||||
|
||||
use crate::adjustments::{PreparedAdjustment, adjust_color};
|
||||
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 graphic_types::adjustment::Adjustment;
|
||||
use graphic_types::effects::{EffectOperation, Effects};
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use vector_types::{Gradient, GradientInterpolation, GradientSettings, GradientSpace};
|
||||
|
||||
/// How many adjusted gradients stay cached after the renders that used them, since paints read the same ones every render.
|
||||
const MAX_CACHED_GRADIENTS: usize = 32;
|
||||
|
||||
/// The gradients adjusted most recently, least recent first, keyed by the hash of what they were adjusted from.
|
||||
static ADJUSTED_GRADIENTS: Mutex<Vec<(u64, Gradient, GradientSettings)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The adjustments among the effects, in order.
|
||||
pub fn adjustments(effects: &Effects) -> Vec<Adjustment> {
|
||||
effects
|
||||
.operations()
|
||||
.filter_map(|operation| match operation {
|
||||
EffectOperation::Adjustment(adjustment) => Some(adjustment),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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))
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` in order on any number of colors, with each one's kernel prepared once.
|
||||
fn prepared(adjustments: &[Adjustment]) -> impl Fn(Color) -> Color {
|
||||
let adjustments: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
move |color| adjustments.iter().fold(color, |color, adjustment| adjustment.adjust(color))
|
||||
}
|
||||
|
||||
/// The gradient with `adjustments` carried out along its ramp, with the settings to read the result with, or `None` if there are no adjustments.
|
||||
/// 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]) -> Option<(Gradient, GradientSettings)> {
|
||||
if adjustments.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if settings.interpolation == GradientInterpolation::Stepped {
|
||||
let adjust = prepared(adjustments);
|
||||
return Some((gradient.map_colors(|color| adjust(*color)), settings));
|
||||
}
|
||||
|
||||
// Resampling takes thousands of evaluations for a steep adjustment, so recent results are reused
|
||||
let mut hasher = DefaultHasher::new();
|
||||
gradient.cache_hash(&mut hasher);
|
||||
settings.cache_hash(&mut hasher);
|
||||
adjustments.iter().for_each(|adjustment| adjustment.cache_hash(&mut hasher));
|
||||
let key = hasher.finish();
|
||||
|
||||
// A lock poisoned by a panic elsewhere still guards a usable cache
|
||||
let mut cached = ADJUSTED_GRADIENTS.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(index) = cached.iter().position(|(cached_key, ..)| *cached_key == key) {
|
||||
let entry = cached.remove(index);
|
||||
let result = (entry.1.clone(), entry.2);
|
||||
cached.push(entry);
|
||||
return Some(result);
|
||||
}
|
||||
|
||||
let resampled = gradient.map_ramp(settings, prepared(adjustments));
|
||||
let resampled_settings = GradientSettings {
|
||||
space: GradientSpace::RgbGamma,
|
||||
interpolation: GradientInterpolation::Linear,
|
||||
hue_direction: Default::default(),
|
||||
..settings
|
||||
};
|
||||
|
||||
cached.push((key, resampled.clone(), resampled_settings));
|
||||
let excess = cached.len().saturating_sub(MAX_CACHED_GRADIENTS);
|
||||
cached.drain(..excess);
|
||||
|
||||
Some((resampled, resampled_settings))
|
||||
}
|
||||
|
||||
/// The color with the adjustments among its effects carried out and the effects consumed, for nodes that read the color.
|
||||
/// 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 {
|
||||
return item;
|
||||
};
|
||||
|
||||
let mut item = item;
|
||||
*item.element_mut() = adjusted_color(*item.element(), &adjustments);
|
||||
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.
|
||||
/// 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 settings = GradientSettings::from_item_attributes(&item);
|
||||
|
||||
let mut item = item;
|
||||
let settings = match adjusted_gradient(item.element(), settings, &adjustments) {
|
||||
Some((gradient, adjusted_settings)) => {
|
||||
*item.element_mut() = gradient;
|
||||
adjusted_settings
|
||||
}
|
||||
None => settings,
|
||||
};
|
||||
|
||||
// Which attributes come out depends only on whether the effects attribute came in, not on what it holds
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
item.set_attribute(ATTR_GRADIENT_SPACE, settings.space);
|
||||
item.set_attribute(ATTR_GRADIENT_INTERPOLATION, settings.interpolation);
|
||||
item.set_attribute(ATTR_GRADIENT_HUE_DIRECTION, settings.hue_direction);
|
||||
item
|
||||
}
|
||||
@@ -158,6 +158,39 @@ impl<P: Pixel> Image<P> {
|
||||
}
|
||||
|
||||
impl Image<Color> {
|
||||
/// The color at a point in pixel coordinates, interpolating the four nearest pixel centers by their alpha.
|
||||
/// Like the renderer draws images, it's transparent outside the image and takes the edge pixels' colors out to its edges.
|
||||
pub fn sample_bilinear(&self, point: DVec2) -> Color {
|
||||
// Also rejects NaN and far-off points before they become pixel indices
|
||||
let size = DVec2::new(self.width as f64, self.height as f64);
|
||||
if !(point.cmpge(DVec2::ZERO).all() && point.cmplt(size).all()) {
|
||||
return Color::TRANSPARENT;
|
||||
}
|
||||
|
||||
let point = point.clamp(DVec2::splat(0.5), size - 0.5);
|
||||
let corner = (point - 0.5).floor();
|
||||
let fraction = (point - 0.5 - corner).as_vec2();
|
||||
|
||||
let premultiplied_at = |offset_x: i64, offset_y: i64| {
|
||||
let (x, y) = (corner.x as i64 + offset_x, corner.y as i64 + offset_y);
|
||||
if x < 0 || y < 0 || x >= self.width as i64 || y >= self.height as i64 {
|
||||
return [0.; 4];
|
||||
}
|
||||
let color = self.data[(y * self.width as i64 + x) as usize];
|
||||
[color.r() * color.a(), color.g() * color.a(), color.b() * color.a(), color.a()]
|
||||
};
|
||||
let lerp = |a: [f32; 4], b: [f32; 4], t: f32| std::array::from_fn::<f32, 4, _>(|channel| a[channel] + (b[channel] - a[channel]) * t);
|
||||
|
||||
let top = lerp(premultiplied_at(0, 0), premultiplied_at(1, 0), fraction.x);
|
||||
let bottom = lerp(premultiplied_at(0, 1), premultiplied_at(1, 1), fraction.x);
|
||||
let [red, green, blue, alpha] = lerp(top, bottom, fraction.y);
|
||||
|
||||
match alpha > 0. {
|
||||
true => Color::from_rgbaf32_unchecked(red / alpha, green / alpha, blue / alpha, alpha),
|
||||
false => Color::TRANSPARENT,
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate Image from some frontend image data (the canvas pixels as u8s in a flat array)
|
||||
pub fn from_image_data(image_data: &[u8], width: u32, height: u32) -> Self {
|
||||
let data = image_data
|
||||
|
||||
@@ -76,7 +76,7 @@ mod cpu {
|
||||
use super::*;
|
||||
use crate::raster_types::__private::Sealed;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, OnceLock, Weak};
|
||||
use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak};
|
||||
|
||||
/// Pixels in CPU memory, shared between clones and identified by an ID that changes whenever they are modified.
|
||||
/// So cloning is a reference count increment, and hashing for caches reads the ID rather than every pixel.
|
||||
@@ -90,6 +90,8 @@ mod cpu {
|
||||
image: Image<Color>,
|
||||
/// The pixels encoded as a PNG data URL, made the first time an SVG embeds them.
|
||||
png_data_url: OnceLock<Arc<str>>,
|
||||
/// The pixels most recently derived from these, with the key they were derived for.
|
||||
derived: Mutex<Option<(u64, Raster<CPU>)>>,
|
||||
}
|
||||
|
||||
// A copy is made only to be modified, so it starts without an ID
|
||||
@@ -99,6 +101,7 @@ mod cpu {
|
||||
id: AtomicU64::new(0),
|
||||
image: self.image.clone(),
|
||||
png_data_url: OnceLock::new(),
|
||||
derived: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -200,6 +203,21 @@ mod cpu {
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Pixels derived from these by `derive` for `key`.
|
||||
/// The latest are kept with these pixels and shared by every clone, so deriving them again for the same key reuses them, ID and all.
|
||||
pub fn derived(&self, key: u64, derive: impl FnOnce(&Self) -> Raster<CPU>) -> Raster<CPU> {
|
||||
let mut derived = self.0.derived.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some((derived_key, raster)) = &*derived
|
||||
&& *derived_key == key
|
||||
{
|
||||
return raster.clone();
|
||||
}
|
||||
|
||||
let raster = derive(self);
|
||||
*derived = Some((key, raster.clone()));
|
||||
raster
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for CPU {
|
||||
@@ -211,11 +229,12 @@ mod cpu {
|
||||
}
|
||||
|
||||
impl DerefMut for CPU {
|
||||
/// Copies the pixels if another clone shares them, and drops their ID and PNG encoding since they may change.
|
||||
/// Copies the pixels if another clone shares them, and drops their ID, PNG encoding, and derived pixels since they may change.
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
let buffer = Arc::make_mut(&mut self.0);
|
||||
*buffer.id.get_mut() = 0;
|
||||
buffer.png_data_url = OnceLock::new();
|
||||
*buffer.derived.get_mut().unwrap_or_else(PoisonError::into_inner) = None;
|
||||
&mut buffer.image
|
||||
}
|
||||
}
|
||||
@@ -266,6 +285,22 @@ mod cpu {
|
||||
assert_eq!(raster.data().data.as_ptr(), pixels, "pixels nothing else shares are modified without a copy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derived_pixels_are_reused_for_the_same_key_until_the_pixels_change() {
|
||||
let mut raster = Raster::new_cpu(Image::new(2, 2, Color::BLACK));
|
||||
let derive = |_: &Raster<CPU>| Raster::new_cpu(Image::new(1, 1, Color::WHITE));
|
||||
|
||||
let first = raster.derived(1, derive);
|
||||
let again = raster.clone().derived(1, |_| panic!("the pixels derived for this key are kept"));
|
||||
assert_eq!(again.buffer_id(), first.buffer_id(), "reused pixels keep their ID");
|
||||
|
||||
let second = raster.derived(2, derive);
|
||||
assert_ne!(second.buffer_id(), first.buffer_id(), "another key derives anew");
|
||||
|
||||
raster.data_mut().data[0] = Color::WHITE;
|
||||
assert_ne!(raster.derived(2, derive).buffer_id(), second.buffer_id(), "modified pixels derive anew");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_pixels_compare_equal_whatever_their_ids() {
|
||||
let first = Raster::new_cpu(Image::new(2, 2, Color::BLACK));
|
||||
|
||||
@@ -36,7 +36,9 @@ usvg = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
parley = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
|
||||
|
||||
@@ -0,0 +1,541 @@
|
||||
//! Gradients whose two ends are each a contour dialed between a line, a circle, and a point, with the contours between
|
||||
//! them filling in as the pencil of circles the two end contours span.
|
||||
//!
|
||||
//! 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 dial
|
||||
//! `α ∈ [-1, 1]`: 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 contours between are the members of the pencil the end contours span. Each member is spaced by where it crosses
|
||||
//! the gradient line, so 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 glam::DVec2;
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
|
||||
pub use graphic_types::vector_types::gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
/// Stands in for a t of infinity, on the contours whose crossing with the gradient line is 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, dialed 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), dialed 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 pencil `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 a dialed gradient.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PencilParameters {
|
||||
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,
|
||||
}
|
||||
|
||||
impl PencilParameters {
|
||||
/// The parameters of the gradient with these two dials, which must be finite and within -1 to 1.
|
||||
pub fn new(start_dial: f64, end_dial: f64) -> Self {
|
||||
let start = AxisCircle::start(start_dial);
|
||||
let end = AxisCircle::end(end_dial);
|
||||
|
||||
// The members of the pencil 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 pencil 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.);
|
||||
}
|
||||
|
||||
// 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. Among the rest, prefer the
|
||||
// band that keeps the endpoints at t of 0 and 1.
|
||||
let limit_values = limit_points.map(|point| point.value());
|
||||
let usable = |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)] => {
|
||||
let (low, high) = (first.min(second), first.max(second));
|
||||
let beyond = |y: f64| {
|
||||
if y > high {
|
||||
1
|
||||
} else if y < low {
|
||||
-1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
// On the outer arc, crossings on opposite sides of the limit points lie across infinity from each other
|
||||
beyond(band_start) * beyond(band_end) >= 0
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
};
|
||||
let truthfulness = |band_start: Homogeneous, band_end: Homogeneous| {
|
||||
let is = |point: Homogeneous, target: f64| point.value().is_some_and(|value| (value - target).abs() < 1e-9);
|
||||
is(band_start, 0.) as u8 + is(band_end, 1.) as u8
|
||||
};
|
||||
let chosen = candidates
|
||||
.into_iter()
|
||||
.filter(|&(_, band_start, band_end)| usable(band_start, band_end))
|
||||
.max_by_key(|&(_, band_start, band_end)| truthfulness(band_start, band_end))
|
||||
.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)
|
||||
}
|
||||
|
||||
fn with_band(start: AxisCircle, end: AxisCircle, selection: CrossingSelection, wrap: Option<Wrap>, band_start: f64, band_end: f64) -> 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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, whose crossing is 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
|
||||
}
|
||||
}
|
||||
|
||||
impl PencilParameters {
|
||||
/// The same parameters for Vello GPU's pencil gradient paint.
|
||||
pub fn to_vello(&self) -> vello_gpu::PencilGeometry {
|
||||
let circle = |circle: &AxisCircle| [circle.a as f32, circle.b as f32, circle.c as f32];
|
||||
|
||||
vello_gpu::PencilGeometry {
|
||||
start: circle(&self.start),
|
||||
end: circle(&self.end),
|
||||
selection: match self.selection {
|
||||
CrossingSelection::SameSideAs { radical_x } => vello_gpu::PencilSelection::SameSideAs { radical_x: radical_x as f32 },
|
||||
CrossingSelection::OnArc { quadratic } => vello_gpu::PencilSelection::OnArc {
|
||||
quadratic: quadratic.map(|coefficient| coefficient as f32),
|
||||
},
|
||||
},
|
||||
wrap: self.wrap.map(|wrap| vello_gpu::PencilWrap {
|
||||
reference_x: wrap.reference_x as f32,
|
||||
band_side: wrap.band_side as f32,
|
||||
t: wrap.t as f32,
|
||||
}),
|
||||
t_scale: self.t_scale as f32,
|
||||
t_offset: self.t_offset as f32,
|
||||
}
|
||||
}
|
||||
|
||||
/// The closest gradient SVG can express: a radial gradient from the start circle to the end circle when one nests inside
|
||||
/// the other, or else the linear gradient along the gradient line.
|
||||
pub fn svg_approximation(&self) -> SvgApproximation {
|
||||
let (Some(start), Some(end)) = (self.start.center_and_radius(), self.end.center_and_radius()) else {
|
||||
return SvgApproximation::Linear;
|
||||
};
|
||||
|
||||
let distance = (start.0 - end.0).abs();
|
||||
let nested = distance <= (start.1 - end.1).abs();
|
||||
if !nested {
|
||||
return SvgApproximation::Linear;
|
||||
}
|
||||
|
||||
SvgApproximation::Radial {
|
||||
start_center: start.0,
|
||||
start_radius: start.1,
|
||||
end_center: end.0,
|
||||
end_radius: end.1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient SVG can draw in place of a dialed one, in gradient space.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum SvgApproximation {
|
||||
Linear,
|
||||
/// From the start circle, as SVG's focal circle, out to the end circle, both centered on the gradient line.
|
||||
Radial {
|
||||
start_center: f64,
|
||||
start_radius: f64,
|
||||
end_center: f64,
|
||||
end_radius: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl AxisCircle {
|
||||
/// Where its center sits on the gradient line, and its radius, unless it's a line.
|
||||
fn center_and_radius(&self) -> Option<(f64, f64)> {
|
||||
if self.a.abs() < 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let center = -self.b / (2. * self.a);
|
||||
let radius = (center * center - self.c / self.a).max(0.).sqrt();
|
||||
Some((center, radius))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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::*;
|
||||
|
||||
fn assert_close(actual: f64, expected: f64, context: &str) {
|
||||
assert!((actual - expected).abs() < 1e-6, "{context}: expected {expected}, got {actual}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_dials_space_contours_by_radius() {
|
||||
let parameters = PencilParameters::new(RADIAL_DIALS[0], RADIAL_DIALS[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_dials_space_contours_by_distance_along_the_line() {
|
||||
let parameters = PencilParameters::new(LINEAR_DIALS[0], LINEAR_DIALS[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_dials_space_contours_by_radius_between_the_ends() {
|
||||
// The donut: a hole of radius 1 centered 1 before the start, and an end circle of radius 2 around the same center
|
||||
let parameters = PencilParameters::new(-0.5, 0.5_f64.atan() / FRAC_PI_2);
|
||||
let center = DVec2::new(-1., 0.);
|
||||
for radius in [1., 1.25, 1.5, 2., 3.] {
|
||||
for angle in [0., 1., 2.5, 4.] {
|
||||
let point = center + DVec2::from_angle(angle) * radius;
|
||||
assert_close(parameters.t(point), radius - 1., &format!("radius {radius} at angle {angle}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_dials_space_contours_by_distance_ratio() {
|
||||
let parameters = PencilParameters::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 dials_near_a_preset_render_like_it() {
|
||||
let radial = PencilParameters::new(RADIAL_DIALS[0], RADIAL_DIALS[1]);
|
||||
let near_radial = PencilParameters::new(RADIAL_DIALS[0] - 1e-7, RADIAL_DIALS[1] + 1e-7);
|
||||
let linear = PencilParameters::new(LINEAR_DIALS[0], LINEAR_DIALS[1]);
|
||||
let near_linear = PencilParameters::new(LINEAR_DIALS[0] + 1e-7, LINEAR_DIALS[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 = PencilParameters::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 = PencilParameters::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_dial_pair_gives_a_number_everywhere() {
|
||||
for start_step in -10..=10 {
|
||||
for end_step in -10..=10 {
|
||||
let parameters = PencilParameters::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(), "dials ({start_step}, {end_step}) at {point}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod convert_usvg_path;
|
||||
pub mod dial_gradient;
|
||||
pub mod render_ext;
|
||||
mod renderer;
|
||||
pub mod to_peniko;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use crate::renderer::{
|
||||
ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_settings_from_item, spread_adjusted_samples, transform_is_invertible,
|
||||
GradientShape, ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, painted_gradient, spread_adjusted_samples, svg_gradient_definition,
|
||||
transform_is_invertible,
|
||||
};
|
||||
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;
|
||||
@@ -87,12 +87,11 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
let mut stop = String::new();
|
||||
|
||||
let item = item?;
|
||||
let stops = item.element()?;
|
||||
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
|
||||
let (stops, settings) = painted_gradient(item)?;
|
||||
let shape = GradientShape::of(item);
|
||||
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let settings = gradient_settings_from_item(item);
|
||||
|
||||
let mut samples = spread_adjusted_samples(stops, settings, gradient_form);
|
||||
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
|
||||
|
||||
let paint_opacity = item.paint_opacity(for_mask);
|
||||
if paint_opacity < 1. {
|
||||
@@ -134,7 +133,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 placement = gradient_placement(document_transform, shape);
|
||||
let gradient_transform = format_transform_matrix(element_transform_inverse * placement);
|
||||
let gradient_transform = if gradient_transform.is_empty() {
|
||||
String::new()
|
||||
@@ -149,23 +148,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
|
||||
};
|
||||
|
||||
let gradient_id = generate_uuid();
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
svg_defs.push_str(&svg_gradient_definition(shape, gradient_id, &format!("{gradient_spread}{gradient_transform}"), &stop));
|
||||
|
||||
Some(gradient_id)
|
||||
}
|
||||
@@ -285,10 +268,12 @@ impl RenderExt for Graphic {
|
||||
| Graphic::Vector(_)
|
||||
| Graphic::RasterCPU(_)
|
||||
| Graphic::RasterGPU(_)
|
||||
| Graphic::Generator(_)
|
||||
| Graphic::Text(_)
|
||||
| Graphic::VectorList(_)
|
||||
| Graphic::RasterCPUList(_)
|
||||
| Graphic::RasterGPUList(_)
|
||||
| Graphic::GeneratorList(_)
|
||||
| Graphic::GraphicList(_)
|
||||
| Graphic::GradientList(_)
|
||||
| Graphic::TextList(_)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,16 +1,32 @@
|
||||
use graphic_types::raster_types::{CPU, Raster, Texture};
|
||||
use glam::{DMat2, DVec2, UVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use graphic_types::raster_types::{CPU, ImageError, Raster, Texture};
|
||||
use graphic_types::{Adjustment, Effects};
|
||||
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::peniko::{self, BlendMode, Brush, Fill};
|
||||
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;
|
||||
|
||||
/// The texture size an effects group's area rounds up to a multiple of, so a group moving across renders keeps reusing the same pooled textures.
|
||||
const EFFECTS_SIZE_CLASS: u32 = 64;
|
||||
|
||||
/// The pixels across and down a generator's tile covers, besides the samples bordering it that let neighboring tiles overlap seamlessly.
|
||||
const GENERATOR_TILE_PIXELS: u32 = 256;
|
||||
|
||||
/// The samples bordering each side of a generator's tile, and how many of them its neighbor's drawing overlaps.
|
||||
const GENERATOR_TILE_BORDER: u32 = 2;
|
||||
const GENERATOR_TILE_OVERLAP: u32 = 1;
|
||||
|
||||
/// The most tiles one generator draws in a render, past which larger tiles render at a lower resolution, as for a view skewed far along one axis.
|
||||
const MAX_GENERATOR_TILES_PER_DRAW: f64 = 256.;
|
||||
|
||||
/// Builds a Vello GPU scene of a fixed size, recording the images it draws so the renderer can supply their textures at render time.
|
||||
#[derive(Debug)]
|
||||
pub struct VelloSceneBuilder {
|
||||
pub struct VelloSceneBuilder<'a> {
|
||||
scene: vello_gpu::Scene,
|
||||
/// Places the drawn content in the scene, applied on top of every transform it's drawn with.
|
||||
view: Affine,
|
||||
@@ -20,6 +36,67 @@ pub struct VelloSceneBuilder {
|
||||
/// The largest width or height an image's texture can have, beyond which images are drawn from a downscaled texture.
|
||||
max_texture_size: u32,
|
||||
pushed: Vec<Pushed>,
|
||||
/// Renders effects groups as they're drawn. A scene drawn ahead of its render has none, so it draws effects groups without their effects.
|
||||
effects_renderer: Option<&'a mut dyn EffectsRenderer>,
|
||||
}
|
||||
|
||||
/// Renders the content of a scene's effects groups offscreen and carries out their effects, while the scene is drawn.
|
||||
pub trait EffectsRenderer: Send {
|
||||
/// Whether the GPU can carry out effects, without which effects groups draw their content faded by their fill.
|
||||
fn renders_effects(&self) -> bool;
|
||||
|
||||
/// Renders the content `draw` draws, and each paint overlay's paint `draw_paint` draws by index, placed by `view` in premultiplied textures of `size`, returning one with `effects` carried out.
|
||||
/// `lengths_to_pixels` maps the effects' lengths onto the texture's pixels, and `fill` fades the content but not the shadows and glows cast from it.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_effects(
|
||||
&mut self,
|
||||
size: UVec2,
|
||||
view: Affine,
|
||||
effects: &Effects,
|
||||
fill: f32,
|
||||
lengths_to_pixels: DMat2,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) -> wgpu::Texture;
|
||||
}
|
||||
|
||||
/// What a fill or stroke paints with.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SceneBrush {
|
||||
/// A solid color, gradient, or image.
|
||||
Peniko(Brush),
|
||||
/// A gradient whose contours are a pencil of circles, which only Vello GPU's fork can draw.
|
||||
PencilGradient(PencilGradient),
|
||||
}
|
||||
|
||||
impl From<Brush> for SceneBrush {
|
||||
fn from(brush: Brush) -> Self {
|
||||
Self::Peniko(brush)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Brush> for SceneBrush {
|
||||
fn from(brush: &Brush) -> Self {
|
||||
Self::Peniko(brush.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<peniko::Color> for SceneBrush {
|
||||
fn from(color: peniko::Color) -> Self {
|
||||
Self::Peniko(Brush::Solid(color))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&peniko::Gradient> for SceneBrush {
|
||||
fn from(gradient: &peniko::Gradient) -> Self {
|
||||
Self::Peniko(Brush::Gradient(gradient.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PencilGradient> for SceneBrush {
|
||||
fn from(gradient: PencilGradient) -> Self {
|
||||
Self::PencilGradient(gradient)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels behind an image the scene draws.
|
||||
@@ -28,9 +105,14 @@ pub enum SceneImage {
|
||||
/// Straight-alpha RGBA8 pixels in CPU memory, identified by their blob's ID so the renderer uploads them once.
|
||||
Pixels(peniko::ImageData),
|
||||
/// A CPU raster's straight-alpha linear pixels, identified by their buffer's ID so the renderer uploads them once.
|
||||
Raster(Raster<CPU>),
|
||||
/// The adjustments, if any, are carried out on its pixels before they are sampled.
|
||||
Raster { raster: Raster<CPU>, adjustments: Vec<Adjustment> },
|
||||
/// Straight-alpha pixels in a GPU texture.
|
||||
Texture(Texture),
|
||||
/// Premultiplied pixels of an effects group's result, rendered for this scene.
|
||||
Rendered(wgpu::Texture),
|
||||
/// One tile of a generator's pattern, rendered on the CPU the first time it's drawn.
|
||||
GeneratorTile { pattern: GeneratorPattern, tile: GeneratorTile },
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
|
||||
@@ -38,6 +120,37 @@ enum ImageKey {
|
||||
Blob(u64),
|
||||
Raster(u64),
|
||||
Texture(Texture),
|
||||
Rendered(wgpu::Texture),
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
/// One tile of a generator's pattern, from a grid in the pattern's space whose tiles span a power of two of units.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
pub struct GeneratorTile {
|
||||
/// Identifies the pattern by the hash of its settings.
|
||||
pub pattern: u64,
|
||||
/// The tiles span `2^-level` units, so a tile is about the same number of pixels in view at any zoom.
|
||||
pub level: i32,
|
||||
pub column: i64,
|
||||
pub row: i64,
|
||||
}
|
||||
|
||||
impl GeneratorTile {
|
||||
/// The samples across and down the tile and its border.
|
||||
pub const SAMPLES: u32 = GENERATOR_TILE_PIXELS + 2 * GENERATOR_TILE_BORDER;
|
||||
|
||||
/// The pattern's pixels across the tile and its border, rendered on the CPU.
|
||||
pub fn render(&self, pattern: &GeneratorPattern) -> Result<Raster<CPU>, ImageError> {
|
||||
let (corner, texel) = self.corner_and_texel();
|
||||
raster_kernels::generators::render_pattern(pattern, [corner, corner + DVec2::splat(Self::SAMPLES as f64 * texel)], Self::SAMPLES, Self::SAMPLES).map(Raster::new_cpu)
|
||||
}
|
||||
|
||||
/// The corner of the tile's samples, including its border, in the pattern's space, and the span of one sample.
|
||||
pub fn corner_and_texel(&self) -> (DVec2, f64) {
|
||||
let span = 2_f64.powi(-self.level);
|
||||
let texel = span / GENERATOR_TILE_PIXELS as f64;
|
||||
(DVec2::new(self.column as f64, self.row as f64) * span - GENERATOR_TILE_BORDER as f64 * texel, texel)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -46,7 +159,17 @@ enum Pushed {
|
||||
Clip,
|
||||
}
|
||||
|
||||
impl VelloSceneBuilder {
|
||||
impl std::fmt::Debug for VelloSceneBuilder<'_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("VelloSceneBuilder")
|
||||
.field("scene", &self.scene)
|
||||
.field("view", &self.view)
|
||||
.field("images", &self.images)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> VelloSceneBuilder<'a> {
|
||||
pub fn new(width: u16, height: u16, view: Affine, max_texture_size: u32) -> Self {
|
||||
Self::from_vello(vello_gpu::Scene::new(width, height), view, max_texture_size)
|
||||
}
|
||||
@@ -61,9 +184,16 @@ impl VelloSceneBuilder {
|
||||
image_ids: HashMap::new(),
|
||||
max_texture_size,
|
||||
pushed: Vec::new(),
|
||||
effects_renderer: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders the effects groups drawn into the scene through `renderer`.
|
||||
pub fn with_effects_renderer(mut self, renderer: &'a mut dyn EffectsRenderer) -> Self {
|
||||
self.effects_renderer = Some(renderer);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn width(&self) -> u16 {
|
||||
self.scene.width()
|
||||
}
|
||||
@@ -102,35 +232,32 @@ impl VelloSceneBuilder {
|
||||
}
|
||||
|
||||
/// 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(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush>, 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(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, path: &BezPath) {
|
||||
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(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||
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(&mut self, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>) {
|
||||
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));
|
||||
}
|
||||
@@ -175,9 +302,9 @@ impl VelloSceneBuilder {
|
||||
self.draw_image_source(source, image.sampler, transform * texture_to_image, texture_size);
|
||||
}
|
||||
|
||||
/// Draws a CPU raster's rectangle of pixels, from the origin to its width and height, placed by `transform`.
|
||||
pub fn draw_raster(&mut self, raster: Raster<CPU>, sampler: peniko::ImageSampler, transform: Affine) {
|
||||
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Raster(raster)) else {
|
||||
/// 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) {
|
||||
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Raster { raster, adjustments }) else {
|
||||
return;
|
||||
};
|
||||
self.draw_image_source(source, sampler, transform * texture_to_image, texture_size);
|
||||
@@ -191,6 +318,115 @@ impl VelloSceneBuilder {
|
||||
self.draw_image_source(source, sampler, transform * texture_to_image, texture_size);
|
||||
}
|
||||
|
||||
/// Draws a generator's pattern, whose own space `transform` places, across the part of the scene it covers as tiles the renderer makes the first time each is seen.
|
||||
/// The tiles span a power of two of the pattern's units, so a pan reuses them, as does a zoom until the scale nears the next power.
|
||||
pub fn draw_generator(&mut self, pattern: &GeneratorPattern, transform: Affine) {
|
||||
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() {
|
||||
return;
|
||||
}
|
||||
|
||||
// The part of the pattern's space in view
|
||||
let viewport = Rect::new(0., 0., self.width() as f64, self.height() as f64);
|
||||
let visible = local_to_device.inverse().transform_rect_bbox(viewport);
|
||||
if visible.width() <= 0. || visible.height() <= 0. {
|
||||
return;
|
||||
}
|
||||
|
||||
// The tile size nearest to a tile's pixels in view, grown if the view would otherwise need too many
|
||||
let pixels_per_unit = determinant.abs().sqrt();
|
||||
let tile_span = |level: i32| 2_f64.powi(-level);
|
||||
let tile_range = |start: f64, end: f64, span: f64| (start / span).floor() as i64..(end / span).ceil() as i64;
|
||||
let tile_count = |level: i32| {
|
||||
let span = tile_span(level);
|
||||
(tile_range(visible.x0, visible.x1, span).count() * tile_range(visible.y0, visible.y1, span).count()) as f64
|
||||
};
|
||||
let mut level = (pixels_per_unit / GENERATOR_TILE_PIXELS as f64).log2().round() as i32;
|
||||
while tile_count(level) > MAX_GENERATOR_TILES_PER_DRAW {
|
||||
level -= 1;
|
||||
}
|
||||
let span = tile_span(level);
|
||||
|
||||
let mut hasher = std::hash::DefaultHasher::new();
|
||||
pattern.cache_hash(&mut hasher);
|
||||
let pattern_hash = std::hash::Hasher::finish(&hasher);
|
||||
|
||||
let (border, overlap) = (GENERATOR_TILE_BORDER as f64, GENERATOR_TILE_OVERLAP as f64);
|
||||
for row in tile_range(visible.y0, visible.y1, span) {
|
||||
for column in tile_range(visible.x0, visible.x1, span) {
|
||||
let tile = GeneratorTile {
|
||||
pattern: pattern_hash,
|
||||
level,
|
||||
column,
|
||||
row,
|
||||
};
|
||||
let id = *self.image_ids.entry(ImageKey::GeneratorTile(tile)).or_insert_with(|| {
|
||||
self.images.push(SceneImage::GeneratorTile { pattern: pattern.clone(), tile });
|
||||
TextureId(self.images.len() as u64 - 1)
|
||||
});
|
||||
|
||||
// Drawn across the tile and part of its border, overlapping its neighbors' identical samples so no seam shows between them
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
self.scene.set_transform(local_to_device * Affine::translate((corner.x, corner.y)) * Affine::scale(texel));
|
||||
self.scene.set_paint(PaintType::Image(Image {
|
||||
image: ImageSource::external_texture(id, TextureRegion::Full, true),
|
||||
sampler: peniko::ImageSampler::new(),
|
||||
}));
|
||||
self.scene.set_paint_transform(Affine::IDENTITY);
|
||||
let (start, end) = (border - overlap, border + GENERATOR_TILE_PIXELS as f64 + overlap);
|
||||
self.scene.fill_rect(&Rect::new(start, start, end, end));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the content `draw` draws with `effects` carried out on it, within `bounds` in the space of the drawn content (or everywhere for `None`), drawing again for each part of a split render.
|
||||
/// `draw_paint` draws each paint overlay's paint by its index among them, and `fill` fades the content but not the shadows and glows cast from it.
|
||||
pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option<Rect>, draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder)) {
|
||||
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) {
|
||||
self.push_viewport_layer(peniko::Mix::Normal, fill);
|
||||
draw(self);
|
||||
self.pop_layer();
|
||||
return;
|
||||
}
|
||||
|
||||
let [a, b, c, d, _, _] = self.view.as_coeffs();
|
||||
let lengths_to_device = DMat2::from_cols_array(&[a, b, c, d]);
|
||||
let reach = effects.reach() * lengths_to_device.determinant().abs().sqrt();
|
||||
|
||||
// The content reaching into the viewport, rounded out to whole pixels
|
||||
let viewport = Rect::new(0., 0., self.width() as f64, self.height() as f64);
|
||||
let content_bounds = bounds.map_or(viewport, |bounds| self.view.transform_rect_bbox(bounds));
|
||||
let region = content_bounds.inflate(reach, reach).intersect(viewport.inflate(reach, reach)).expand();
|
||||
if !(region.width() > 0. && region.height() > 0.) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A region too large for one texture 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 max_size = self.max_texture_size.min(u16::MAX as u32);
|
||||
let resolution = (max_size as f64 / region.width().max(region.height())).min(1.);
|
||||
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();
|
||||
|
||||
let content_view = Affine::scale(resolution) * Affine::translate(-origin) * self.view;
|
||||
let Some(renderer) = self.effects_renderer.as_deref_mut() else { return };
|
||||
let result = renderer.render_effects(size, content_view, effects, fill, lengths_to_device * resolution, draw_paint, draw);
|
||||
|
||||
// Draw the result where the content was
|
||||
self.images.push(SceneImage::Rendered(result));
|
||||
let id = TextureId(self.images.len() as u64 - 1);
|
||||
self.scene.set_transform(Affine::translate(origin) * Affine::scale(1. / resolution));
|
||||
self.scene.set_paint(PaintType::Image(Image {
|
||||
image: ImageSource::external_texture(id, TextureRegion::Full, true),
|
||||
sampler: peniko::ImageSampler::new(),
|
||||
}));
|
||||
self.scene.set_paint_transform(Affine::IDENTITY);
|
||||
self.scene.fill_rect(&Rect::new(0., 0., size.x as f64, size.y as f64));
|
||||
}
|
||||
|
||||
fn draw_image_source(&mut self, source: ImageSource, sampler: peniko::ImageSampler, transform: Affine, (width, height): (u32, u32)) {
|
||||
self.scene.set_transform(self.view * transform);
|
||||
self.scene.set_paint(PaintType::Image(Image { image: source, sampler }));
|
||||
@@ -198,44 +434,64 @@ impl VelloSceneBuilder {
|
||||
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 brush = match brush {
|
||||
SceneBrush::Peniko(brush) => brush,
|
||||
SceneBrush::PencilGradient(gradient) => {
|
||||
self.scene.set_pencil_gradient_paint(gradient);
|
||||
return Some(Affine::IDENTITY);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let (paint, paint_to_brush) = match brush {
|
||||
Brush::Solid(color) => (PaintType::Solid(color), Affine::IDENTITY),
|
||||
Brush::Gradient(gradient) => (PaintType::Gradient(gradient), Affine::IDENTITY),
|
||||
Brush::Image(image) => {
|
||||
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image))?;
|
||||
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.
|
||||
fn image_source(&mut self, image: SceneImage) -> Option<(ImageSource, Affine, (u32, u32))> {
|
||||
let (width, height) = match &image {
|
||||
SceneImage::Pixels(data) => (data.width, data.height),
|
||||
SceneImage::Raster(raster) => (raster.width, raster.height),
|
||||
SceneImage::Raster { raster, .. } => (raster.width, raster.height),
|
||||
SceneImage::Texture(texture) => (texture.width(), texture.height()),
|
||||
SceneImage::Rendered(texture) => (texture.width(), texture.height()),
|
||||
SceneImage::GeneratorTile { .. } => (GeneratorTile::SAMPLES, GeneratorTile::SAMPLES),
|
||||
};
|
||||
if width == 0 || height == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Adjusted rasters aren't shared, since the same pixels can be drawn with different adjustments
|
||||
let key = match &image {
|
||||
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
|
||||
SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::Texture(texture) => ImageKey::Texture(texture.clone()),
|
||||
SceneImage::Pixels(data) => Some(ImageKey::Blob(data.data.id())),
|
||||
SceneImage::Raster { raster, adjustments } if adjustments.is_empty() => Some(ImageKey::Raster(raster.buffer_id())),
|
||||
SceneImage::Raster { .. } => None,
|
||||
SceneImage::Texture(texture) => Some(ImageKey::Texture(texture.clone())),
|
||||
SceneImage::Rendered(texture) => Some(ImageKey::Rendered(texture.clone())),
|
||||
SceneImage::GeneratorTile { tile, .. } => Some(ImageKey::GeneratorTile(*tile)),
|
||||
};
|
||||
let images = &mut self.images;
|
||||
let mut add_image = move |image| {
|
||||
images.push(image);
|
||||
TextureId(images.len() as u64 - 1)
|
||||
};
|
||||
let id = match key {
|
||||
Some(key) => *self.image_ids.entry(key).or_insert_with(|| add_image(image)),
|
||||
None => add_image(image),
|
||||
};
|
||||
let id = *self.image_ids.entry(key).or_insert_with(|| {
|
||||
self.images.push(image);
|
||||
TextureId(self.images.len() as u64 - 1)
|
||||
});
|
||||
|
||||
let (texture_width, texture_height) = image_texture_size(width, height, self.max_texture_size);
|
||||
let texture_to_image = Affine::scale_non_uniform(width as f64 / texture_width as f64, height as f64 / texture_height as f64);
|
||||
|
||||
@@ -17,6 +17,26 @@ pub enum GradientForm {
|
||||
Radial,
|
||||
}
|
||||
|
||||
/// The curvature dials of the linear form: both ends are lines.
|
||||
pub const LINEAR_DIALS: [f64; 2] = [0., 0.];
|
||||
/// The curvature dials of the radial form: the start is a point at the center, and the end is the circle around it through the end point.
|
||||
pub const RADIAL_DIALS: [f64; 2] = [1., 0.5];
|
||||
|
||||
impl GradientForm {
|
||||
/// The curvature dials of the start and end contours that make this form.
|
||||
pub fn dials(self) -> [f64; 2] {
|
||||
match self {
|
||||
Self::Linear => LINEAR_DIALS,
|
||||
Self::Radial => RADIAL_DIALS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A curvature dial wrapped into the range ending at 1, since -1 and 1 are both the end's own point, or `preset` if it isn't finite.
|
||||
pub fn wrapped_dial(dial: f64, preset: f64) -> f64 {
|
||||
if dial.is_finite() { 1. - (1. - dial).rem_euclid(2.) } else { 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`).
|
||||
@@ -1405,6 +1425,61 @@ impl Gradient {
|
||||
mapped
|
||||
}
|
||||
|
||||
/// The ramp of `map` applied along this gradient's ramp, as stops that interpolate linearly in gamma sRGB to within [`SAMPLE_THRESHOLD`]
|
||||
/// 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 {
|
||||
/// 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;
|
||||
|
||||
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
|
||||
let deviates = [0.25, 0.5, 0.75].into_iter().any(|fraction| {
|
||||
let probe = ramp(left + (right - left) * fraction);
|
||||
max_gamma_channel_deviation(probe, color_left.lerp_gamma_srgb(&color_right, fraction as f32)) > SAMPLE_THRESHOLD
|
||||
});
|
||||
if !deviates || depth >= MAX_DEPTH {
|
||||
return;
|
||||
}
|
||||
|
||||
let mid = (left + right) / 2.;
|
||||
let color_mid = ramp(mid);
|
||||
subdivide(ramp, left, mid, color_left, color_mid, result, depth + 1);
|
||||
result.push(GradientStop {
|
||||
position: mid,
|
||||
midpoint: 0.5,
|
||||
color: color_mid,
|
||||
});
|
||||
subdivide(ramp, mid, right, color_mid, color_right, result, depth + 1);
|
||||
}
|
||||
|
||||
let stops = self.normalized_stops(settings.cyclic);
|
||||
let evaluator = self.evaluator(settings);
|
||||
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();
|
||||
if settings.cyclic && anchors.first().is_some_and(|&(position, _)| position > 0.) {
|
||||
anchors.insert(0, (0., ramp(0.)));
|
||||
}
|
||||
if settings.cyclic && anchors.last().is_some_and(|&(position, _)| position < 1.) {
|
||||
anchors.push((1., ramp(0.)));
|
||||
}
|
||||
|
||||
let mut result = Vec::new();
|
||||
for (index, &(position, color)) in anchors.iter().enumerate() {
|
||||
result.push(GradientStop { position, midpoint: 0.5, color });
|
||||
|
||||
if let Some(&(next_position, next_color)) = anchors.get(index + 1)
|
||||
&& next_position > position
|
||||
{
|
||||
subdivide(&ramp, position, next_position, color, next_color, &mut result, 0);
|
||||
}
|
||||
}
|
||||
|
||||
Gradient::new(result)
|
||||
}
|
||||
|
||||
/// The gradient's [`Gradient::interpolated_samples`], falling back to one black sample when it has no stops, since a
|
||||
/// stopless SVG gradient paints nothing where [`Gradient::evaluate`] gives black.
|
||||
pub fn interpolated_samples_or_black(&self, settings: GradientSettings) -> Vec<(f64, Color, Option<f64>)> {
|
||||
@@ -2225,6 +2300,32 @@ mod tests {
|
||||
assert_eq!((last.0, last.1), (1., Color::WHITE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_ramp_follows_the_map_and_keeps_hard_stops() {
|
||||
let gamma = GradientSettings {
|
||||
space: GradientSpace::RgbGamma,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Thresholding at middle gray needs samples beside the jump, where the two stops alone would blend from black to white
|
||||
let threshold = |color: Color| if color.to_gamma_srgb_channels()[0] < 0.5 { Color::BLACK } else { Color::WHITE };
|
||||
let mapped = Gradient::from(vec![Color::BLACK, Color::WHITE]).map_ramp(gamma, threshold);
|
||||
for t in [0.1, 0.4, 0.48] {
|
||||
assert_eq!(mapped.evaluate(t, gamma), Color::BLACK, "below the threshold at {t}");
|
||||
}
|
||||
for t in [0.52, 0.6, 0.9] {
|
||||
assert_eq!(mapped.evaluate(t, gamma), Color::WHITE, "above the threshold at {t}");
|
||||
}
|
||||
|
||||
// Coincident stops keep their jump, and a map that changes nothing adds no stops
|
||||
let mut hard = Gradient::from(vec![Color::RED, Color::RED, Color::BLUE, Color::BLUE]);
|
||||
hard.set_positions(&[0., 0.5, 0.5, 1.]);
|
||||
let unchanged = hard.map_ramp(gamma, |color| color);
|
||||
assert_eq!(unchanged.len(), 4);
|
||||
assert_eq!(unchanged.evaluate(0.49, gamma), Color::RED);
|
||||
assert_eq!(unchanged.evaluate(0.51, gamma), Color::BLUE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_space_densifies_samples_where_gamma_segments_deviate() {
|
||||
let gradient = Gradient::from(vec![Color::BLACK, Color::WHITE]);
|
||||
|
||||
@@ -16,6 +16,8 @@ workspace = true
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
raster-types = { workspace = true, features = ["wgpu"] }
|
||||
graphene-application-io = { workspace = true, features = ["wgpu"] }
|
||||
rendering = { workspace = true }
|
||||
@@ -33,3 +35,4 @@ web-sys = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
half = { workspace = true }
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,8 @@ mod context;
|
||||
mod pipeline;
|
||||
mod texture_cache;
|
||||
pub mod texture_conversion;
|
||||
mod vello_effects;
|
||||
mod vello_generators;
|
||||
mod vello_render;
|
||||
|
||||
use crate::texture_cache::TextureCache;
|
||||
@@ -177,7 +179,7 @@ impl WgpuExecutor {
|
||||
}
|
||||
|
||||
pub fn with_context(context: WgpuContext) -> Option<Self> {
|
||||
let vello_renderer = VelloRenderer::new(&context.device);
|
||||
let vello_renderer = VelloRenderer::new(&context.device, &context.adapter);
|
||||
|
||||
let texture_cache = TextureCache::new(TEXTURE_CACHE_SIZE);
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,666 @@
|
||||
// The passes that carry out an item's effects on the pixels of its content, which are premultiplied with gamma-encoded color like the pixels Vello GPU blends
|
||||
|
||||
struct Parameters {
|
||||
// Converts a target pixel's position into the normalized coordinates the inputs are sampled at
|
||||
target_to_uv: vec2<f32>,
|
||||
// One step along the axis a kernel runs, in normalized coordinates
|
||||
step: vec2<f32>,
|
||||
// How far a silhouette is cast, in normalized coordinates
|
||||
offset: vec2<f32>,
|
||||
// The factor the scale pass multiplies by
|
||||
amount: f32,
|
||||
tap_count: u32,
|
||||
// The premultiplied color a silhouette is tinted
|
||||
color: vec4<f32>,
|
||||
// The extra constants a pass needs beyond the fields above
|
||||
values: vec4<f32>,
|
||||
// Each kernel tap's distance in steps (x) and weight (y)
|
||||
taps: array<vec4<f32>, 25>,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var source: texture_2d<f32>;
|
||||
@group(0) @binding(1) var secondary: texture_2d<f32>;
|
||||
@group(0) @binding(2) var content: texture_2d<f32>;
|
||||
@group(0) @binding(3) var linear_sampler: sampler;
|
||||
@group(0) @binding(4) var<uniform> parameters: Parameters;
|
||||
|
||||
// One triangle that covers the whole target
|
||||
@vertex
|
||||
fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
|
||||
let corner = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u));
|
||||
return vec4<f32>(corner * 2. - 1., 0., 1.);
|
||||
}
|
||||
|
||||
fn sample_source(uv: vec2<f32>) -> vec4<f32> {
|
||||
return textureSampleLevel(source, linear_sampler, uv, 0.);
|
||||
}
|
||||
|
||||
// A separable kernel along one axis, whose taps sit between texels to weight two of them at once
|
||||
@fragment
|
||||
fn convolve(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let uv = position.xy * parameters.target_to_uv;
|
||||
|
||||
var sum = vec4<f32>(0.);
|
||||
for (var i = 0u; i < parameters.tap_count; i++) {
|
||||
let tap = parameters.taps[i];
|
||||
sum += sample_source(uv + parameters.step * tap.x) * tap.y;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
// Halving a texture samples the corner shared by each block of four texels, averaging them, and doubling it interpolates between texels
|
||||
@fragment
|
||||
fn resample(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return sample_source(position.xy * parameters.target_to_uv);
|
||||
}
|
||||
|
||||
// Grows the shapes by one step along an axis, so steps that double each time grow them by any distance in a few passes
|
||||
@fragment
|
||||
fn dilate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let uv = position.xy * parameters.target_to_uv;
|
||||
return max(sample_source(uv), max(sample_source(uv - parameters.step), sample_source(uv + parameters.step)));
|
||||
}
|
||||
|
||||
// The coverage of the content's silhouette, shifted by the offset
|
||||
@fragment
|
||||
fn cast_silhouette(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(sample_source(position.xy * parameters.target_to_uv - parameters.offset).a);
|
||||
}
|
||||
|
||||
// The coverage of the area outside the content's silhouette, shifted by the offset
|
||||
@fragment
|
||||
fn cast_inverse_silhouette(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(1. - sample_source(position.xy * parameters.target_to_uv - parameters.offset).a);
|
||||
}
|
||||
|
||||
// The coverage of where a silhouette doesn't reach, which turns an inner glow from the edges into one from the center
|
||||
@fragment
|
||||
fn invert_coverage(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(1. - textureLoad(source, vec2<i32>(position.xy), 0).r);
|
||||
}
|
||||
|
||||
// Satin's shading from two casts of the silhouette: how much one covers without the other, or how much they agree with `amount` 1
|
||||
@fragment
|
||||
fn satin(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let difference = abs(textureLoad(source, pixel, 0).r - textureLoad(secondary, pixel, 0).r);
|
||||
return vec4<f32>(select(difference, 1. - difference, parameters.amount > 0.5));
|
||||
}
|
||||
|
||||
// Jump flooding keeps each texel's offset to the nearest seed found so far (xy) and whether one is found (z).
|
||||
// The seeds are the texels inside the content's silhouette, or outside it with `amount` 1, and each is its own nearest.
|
||||
@fragment
|
||||
fn jump_flood_seed(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let inside = textureLoad(source, vec2<i32>(position.xy), 0).a >= 0.5;
|
||||
let seed = inside != (parameters.amount > 0.5);
|
||||
return vec4<f32>(0., 0., select(0., 1., seed), 0.);
|
||||
}
|
||||
|
||||
// Takes the nearest of the seeds that the texel and its eight neighbors `values.x` texels away have found so far
|
||||
@fragment
|
||||
fn jump_flood_step(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let size = vec2<i32>(textureDimensions(source));
|
||||
let step = i32(parameters.values.x);
|
||||
|
||||
var best = textureLoad(source, pixel, 0);
|
||||
for (var neighbor_y = -1; neighbor_y <= 1; neighbor_y++) {
|
||||
for (var neighbor_x = -1; neighbor_x <= 1; neighbor_x++) {
|
||||
let direction = vec2<i32>(neighbor_x, neighbor_y);
|
||||
let neighbor = pixel + direction * step;
|
||||
if any(neighbor < vec2<i32>(0)) || any(neighbor >= size) {
|
||||
continue;
|
||||
}
|
||||
let found = textureLoad(source, neighbor, 0);
|
||||
if found.z < 0.5 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let candidate = found.xy + vec2<f32>(direction * step);
|
||||
if best.z < 0.5 || dot(candidate, candidate) < dot(best.xy, best.xy) {
|
||||
best = vec4<f32>(candidate, 1., 0.);
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// Covers the texels within `values.x` texels of the edge, which lies about half a texel short of the nearest seed, fading out over one texel
|
||||
@fragment
|
||||
fn edge_band(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let nearest = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if nearest.z < 0.5 {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
return vec4<f32>(clamp(parameters.values.x + 1. - length(nearest.xy), 0., 1.));
|
||||
}
|
||||
|
||||
// A bevel's height from 0 to 1, shaped by the style in `values.y` over a slope `values.x` texels wide, from the nearest texels inside (source) and outside (secondary)
|
||||
@fragment
|
||||
fn bevel_height(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let to_inside = textureLoad(source, pixel, 0);
|
||||
let to_outside = textureLoad(secondary, pixel, 0);
|
||||
let size = parameters.values.x;
|
||||
|
||||
// Texels inside the silhouette are those at no distance from it, and the edge lies about half a texel short of the nearest texel across it
|
||||
let far = 4. * size + 4.;
|
||||
var signed_distance: f32;
|
||||
if to_inside.z > 0.5 && dot(to_inside.xy, to_inside.xy) == 0. {
|
||||
signed_distance = select(far, length(to_outside.xy) - 0.5, to_outside.z > 0.5);
|
||||
} else {
|
||||
signed_distance = select(-far, 0.5 - length(to_inside.xy), to_inside.z > 0.5);
|
||||
}
|
||||
|
||||
var progress: f32;
|
||||
switch u32(parameters.values.y) {
|
||||
case 0u: {
|
||||
progress = signed_distance / size;
|
||||
}
|
||||
case 1u: {
|
||||
progress = (signed_distance + size) / size;
|
||||
}
|
||||
case 2u: {
|
||||
progress = (signed_distance + size / 2.) / size;
|
||||
}
|
||||
default: {
|
||||
progress = abs(signed_distance) / (size / 2.);
|
||||
}
|
||||
}
|
||||
let height = clamp(progress, 0., 1.);
|
||||
return vec4<f32>(height * height * (3. - 2. * height));
|
||||
}
|
||||
|
||||
fn height_at(pixel: vec2<i32>) -> f32 {
|
||||
return textureLoad(source, clamp(pixel, vec2<i32>(0), vec2<i32>(textureDimensions(source)) - 1), 0).r;
|
||||
}
|
||||
|
||||
// How far the light toward `values.yzw` brightens the bevel's surface past a flat surface's brightness, or with `amount` 1, how far it falls short.
|
||||
// `values.x` scales the height's gradient into the surface's steepness, and is negative for a bevel pressed into the surface.
|
||||
@fragment
|
||||
fn bevel_shading(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let gradient = vec2<f32>(
|
||||
height_at(pixel + vec2<i32>(1, 0)) - height_at(pixel - vec2<i32>(1, 0)),
|
||||
height_at(pixel + vec2<i32>(0, 1)) - height_at(pixel - vec2<i32>(0, 1)),
|
||||
) / 2.;
|
||||
let light = parameters.values.yzw;
|
||||
let shade = dot(normalize(vec3<f32>(-parameters.values.x * gradient, 1.)), light);
|
||||
|
||||
if parameters.amount > 0.5 {
|
||||
return vec4<f32>(clamp((light.z - shade) / max(light.z, 1e-4), 0., 1.));
|
||||
}
|
||||
return vec4<f32>(clamp((shade - light.z) / max(1. - light.z, 1e-4), 0., 1.));
|
||||
}
|
||||
|
||||
// A silhouette's coverage in its color
|
||||
@fragment
|
||||
fn tint(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return parameters.color * textureLoad(source, vec2<i32>(position.xy), 0).r;
|
||||
}
|
||||
|
||||
// Stacks a tinted silhouette over the shadows and glows beneath the content
|
||||
@fragment
|
||||
fn accumulate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let beneath = textureLoad(source, pixel, 0);
|
||||
let tinted = parameters.color * textureLoad(secondary, pixel, 0).r;
|
||||
|
||||
return tinted + beneath * (1. - tinted.a);
|
||||
}
|
||||
|
||||
// Places a tinted silhouette over the image, within the content at full strength so it stays visible over a faded fill
|
||||
@fragment
|
||||
fn composite_within(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let image = textureLoad(source, pixel, 0);
|
||||
let tinted = parameters.color * textureLoad(secondary, pixel, 0).r;
|
||||
let full_content = textureLoad(content, pixel, 0);
|
||||
|
||||
return tinted * full_content.a + image * (1. - tinted.a);
|
||||
}
|
||||
|
||||
// Places the shadows and glows beneath the image, knocked out by the content at full strength so a faded fill doesn't reveal them
|
||||
@fragment
|
||||
fn composite_beneath(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let image = textureLoad(source, pixel, 0);
|
||||
let beneath = textureLoad(secondary, pixel, 0);
|
||||
let full_content = textureLoad(content, pixel, 0);
|
||||
|
||||
return image + beneath * (1. - full_content.a);
|
||||
}
|
||||
|
||||
// The image (source) with the paint (secondary input) mixed over its colors by the blend mode in `values.x`, as much as the paint's alpha times `amount`, keeping the image's alpha
|
||||
@fragment
|
||||
fn paint_overlay(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let image = textureLoad(source, pixel, 0);
|
||||
let paint = textureLoad(secondary, pixel, 0);
|
||||
if image.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
if paint.a <= 0. {
|
||||
return image;
|
||||
}
|
||||
|
||||
// The blend modes work on straight linear colors, as the CPU's do
|
||||
let backdrop = srgb_to_linear(image.rgb / image.a);
|
||||
let blended = blend(backdrop, srgb_to_linear(paint.rgb / paint.a), u32(parameters.values.x));
|
||||
let mixed = mix(backdrop, blended, parameters.amount * paint.a);
|
||||
|
||||
return vec4<f32>(linear_to_srgb(mixed) * image.a, image.a);
|
||||
}
|
||||
|
||||
// The paint mixed with the backdrop by a blend mode, numbered in the order `BlendMode` declares them, matching `apply_blend_mode`
|
||||
fn blend(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> {
|
||||
let average = vec3<f32>(1. / 3.);
|
||||
switch mode {
|
||||
// Darker Color and Lighter Color keep whichever whole color has the lower or higher mean
|
||||
case 5u: {
|
||||
return select(paint, backdrop, dot(backdrop, average) <= dot(paint, average));
|
||||
}
|
||||
case 10u: {
|
||||
return select(paint, backdrop, dot(backdrop, average) >= dot(paint, average));
|
||||
}
|
||||
// The component modes are defined on gamma-encoded channels
|
||||
case 22u, 23u, 24u, 25u: {
|
||||
return srgb_to_linear(blend_components(clamp(linear_to_srgb(backdrop), vec3<f32>(0.), vec3<f32>(1.)), clamp(linear_to_srgb(paint), vec3<f32>(0.), vec3<f32>(1.)), mode));
|
||||
}
|
||||
default: {
|
||||
return vec3<f32>(blend_channel(backdrop.r, paint.r, mode), blend_channel(backdrop.g, paint.g, mode), blend_channel(backdrop.b, paint.b, mode));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One channel mixed by a separable blend mode, clamped to 0 to 1
|
||||
fn blend_channel(backdrop: f32, paint: f32, mode: u32) -> f32 {
|
||||
var result: f32;
|
||||
switch mode {
|
||||
// Darken, Multiply, Color Burn, Linear Burn
|
||||
case 1u: {
|
||||
result = min(paint, backdrop);
|
||||
}
|
||||
case 2u: {
|
||||
result = paint * backdrop;
|
||||
}
|
||||
case 3u: {
|
||||
result = color_burn(backdrop, paint);
|
||||
}
|
||||
case 4u: {
|
||||
result = backdrop + paint - 1.;
|
||||
}
|
||||
// Lighten, Screen, Color Dodge, Linear Dodge
|
||||
case 6u: {
|
||||
result = max(paint, backdrop);
|
||||
}
|
||||
case 7u: {
|
||||
result = screen(backdrop, paint);
|
||||
}
|
||||
case 8u: {
|
||||
result = color_dodge(backdrop, paint);
|
||||
}
|
||||
case 9u: {
|
||||
result = backdrop + paint;
|
||||
}
|
||||
// Overlay, Soft Light, Hard Light, Vivid Light, Linear Light, Pin Light, Hard Mix
|
||||
case 11u: {
|
||||
result = hard_light(paint, backdrop);
|
||||
}
|
||||
case 12u: {
|
||||
result = soft_light(backdrop, paint);
|
||||
}
|
||||
case 13u: {
|
||||
result = hard_light(backdrop, paint);
|
||||
}
|
||||
case 14u: {
|
||||
result = select(color_dodge(backdrop, 2. * paint - 1.), color_burn(backdrop, 2. * paint), paint <= 0.5);
|
||||
}
|
||||
case 15u: {
|
||||
result = linear_light(backdrop, paint);
|
||||
}
|
||||
case 16u: {
|
||||
result = select(max(2. * paint - 1., backdrop), min(2. * paint, backdrop), paint <= 0.5);
|
||||
}
|
||||
case 17u: {
|
||||
result = select(1., 0., linear_light(backdrop, paint) < 0.5);
|
||||
}
|
||||
// Difference, Exclusion, Subtract, Divide
|
||||
case 18u: {
|
||||
result = abs(backdrop - paint);
|
||||
}
|
||||
case 19u: {
|
||||
result = backdrop + paint - 2. * backdrop * paint;
|
||||
}
|
||||
case 20u: {
|
||||
result = backdrop - paint;
|
||||
}
|
||||
case 21u: {
|
||||
result = select(backdrop / paint, 1., backdrop == 0.);
|
||||
}
|
||||
// Normal, and the alpha-only utility modes, which mix no color
|
||||
default: {
|
||||
result = paint;
|
||||
}
|
||||
}
|
||||
return clamp(result, 0., 1.);
|
||||
}
|
||||
|
||||
fn screen(backdrop: f32, paint: f32) -> f32 {
|
||||
return 1. - (1. - paint) * (1. - backdrop);
|
||||
}
|
||||
|
||||
fn color_burn(backdrop: f32, paint: f32) -> f32 {
|
||||
if backdrop == 1. {
|
||||
return 1.;
|
||||
}
|
||||
if paint == 0. {
|
||||
return 0.;
|
||||
}
|
||||
return 1. - min((1. - backdrop) / paint, 1.);
|
||||
}
|
||||
|
||||
fn color_dodge(backdrop: f32, paint: f32) -> f32 {
|
||||
if paint == 1. {
|
||||
return 1.;
|
||||
}
|
||||
return min(backdrop / (1. - paint), 1.);
|
||||
}
|
||||
|
||||
fn hard_light(backdrop: f32, paint: f32) -> f32 {
|
||||
return select(screen(2. * paint - 1., backdrop), 2. * paint * backdrop, paint <= 0.5);
|
||||
}
|
||||
|
||||
fn soft_light(backdrop: f32, paint: f32) -> f32 {
|
||||
if paint <= 0.5 {
|
||||
return backdrop - (1. - 2. * paint) * backdrop * (1. - backdrop);
|
||||
}
|
||||
let curve = select(sqrt(backdrop), ((16. * backdrop - 12.) * backdrop + 4.) * backdrop, backdrop <= 0.25);
|
||||
return backdrop + (2. * paint - 1.) * (curve - backdrop);
|
||||
}
|
||||
|
||||
fn linear_light(backdrop: f32, paint: f32) -> f32 {
|
||||
return select(2. * paint - 1. + backdrop, 2. * paint + backdrop - 1., paint <= 0.5);
|
||||
}
|
||||
|
||||
// Hue, Saturation, Color, and Luminosity on gamma-encoded channels, as the compositing specification constructs them
|
||||
fn blend_components(backdrop: vec3<f32>, paint: vec3<f32>, mode: u32) -> vec3<f32> {
|
||||
switch mode {
|
||||
case 22u: {
|
||||
let hued = set_saturation(paint, channel_range(backdrop));
|
||||
return set_luminosity(hued, luma(hued), luma(backdrop));
|
||||
}
|
||||
case 23u: {
|
||||
let saturated = set_saturation(backdrop, channel_range(paint));
|
||||
return set_luminosity(saturated, luma(saturated), luma(backdrop));
|
||||
}
|
||||
case 24u: {
|
||||
return set_luminosity(paint, luma(paint), luma(backdrop));
|
||||
}
|
||||
default: {
|
||||
return set_luminosity(backdrop, luma(backdrop), luma(paint));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn luma(color: vec3<f32>) -> f32 {
|
||||
return dot(color, vec3<f32>(0.3, 0.59, 0.11));
|
||||
}
|
||||
|
||||
fn channel_range(color: vec3<f32>) -> f32 {
|
||||
return max(max(color.r, color.g), color.b) - min(min(color.r, color.g), color.b);
|
||||
}
|
||||
|
||||
fn set_saturation(color: vec3<f32>, saturation: f32) -> vec3<f32> {
|
||||
let range = channel_range(color);
|
||||
if range <= 0. {
|
||||
return vec3<f32>(0.);
|
||||
}
|
||||
return (color - min(min(color.r, color.g), color.b)) * (saturation / range);
|
||||
}
|
||||
|
||||
// Shifts the channels from `from_luma` to `luminosity`, then pulls them toward it just enough to bring every channel back into 0 to 1
|
||||
fn set_luminosity(color: vec3<f32>, from_luma: f32, luminosity: f32) -> vec3<f32> {
|
||||
var channels = color + (luminosity - from_luma);
|
||||
|
||||
let low = min(min(channels.r, channels.g), channels.b);
|
||||
if low < 0. {
|
||||
channels = luminosity + (channels - luminosity) * (luminosity / (luminosity - low));
|
||||
}
|
||||
let high = max(max(channels.r, channels.g), channels.b);
|
||||
if high > 1. {
|
||||
channels = luminosity + (channels - luminosity) * ((1. - luminosity) / (high - luminosity));
|
||||
}
|
||||
|
||||
return clamp(channels, vec3<f32>(0.), vec3<f32>(1.));
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn scale(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return textureLoad(source, vec2<i32>(position.xy), 0) * parameters.amount;
|
||||
}
|
||||
|
||||
// A mipmap level from the one above it, each texel averaging a block of two by two, which grows to three along an odd side's last texel
|
||||
@fragment
|
||||
fn halve(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let size = vec2<i32>(textureDimensions(source));
|
||||
let half_size = max(size / 2, vec2<i32>(1));
|
||||
let index = vec2<i32>(position.xy);
|
||||
let start = index * 2;
|
||||
// Selecting per axis, since WebGL2 can't select between integer vectors
|
||||
let last = index + 1 == half_size;
|
||||
let end = clamp(vec2<i32>(select(start.x + 2, size.x, last.x), select(start.y + 2, size.y, last.y)), start + 1, size);
|
||||
|
||||
var sum = vec4<f32>(0.);
|
||||
for (var y = start.y; y < end.y; y++) {
|
||||
for (var x = start.x; x < end.x; x++) {
|
||||
sum += textureLoad(source, vec2<i32>(x, y), 0);
|
||||
}
|
||||
}
|
||||
let count = end - start;
|
||||
return sum / f32(count.x * count.y);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn decode_to_linear(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let color = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if color.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
|
||||
return vec4<f32>(srgb_to_linear(max(color.rgb / color.a, vec3<f32>(0.))) * color.a, color.a);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn encode_to_gamma(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let color = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if color.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
|
||||
return vec4<f32>(linear_to_srgb(max(color.rgb / color.a, vec3<f32>(0.))) * color.a, color.a);
|
||||
}
|
||||
|
||||
fn srgb_to_linear(srgb: vec3<f32>) -> vec3<f32> {
|
||||
let low = srgb / 12.92;
|
||||
let high = pow((srgb + 0.055) / 1.055, vec3<f32>(2.4));
|
||||
return select(high, low, srgb <= vec3<f32>(0.04045));
|
||||
}
|
||||
|
||||
fn linear_to_srgb(linear: vec3<f32>) -> vec3<f32> {
|
||||
let low = linear * 12.92;
|
||||
let high = 1.055 * pow(linear, vec3<f32>(1. / 2.4)) - 0.055;
|
||||
return select(high, low, linear <= vec3<f32>(0.0031308));
|
||||
}
|
||||
|
||||
// ===========
|
||||
// Adjustments
|
||||
// ===========
|
||||
|
||||
// The adjustment passes work on a pixel's straight color, leaving fully transparent pixels empty since they keep no color to adjust
|
||||
|
||||
// A one-row table's value at a position from 0 to 1, interpolated between its two nearest entries
|
||||
fn curve_lookup(table: texture_2d<f32>, value: f32) -> vec4<f32> {
|
||||
let last = f32(textureDimensions(table).x - 1u);
|
||||
let position = clamp(value, 0., 1.) * last;
|
||||
let index = min(floor(position), last - 1.);
|
||||
|
||||
let before = textureLoad(table, vec2<i32>(i32(index), 0), 0);
|
||||
let after = textureLoad(table, vec2<i32>(i32(index) + 1, 0), 0);
|
||||
return mix(before, after, position - index);
|
||||
}
|
||||
|
||||
// Each channel through its own curve
|
||||
@fragment
|
||||
fn adjust_curves(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if pixel.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
let color = vec4<f32>(pixel.rgb / pixel.a, pixel.a);
|
||||
|
||||
let red = curve_lookup(secondary, color.r).r;
|
||||
let green = curve_lookup(secondary, color.g).g;
|
||||
let blue = curve_lookup(secondary, color.b).b;
|
||||
let alpha = curve_lookup(secondary, color.a).a;
|
||||
return vec4<f32>(vec3<f32>(red, green, blue) * alpha, alpha);
|
||||
}
|
||||
|
||||
// The cube entry at a grid point, from the texture's tiles of slices of constant blue, each with red across and green down
|
||||
fn cube_entry(size: u32, point: vec3<u32>) -> vec3<f32> {
|
||||
let columns = textureDimensions(secondary).x / size;
|
||||
let tile = vec2<u32>(point.b % columns, point.b / columns) * size;
|
||||
return textureLoad(secondary, vec2<i32>(tile + point.rg), 0).rgb;
|
||||
}
|
||||
|
||||
// The cube's color at a point, interpolated in the tetrahedron of its cell that holds it, which fits the cube far closer than trilinear interpolation.
|
||||
// The cube has `values.x` samples along each side.
|
||||
fn cube_lookup(color: vec3<f32>) -> vec3<f32> {
|
||||
let size = u32(parameters.values.x);
|
||||
let scaled = clamp(color, vec3<f32>(0.), vec3<f32>(1.)) * f32(size - 1u);
|
||||
let base = min(vec3<u32>(floor(scaled)), vec3<u32>(size - 2u));
|
||||
let f = scaled - vec3<f32>(base);
|
||||
|
||||
let black = cube_entry(size, base);
|
||||
let white = cube_entry(size, base + vec3<u32>(1u, 1u, 1u));
|
||||
let r = cube_entry(size, base + vec3<u32>(1u, 0u, 0u));
|
||||
let g = cube_entry(size, base + vec3<u32>(0u, 1u, 0u));
|
||||
let b = cube_entry(size, base + vec3<u32>(0u, 0u, 1u));
|
||||
let rg = cube_entry(size, base + vec3<u32>(1u, 1u, 0u));
|
||||
let rb = cube_entry(size, base + vec3<u32>(1u, 0u, 1u));
|
||||
let gb = cube_entry(size, base + vec3<u32>(0u, 1u, 1u));
|
||||
|
||||
// Each tetrahedron runs from the cell's black corner to its white one, stepping along the axes in order of how far the point lies along them
|
||||
if f.r >= f.g && f.g >= f.b {
|
||||
return (1. - f.r) * black + (f.r - f.g) * r + (f.g - f.b) * rg + f.b * white;
|
||||
} else if f.r >= f.b && f.b >= f.g {
|
||||
return (1. - f.r) * black + (f.r - f.b) * r + (f.b - f.g) * rb + f.g * white;
|
||||
} else if f.b >= f.r && f.r >= f.g {
|
||||
return (1. - f.b) * black + (f.b - f.r) * b + (f.r - f.g) * rb + f.g * white;
|
||||
} else if f.g >= f.r && f.r >= f.b {
|
||||
return (1. - f.g) * black + (f.g - f.r) * g + (f.r - f.b) * rg + f.b * white;
|
||||
} else if f.g >= f.b && f.b >= f.r {
|
||||
return (1. - f.g) * black + (f.g - f.b) * g + (f.b - f.r) * gb + f.r * white;
|
||||
}
|
||||
return (1. - f.b) * black + (f.b - f.g) * b + (f.g - f.r) * gb + f.r * white;
|
||||
}
|
||||
|
||||
// The color through the cube and alpha through its own curve
|
||||
@fragment
|
||||
fn adjust_cube(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if pixel.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
|
||||
let alpha = curve_lookup(content, pixel.a).a;
|
||||
return vec4<f32>(cube_lookup(pixel.rgb / pixel.a) * alpha, alpha);
|
||||
}
|
||||
|
||||
// The color the pixel's luma picks from a table, with the pixel's alpha
|
||||
@fragment
|
||||
fn adjust_by_luma(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if pixel.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
|
||||
let luma = dot(pixel.rgb / pixel.a, parameters.values.rgb);
|
||||
return vec4<f32>(curve_lookup(secondary, luma).rgb * pixel.a, pixel.a);
|
||||
}
|
||||
|
||||
fn wrap_positive(value: f32, modulus: f32) -> f32 {
|
||||
return value - floor(value / modulus) * modulus;
|
||||
}
|
||||
|
||||
// Hexagon hue in degrees, 0 for gray
|
||||
fn hexagon_hue_degrees(color: vec3<f32>) -> f32 {
|
||||
let maximum = max(color.r, max(color.g, color.b));
|
||||
let chroma = maximum - min(color.r, min(color.g, color.b));
|
||||
if chroma <= 0. {
|
||||
return 0.;
|
||||
}
|
||||
|
||||
if maximum == color.r {
|
||||
return wrap_positive((color.g - color.b) / chroma, 6.) * 60.;
|
||||
} else if maximum == color.g {
|
||||
return ((color.b - color.r) / chroma + 2.) * 60.;
|
||||
}
|
||||
return ((color.r - color.g) / chroma + 4.) * 60.;
|
||||
}
|
||||
|
||||
// How fully a hue falls under the skin-tone protection: all of it from red to 30 degrees, fading out by 45, and back in from 300
|
||||
fn skin_tone_window(hue: f32) -> f32 {
|
||||
if hue < 45. {
|
||||
return min((45. - hue) / 15., 1.);
|
||||
} else if hue >= 300. {
|
||||
return (hue - 300.) / 60.;
|
||||
}
|
||||
return 0.;
|
||||
}
|
||||
|
||||
// Vibrance on linear channels as the chroma factor about the maximum channel (x) and the brightness multiplier (y), mirroring the CPU kernel
|
||||
fn vibrance_factors(color: vec3<f32>, amount: f32) -> vec2<f32> {
|
||||
let maximum = max(color.r, max(color.g, color.b));
|
||||
let minimum = min(color.r, min(color.g, color.b));
|
||||
if maximum <= 0. {
|
||||
return vec2<f32>(1.);
|
||||
}
|
||||
|
||||
let ratio = minimum / maximum;
|
||||
let saturation = 1. - ratio;
|
||||
let q = ratio * saturation;
|
||||
let toe = 1. - min(16. * maximum, 1.);
|
||||
let rolloff = 1. - toe * toe;
|
||||
let brightness = (2. * q - q * q) * (1. - maximum) * rolloff;
|
||||
|
||||
if amount < 0. {
|
||||
let desaturation = -amount;
|
||||
let chroma_factor = (1. - desaturation / 4.) * (1. - desaturation * (1. - rolloff * saturation * (1. + saturation) / 2.));
|
||||
return vec2<f32>(chroma_factor, 1. - desaturation * brightness);
|
||||
}
|
||||
|
||||
let protection = skin_tone_window(hexagon_hue_degrees(color)) * (1. - saturation * saturation);
|
||||
let protected_amount = amount * (1. - protection * (1. - amount));
|
||||
let boost = (5. / 6.) * (1. - 0.4857 * protection) * protected_amount * ratio * (1. - minimum) * rolloff;
|
||||
return vec2<f32>(1. / (1. - boost), 1. + protected_amount * brightness / 4.);
|
||||
}
|
||||
|
||||
// Vibrance (amount in values.x) then saturation (scale in values.y), both in linear light
|
||||
@fragment
|
||||
fn adjust_vibrance(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if pixel.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
let linear = srgb_to_linear(max(pixel.rgb / pixel.a, vec3<f32>(0.)));
|
||||
|
||||
let maximum = max(linear.r, max(linear.g, linear.b));
|
||||
let factors = vibrance_factors(linear, parameters.values.x);
|
||||
let vibrant = clamp(factors.y * (maximum + factors.x * (linear - maximum)), vec3<f32>(0.), vec3<f32>(1.));
|
||||
|
||||
// Saturation scales each channel's distance from a gray weighted by ProPhoto's luminance coefficients
|
||||
let gray = dot(vibrant, vec3<f32>(0.288040, 0.711874, 0.000086));
|
||||
let saturated = clamp(gray + (vibrant - gray) * parameters.values.y, vec3<f32>(0.), vec3<f32>(1.));
|
||||
return vec4<f32>(linear_to_srgb(saturated) * pixel.a, pixel.a);
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
//! The GPU pass that renders tiles of generators' patterns, matching the CPU's renders of them.
|
||||
|
||||
use crate::vello_render::TEXTURE_FORMAT;
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use glam::DVec2;
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
|
||||
use std::sync::OnceLock;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
/// How many of a 32-bit float's steps one pixel must span for the Mandelbrot set to render on the GPU, past which its deep zooms render on the CPU in 64 bits.
|
||||
const MIN_MANDELBROT_PIXEL_STEPS: f64 = 64.;
|
||||
|
||||
/// The shader's patterns, matching its `PATTERN_` constants.
|
||||
const PATTERN_NOISE: u32 = 0;
|
||||
const PATTERN_WHITE_NOISE: u32 = 1;
|
||||
const PATTERN_MANDELBROT: u32 = 2;
|
||||
|
||||
/// FastNoiseLite's `fnl_state`, laid out to match the shader's.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default, Pod, Zeroable)]
|
||||
struct NoiseState {
|
||||
seed: i32,
|
||||
frequency: f32,
|
||||
noise_type: i32,
|
||||
rotation_type_3d: i32,
|
||||
fractal_type: i32,
|
||||
octaves: i32,
|
||||
lacunarity: f32,
|
||||
gain: f32,
|
||||
weighted_strength: f32,
|
||||
ping_pong_strength: f32,
|
||||
cellular_distance_func: i32,
|
||||
cellular_return_type: i32,
|
||||
cellular_jitter_mod: f32,
|
||||
domain_warp_type: i32,
|
||||
domain_warp_amp: f32,
|
||||
}
|
||||
|
||||
/// The shader's parameters, laid out to match its `Parameters` struct.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default, Pod, Zeroable)]
|
||||
struct Parameters {
|
||||
corner: [f32; 2],
|
||||
texel: [f32; 2],
|
||||
pattern: u32,
|
||||
domain_warp: u32,
|
||||
_padding: [u32; 2],
|
||||
noise: NoiseState,
|
||||
_end_padding: u32,
|
||||
}
|
||||
|
||||
impl NoiseState {
|
||||
/// The state FastNoiseLite's CPU sampler is given for the same settings, with whether it warps its domain.
|
||||
fn new(settings: &NoiseSettings) -> (Self, bool) {
|
||||
let domain_warp_type = match settings.domain_warp_type {
|
||||
DomainWarpType::None => None,
|
||||
DomainWarpType::OpenSimplex2 => Some(0),
|
||||
DomainWarpType::OpenSimplex2Reduced => Some(1),
|
||||
DomainWarpType::BasicGrid => Some(2),
|
||||
};
|
||||
let state = Self {
|
||||
seed: settings.seed as i32,
|
||||
frequency: 1. / (settings.scale as f32).max(f32::EPSILON),
|
||||
noise_type: match settings.noise_type {
|
||||
NoiseType::OpenSimplex2 | NoiseType::WhiteNoise => 0,
|
||||
NoiseType::OpenSimplex2S => 1,
|
||||
NoiseType::Cellular => 2,
|
||||
NoiseType::Perlin => 3,
|
||||
NoiseType::ValueCubic => 4,
|
||||
NoiseType::Value => 5,
|
||||
},
|
||||
rotation_type_3d: 0,
|
||||
fractal_type: match settings.fractal_type {
|
||||
FractalType::None => 0,
|
||||
FractalType::FBm => 1,
|
||||
FractalType::Ridged => 2,
|
||||
FractalType::PingPong => 3,
|
||||
FractalType::DomainWarpProgressive => 4,
|
||||
FractalType::DomainWarpIndependent => 5,
|
||||
},
|
||||
octaves: settings.fractal_octaves as i32,
|
||||
lacunarity: settings.fractal_lacunarity as f32,
|
||||
gain: settings.fractal_gain as f32,
|
||||
weighted_strength: settings.fractal_weighted_strength as f32,
|
||||
ping_pong_strength: settings.fractal_ping_pong_strength as f32,
|
||||
cellular_distance_func: match settings.cellular_distance_function {
|
||||
CellularDistanceFunction::Euclidean => 0,
|
||||
CellularDistanceFunction::EuclideanSq => 1,
|
||||
CellularDistanceFunction::Manhattan => 2,
|
||||
CellularDistanceFunction::Hybrid => 3,
|
||||
},
|
||||
cellular_return_type: match settings.cellular_return_type {
|
||||
CellularReturnType::CellValue => 0,
|
||||
CellularReturnType::Nearest => 1,
|
||||
CellularReturnType::NextNearest => 2,
|
||||
CellularReturnType::Average => 3,
|
||||
CellularReturnType::Difference => 4,
|
||||
CellularReturnType::Product => 5,
|
||||
CellularReturnType::Division => 6,
|
||||
},
|
||||
cellular_jitter_mod: settings.cellular_jitter as f32,
|
||||
domain_warp_type: domain_warp_type.unwrap_or(0),
|
||||
domain_warp_amp: settings.domain_warp_amplitude as f32,
|
||||
};
|
||||
|
||||
(state, domain_warp_type.is_some() && settings.domain_warp_amplitude > 0.)
|
||||
}
|
||||
}
|
||||
|
||||
impl Parameters {
|
||||
/// The parameters of a tile of `pattern` whose top left corner lies at `corner` of the pattern's space, with pixels `texel` units across.
|
||||
/// Returns `None` if the tile's pixels are too fine for 32-bit floats to place.
|
||||
fn new(pattern: &GeneratorPattern, corner: DVec2, texel: f64, pixels: u32) -> Option<Self> {
|
||||
let (pattern, corner, texel, noise, domain_warp) = match pattern {
|
||||
GeneratorPattern::Noise(settings) => {
|
||||
let (noise, domain_warp) = NoiseState::new(settings);
|
||||
let pattern = if settings.noise_type == NoiseType::WhiteNoise { PATTERN_WHITE_NOISE } else { PATTERN_NOISE };
|
||||
(pattern, corner, texel, noise, domain_warp)
|
||||
}
|
||||
GeneratorPattern::Mandelbrot => {
|
||||
// Sampled in the complex plane rather than its unit square, so the shader's coordinates there round only once
|
||||
let (corner, texel) = (corner * 3. - DVec2::new(2., 1.5), texel * 3.);
|
||||
let farthest = corner.abs().max((corner + texel * pixels as f64).abs()).max_element();
|
||||
if texel < farthest * f32::EPSILON as f64 * MIN_MANDELBROT_PIXEL_STEPS {
|
||||
return None;
|
||||
}
|
||||
(PATTERN_MANDELBROT, corner, texel, NoiseState::default(), false)
|
||||
}
|
||||
};
|
||||
|
||||
Some(Self {
|
||||
corner: corner.as_vec2().to_array(),
|
||||
texel: [texel as f32; 2],
|
||||
pattern,
|
||||
domain_warp: domain_warp as u32,
|
||||
noise,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The pipeline of the pass, built the first time a generator is drawn so documents without one don't compile its shader.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct GeneratorPasses {
|
||||
pipeline: OnceLock<(wgpu::RenderPipeline, wgpu::BindGroupLayout)>,
|
||||
}
|
||||
|
||||
impl GeneratorPasses {
|
||||
fn pipeline(&self, device: &wgpu::Device) -> &(wgpu::RenderPipeline, wgpu::BindGroupLayout) {
|
||||
self.pipeline.get_or_init(|| {
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("vello_generators"),
|
||||
source: wgpu::ShaderSource::Wgsl(concat!(include_str!("fast_noise_lite.wgsl"), include_str!("vello_generators.wgsl")).into()),
|
||||
});
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("vello_generators_bind_group_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("vello_generators_pipeline_layout"),
|
||||
bind_group_layouts: &[Some(&bind_group_layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("vello_generators"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vertex"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("generate"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: TEXTURE_FORMAT,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
(pipeline, bind_group_layout)
|
||||
})
|
||||
}
|
||||
|
||||
/// Records the rendering of the top mip level of a square tile of `pattern`, `pixels` across, whose top left corner lies at `corner` of the pattern's space with pixels `texel` units across.
|
||||
/// Returns `None` if the GPU can't render the tile as precisely as the CPU, leaving it to the CPU.
|
||||
pub(crate) fn render_tile(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, pattern: &GeneratorPattern, corner: DVec2, texel: f64, pixels: u32) -> Option<wgpu::Texture> {
|
||||
let parameters = Parameters::new(pattern, corner, texel, pixels)?;
|
||||
let (pipeline, bind_group_layout) = self.pipeline(device);
|
||||
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_generator_tile"),
|
||||
size: wgpu::Extent3d {
|
||||
width: pixels,
|
||||
height: pixels,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: pixels.ilog2() + 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
});
|
||||
|
||||
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("vello_generator_parameters"),
|
||||
contents: bytemuck::bytes_of(¶meters),
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("vello_generator_bind_group"),
|
||||
layout: bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buffer.as_entire_binding(),
|
||||
}],
|
||||
});
|
||||
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
mip_level_count: Some(1),
|
||||
..Default::default()
|
||||
});
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("vello_generator_tile"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_bind_group(0, &bind_group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
drop(pass);
|
||||
|
||||
Some(texture)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn mandelbrot_tiles_too_fine_for_32_bit_floats_are_left_to_the_cpu() {
|
||||
let corner = DVec2::new(0.25, 0.5);
|
||||
assert!(Parameters::new(&GeneratorPattern::Mandelbrot, corner, 2_f64.powi(-8), 260).is_some());
|
||||
assert!(Parameters::new(&GeneratorPattern::Mandelbrot, corner, 2_f64.powi(-30), 260).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Renders a tile of a generator's pattern, sampled at the centers of the tile's pixels, as opaque gamma-encoded color like the CPU's tiles
|
||||
|
||||
const PATTERN_NOISE: u32 = 0u;
|
||||
const PATTERN_WHITE_NOISE: u32 = 1u;
|
||||
const PATTERN_MANDELBROT: u32 = 2u;
|
||||
|
||||
// The most iterations a point is tested for escaping the Mandelbrot set, beyond which it counts as inside
|
||||
const MANDELBROT_ITERATIONS: u32 = 255u;
|
||||
|
||||
struct Parameters {
|
||||
// Where the tile's top left corner lies in the space the pattern is sampled in, and the size of one of its pixels there
|
||||
corner: vec2<f32>,
|
||||
texel: vec2<f32>,
|
||||
pattern: u32,
|
||||
// Whether the noise warps its domain before it's sampled
|
||||
domain_warp: u32,
|
||||
@align(16) noise: fnl_state,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var<uniform> parameters: Parameters;
|
||||
|
||||
// One triangle that covers the whole target
|
||||
@vertex
|
||||
fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
|
||||
let corner = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u));
|
||||
return vec4<f32>(corner * 2. - 1., 0., 1.);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn generate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let point = parameters.corner + position.xy * parameters.texel;
|
||||
|
||||
var luminance: f32;
|
||||
switch parameters.pattern {
|
||||
case PATTERN_NOISE: {
|
||||
luminance = noise(point);
|
||||
}
|
||||
case PATTERN_WHITE_NOISE: {
|
||||
luminance = white_noise(point);
|
||||
}
|
||||
case PATTERN_MANDELBROT, default: {
|
||||
luminance = mandelbrot(point);
|
||||
}
|
||||
}
|
||||
|
||||
return vec4<f32>(vec3<f32>(linear_to_srgb(luminance)), 1.);
|
||||
}
|
||||
|
||||
fn noise(point: vec2<f32>) -> f32 {
|
||||
var x = point.x;
|
||||
var y = point.y;
|
||||
if parameters.domain_warp != 0u {
|
||||
fnlDomainWarp2D(parameters.noise, &x, &y);
|
||||
}
|
||||
return (fnlGetNoise2D(parameters.noise, x, y) + 1.) * 0.5;
|
||||
}
|
||||
|
||||
// A random value for each square of one unit, matching the CPU's
|
||||
fn white_noise(point: vec2<f32>) -> f32 {
|
||||
let cell = vec2<i32>(floor(point));
|
||||
let hash = pcg3d(vec3<u32>(bitcast<vec2<u32>>(cell), bitcast<u32>(parameters.noise.seed)));
|
||||
|
||||
// The top 24 bits, which an f32 holds exactly
|
||||
return f32(hash.x >> 8u) / 16777216.;
|
||||
}
|
||||
|
||||
// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result
|
||||
fn pcg3d(input: vec3<u32>) -> vec3<u32> {
|
||||
var v = input * 1664525u + 1013904223u;
|
||||
v.x += v.y * v.z;
|
||||
v.y += v.z * v.x;
|
||||
v.z += v.x * v.y;
|
||||
v ^= v >> vec3<u32>(16u);
|
||||
v.x += v.y * v.z;
|
||||
v.y += v.z * v.x;
|
||||
v.z += v.x * v.y;
|
||||
return v;
|
||||
}
|
||||
|
||||
// The fraction of the iteration limit that `c` takes to escape the Mandelbrot set, or 1 if it doesn't
|
||||
fn mandelbrot(c: vec2<f32>) -> f32 {
|
||||
var z = vec2<f32>(0.);
|
||||
for (var iteration = 0u; iteration < MANDELBROT_ITERATIONS; iteration++) {
|
||||
z = vec2<f32>(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c;
|
||||
if dot(z, z) > 4. {
|
||||
return f32(iteration) / f32(MANDELBROT_ITERATIONS);
|
||||
}
|
||||
}
|
||||
return 1.;
|
||||
}
|
||||
|
||||
// Clamped to the range the CPU encodes, which takes NaN as 0
|
||||
fn linear_to_srgb(unclamped: f32) -> f32 {
|
||||
let linear = select(0., min(unclamped, 1.), unclamped >= 0.);
|
||||
let low = linear * 12.92;
|
||||
let high = 1.055 * pow(linear, 1. / 2.4) - 0.055;
|
||||
return select(high, low, linear <= 0.0031308);
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
use glam::UVec2;
|
||||
use raster_types::WeakCPU;
|
||||
use rendering::vello_scene_builder::{SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use crate::vello_effects::{AdjustmentPassTextures, EffectPasses, EffectTextures, adjustment_run_hash};
|
||||
use crate::vello_generators::GeneratorPasses;
|
||||
use glam::{DMat2, UVec2};
|
||||
use graphic_types::raster_types::{CPU, Raster, WeakCPU};
|
||||
use graphic_types::{Adjustment, EffectOperation, Effects};
|
||||
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use vello_gpu::kurbo::Affine;
|
||||
use vello_gpu::peniko;
|
||||
use vello_gpu::{
|
||||
@@ -12,11 +15,14 @@ use vello_gpu::{
|
||||
use wgpu_sync::Queue;
|
||||
|
||||
/// The format of the textures Vello GPU renders into, of the image textures it samples, and of the textures handed back.
|
||||
const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
|
||||
pub(crate) const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
|
||||
|
||||
/// How many renders a GPU texture's premultiplied copy survives without being drawn before it is freed.
|
||||
const UNUSED_IMAGE_RENDER_LIMIT: u64 = 60;
|
||||
|
||||
/// The most tiles of generators kept between renders, past which the least recently drawn are freed.
|
||||
const MAX_CACHED_GENERATOR_TILES: usize = 256;
|
||||
|
||||
/// How many times a render with too much content for Vello GPU is halved, reaching areas 1/4096 the size of the original.
|
||||
const MAX_SPLIT_DEPTH: u32 = 12;
|
||||
|
||||
@@ -29,20 +35,38 @@ pub(crate) struct VelloRenderer {
|
||||
/// Locked only while a scene is rendered and submitted, so one canvas drawing its scene on the CPU doesn't hold up another's render.
|
||||
gpu: Mutex<(Renderer, Resources)>,
|
||||
alpha_conversion: AlphaConversion,
|
||||
effect_passes: EffectPasses,
|
||||
generator_passes: GeneratorPasses,
|
||||
}
|
||||
|
||||
/// A stream of frames rendered through the shared Vello renderer, such as the document or the overlays, keeping what its frames reuse.
|
||||
#[derive(Default)]
|
||||
pub struct VelloCanvas {
|
||||
/// The Vello GPU scene of the last render, handed out again to keep its allocations.
|
||||
spare_scene: Option<vello_gpu::Scene>,
|
||||
/// Scenes to draw into, one for each depth of effects groups nested in a render, reused between renders to keep their allocations.
|
||||
spare_scenes: Vec<vello_gpu::Scene>,
|
||||
/// The premultiplied texture Vello GPU renders into before conversion to straight alpha, kept while the render size stays the same.
|
||||
premultiplied_target: Option<wgpu::Texture>,
|
||||
images: ImageTextures,
|
||||
effect_textures: EffectTextures,
|
||||
}
|
||||
|
||||
/// Whether a render leaves its target with the straight alpha the rest of Graphite expects, or the premultiplied alpha the effect passes take.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum TargetAlpha {
|
||||
Straight,
|
||||
Premultiplied,
|
||||
}
|
||||
|
||||
/// A render in progress: the shared renderer and GPU, and the canvas whose resources it draws with.
|
||||
struct RenderContext<'a> {
|
||||
renderer: &'a VelloRenderer,
|
||||
canvas: &'a mut VelloCanvas,
|
||||
device: &'a wgpu::Device,
|
||||
queue: &'a Queue,
|
||||
}
|
||||
|
||||
impl VelloRenderer {
|
||||
pub(crate) fn new(device: &wgpu::Device) -> Self {
|
||||
pub(crate) fn new(device: &wgpu::Device, adapter: &wgpu::Adapter) -> Self {
|
||||
let render_target_config = RenderTargetConfig {
|
||||
format: TEXTURE_FORMAT,
|
||||
width: 1,
|
||||
@@ -60,6 +84,8 @@ impl VelloRenderer {
|
||||
Self {
|
||||
gpu: Mutex::new(Renderer::new_with(device, &render_target_config, settings)),
|
||||
alpha_conversion: AlphaConversion::new(device),
|
||||
effect_passes: EffectPasses::new(device, adapter),
|
||||
generator_passes: GeneratorPasses::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,10 +107,15 @@ impl VelloRenderer {
|
||||
}
|
||||
|
||||
canvas.images.render_count += 1;
|
||||
if let Err(error) = self.render_once(canvas, device, queue, draw, view, size, target) {
|
||||
self.render_halves(canvas, device, queue, draw, view, size, target, error, 1);
|
||||
}
|
||||
let mut context = RenderContext {
|
||||
renderer: self,
|
||||
canvas,
|
||||
device,
|
||||
queue,
|
||||
};
|
||||
context.render_area(draw, view, size, target, TargetAlpha::Straight);
|
||||
canvas.images.free_unused();
|
||||
canvas.effect_textures.finish_render();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -94,27 +125,34 @@ impl VelloRenderer {
|
||||
pub(crate) fn render_scene(&self, canvas: &mut VelloCanvas, device: &wgpu::Device, queue: &Queue, scene: VelloSceneBuilder, target: &wgpu::Texture) {
|
||||
canvas.images.render_count += 1;
|
||||
let max_texture_size = scene.max_texture_size();
|
||||
if let Err(error) = self.submit(canvas, device, queue, scene.finish(), max_texture_size, target) {
|
||||
let mut context = RenderContext {
|
||||
renderer: self,
|
||||
canvas,
|
||||
device,
|
||||
queue,
|
||||
};
|
||||
if let Err(error) = context.submit(scene.finish(), max_texture_size, target, TargetAlpha::Straight) {
|
||||
log::error!("Vello GPU failed to render: {error}");
|
||||
clear(device, queue, target);
|
||||
}
|
||||
canvas.images.free_unused();
|
||||
canvas.effect_textures.finish_render();
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderContext<'_> {
|
||||
/// Renders the scene `draw` draws into `target`, a texture of `size`, splitting its area into halves while it holds more content than one render can.
|
||||
fn render_area(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) {
|
||||
if let Err(error) = self.render_once(draw, view, size, target, target_alpha) {
|
||||
self.render_halves(draw, view, size, target, target_alpha, error, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders each half of the area of `target`, a texture of `size`, after rendering it whole failed with `error`, splitting again each half that still holds too much.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_halves(
|
||||
&self,
|
||||
canvas: &mut VelloCanvas,
|
||||
device: &wgpu::Device,
|
||||
queue: &Queue,
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
view: Affine,
|
||||
size: UVec2,
|
||||
target: &wgpu::Texture,
|
||||
error: RenderError,
|
||||
split_depth: u32,
|
||||
) {
|
||||
fn render_halves(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha, error: RenderError, split_depth: u32) {
|
||||
let (device, queue) = (self.device, self.queue);
|
||||
|
||||
// Each half covers less of the scene, so it has less content and smaller layers to hold
|
||||
let too_much_to_hold = matches!(
|
||||
error,
|
||||
@@ -142,7 +180,7 @@ impl VelloRenderer {
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
|
||||
);
|
||||
let half_view = Affine::translate((-(offset.x as f64), -(offset.y as f64))) * view;
|
||||
let rendered = self.render_once(canvas, device, queue, draw, half_view, half_size, &half_target);
|
||||
let rendered = self.render_once(draw, half_view, half_size, &half_target, target_alpha);
|
||||
(offset, half_size, half_view, half_target, rendered)
|
||||
});
|
||||
|
||||
@@ -166,7 +204,7 @@ impl VelloRenderer {
|
||||
|
||||
for (offset, half_size, half_view, half_target, rendered) in halves {
|
||||
if let Err(half_error) = rendered {
|
||||
self.render_halves(canvas, device, queue, draw, half_view, half_size, &half_target, half_error, split_depth + 1);
|
||||
self.render_halves(draw, half_view, half_size, &half_target, target_alpha, half_error, split_depth + 1);
|
||||
}
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_split_copy") });
|
||||
@@ -182,43 +220,29 @@ impl VelloRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders the scene `draw` draws, with its content placed by `view`, into `target`, a texture of `size`, in a single Vello GPU render.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_once(
|
||||
&self,
|
||||
canvas: &mut VelloCanvas,
|
||||
device: &wgpu::Device,
|
||||
queue: &Queue,
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
view: Affine,
|
||||
size: UVec2,
|
||||
target: &wgpu::Texture,
|
||||
) -> Result<(), RenderError> {
|
||||
/// Renders the scene `draw` draws into `target`, a texture of `size`, in a single Vello GPU render.
|
||||
fn render_once(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> {
|
||||
let (width, height) = (size.x as u16, size.y as u16);
|
||||
let max_texture_size = device.limits().max_texture_dimension_2d;
|
||||
let max_texture_size = self.device.limits().max_texture_dimension_2d;
|
||||
|
||||
let mut scene = canvas.spare_scene.take().unwrap_or_else(|| vello_gpu::Scene::new(width, height));
|
||||
// Draw the scene for this render's size and placement, which renders its effects groups as they're drawn
|
||||
let mut scene = self.canvas.spare_scenes.pop().unwrap_or_else(|| vello_gpu::Scene::new(width, height));
|
||||
scene.reset_and_resize(width, height);
|
||||
let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size);
|
||||
let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size).with_effects_renderer(self);
|
||||
draw(&mut builder);
|
||||
let drawn = builder.finish();
|
||||
|
||||
self.submit(canvas, device, queue, builder.finish(), max_texture_size, target)
|
||||
self.submit(drawn, max_texture_size, target, target_alpha)
|
||||
}
|
||||
|
||||
/// Renders a drawn scene, with the images it draws, into `target`, a texture of the scene's size, in a single Vello GPU render.
|
||||
fn submit(
|
||||
&self,
|
||||
canvas: &mut VelloCanvas,
|
||||
device: &wgpu::Device,
|
||||
queue: &Queue,
|
||||
(scene, images): (vello_gpu::Scene, Vec<SceneImage>),
|
||||
max_texture_size: u32,
|
||||
target: &wgpu::Texture,
|
||||
) -> Result<(), RenderError> {
|
||||
fn submit(&mut self, (scene, images): (vello_gpu::Scene, Vec<SceneImage>), max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> {
|
||||
let device = self.device;
|
||||
let (width, height) = (scene.width(), scene.height());
|
||||
let size = UVec2::new(width as u32, height as u32);
|
||||
|
||||
// Locked from here to the submission, so drawing a scene doesn't hold up other uses of the queue
|
||||
let queue = queue.lock();
|
||||
let queue = self.queue.lock();
|
||||
|
||||
// Each render submits its own encoder, since Vello GPU stages its uploads for the next submission
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_render") });
|
||||
@@ -226,31 +250,43 @@ impl VelloRenderer {
|
||||
// Supply the textures of the images the scene draws, under the IDs it drew them with
|
||||
let mut texture_bindings = TextureBindings::new();
|
||||
for (id, image) in images.iter().enumerate() {
|
||||
if let Some(view) = canvas.images.prepare(device, &queue, &mut encoder, &self.alpha_conversion, image, max_texture_size) {
|
||||
let view = self.canvas.images.prepare(device, &queue, &mut encoder, self.renderer, image, max_texture_size);
|
||||
|
||||
// Adjustments draw a copy of the texture they're carried out on
|
||||
let view = match image {
|
||||
SceneImage::Raster { raster, adjustments } if !adjustments.is_empty() => view.and_then(|_| {
|
||||
let effects = (&self.renderer.effect_passes, &mut self.canvas.effect_textures);
|
||||
self.canvas.images.prepare_adjusted(device, &queue, effects, raster, adjustments)
|
||||
}),
|
||||
_ => view,
|
||||
};
|
||||
|
||||
if let Some(view) = view {
|
||||
texture_bindings.insert(TextureId(id as u64), view);
|
||||
}
|
||||
}
|
||||
|
||||
// Render premultiplied, then convert to the straight alpha the rest of Graphite expects
|
||||
let size = UVec2::new(width as u32, height as u32);
|
||||
let premultiplied_target = match &canvas.premultiplied_target {
|
||||
Some(texture) if texture.width() == size.x && texture.height() == size.y => texture.clone(),
|
||||
_ => {
|
||||
// Vello GPU renders premultiplied, which is converted to straight alpha unless the target wants it premultiplied
|
||||
let target_view = target.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let premultiplied_view = match (target_alpha, &self.canvas.premultiplied_target) {
|
||||
(TargetAlpha::Premultiplied, _) => target_view.clone(),
|
||||
(TargetAlpha::Straight, Some(texture)) if texture.width() == size.x && texture.height() == size.y => texture.create_view(&wgpu::TextureViewDescriptor::default()),
|
||||
(TargetAlpha::Straight, _) => {
|
||||
let texture = create_texture(
|
||||
device,
|
||||
"vello_gpu_premultiplied_target",
|
||||
size,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
);
|
||||
canvas.premultiplied_target = Some(texture.clone());
|
||||
texture
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.canvas.premultiplied_target = Some(texture);
|
||||
view
|
||||
}
|
||||
};
|
||||
let premultiplied_view = premultiplied_target.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let target_init = TargetInit::Clear(ClearSettings::Viewport { color: peniko::Color::TRANSPARENT });
|
||||
|
||||
// Vello GPU stages this render's uploads into resources every render shares, so another can't stage its own until this one is submitted
|
||||
let mut gpu = self.gpu.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let mut gpu = self.renderer.gpu.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let (renderer, resources) = &mut *gpu;
|
||||
let rendered = renderer.render(
|
||||
&scene,
|
||||
@@ -265,20 +301,63 @@ impl VelloRenderer {
|
||||
target_init,
|
||||
);
|
||||
|
||||
if rendered.is_ok() {
|
||||
let target_view = target.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.alpha_conversion.unpremultiply(device, &mut encoder, &premultiplied_view, &target_view);
|
||||
if rendered.is_ok() && target_alpha == TargetAlpha::Straight {
|
||||
self.renderer.alpha_conversion.unpremultiply(device, &mut encoder, &premultiplied_view, &target_view);
|
||||
}
|
||||
|
||||
// Submitted even after a failure, since it also prepares the textures of the scene's images
|
||||
queue.submit([encoder.finish()]);
|
||||
drop((gpu, queue));
|
||||
canvas.spare_scene = Some(scene);
|
||||
|
||||
// Once the render that draws them is submitted, its scene and effects results are free to reuse
|
||||
self.canvas.spare_scenes.push(scene);
|
||||
for image in images {
|
||||
if let SceneImage::Rendered(texture) = image {
|
||||
self.canvas.effect_textures.release(texture);
|
||||
}
|
||||
}
|
||||
|
||||
rendered
|
||||
}
|
||||
}
|
||||
|
||||
impl EffectsRenderer for RenderContext<'_> {
|
||||
fn renders_effects(&self) -> bool {
|
||||
self.renderer.effect_passes.renders_working_formats
|
||||
}
|
||||
|
||||
fn render_effects(
|
||||
&mut self,
|
||||
size: UVec2,
|
||||
view: Affine,
|
||||
effects: &Effects,
|
||||
fill: f32,
|
||||
lengths_to_pixels: DMat2,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) -> wgpu::Texture {
|
||||
let content_texture = self.canvas.effect_textures.acquire(self.device, size, TEXTURE_FORMAT);
|
||||
self.render_area(draw, view, size, &content_texture, TargetAlpha::Premultiplied);
|
||||
|
||||
// The paint overlays' paints, each rendered over the same pixels as the content
|
||||
let paint_count = effects.operations().filter(|operation| matches!(operation, EffectOperation::PaintOverlay { .. })).count();
|
||||
let paint_textures: Vec<wgpu::Texture> = (0..paint_count)
|
||||
.map(|index| {
|
||||
let paint_texture = self.canvas.effect_textures.acquire(self.device, size, TEXTURE_FORMAT);
|
||||
self.render_area(&mut |scene| draw_paint(index, scene), view, size, &paint_texture, TargetAlpha::Premultiplied);
|
||||
paint_texture
|
||||
})
|
||||
.collect();
|
||||
|
||||
let effect_textures = &mut self.canvas.effect_textures;
|
||||
let result = (self.renderer.effect_passes).apply(self.device, &self.queue.lock(), effect_textures, &content_texture, effects, fill, lengths_to_pixels, &paint_textures);
|
||||
effect_textures.release(content_texture);
|
||||
paint_textures.into_iter().for_each(|paint_texture| effect_textures.release(paint_texture));
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// Leaves `target` transparent.
|
||||
fn clear(device: &wgpu::Device, queue: &Queue, target: &wgpu::Texture) {
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_clear") });
|
||||
@@ -286,12 +365,13 @@ fn clear(device: &wgpu::Device, queue: &Queue, target: &wgpu::Texture) {
|
||||
queue.submit([encoder.finish()]);
|
||||
}
|
||||
|
||||
/// Identifies the pixels behind an image texture: a blob of CPU pixels, or a GPU texture.
|
||||
/// Identifies the pixels behind an image texture: a blob of CPU pixels, a GPU texture, or a tile of a generator's pattern.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
enum ImageKey {
|
||||
Blob(u64),
|
||||
Raster(u64),
|
||||
Texture(wgpu::Texture),
|
||||
GeneratorTile(GeneratorTile),
|
||||
}
|
||||
|
||||
/// A premultiplied copy of an image's pixels that Vello GPU samples as an external texture.
|
||||
@@ -300,6 +380,17 @@ struct ImageTexture {
|
||||
last_used: u64,
|
||||
/// The CPU raster pixels copied into the texture, which is freed once they're gone since they can't be drawn again.
|
||||
raster: Option<WeakCPU>,
|
||||
/// Copies with runs of adjustments carried out on them, one for each run the image is drawn with.
|
||||
adjusted: Vec<AdjustedTexture>,
|
||||
}
|
||||
|
||||
/// A copy of an image's texture with a run of adjustments carried out on it, made over in place for another run or refined tables.
|
||||
struct AdjustedTexture {
|
||||
texture: wgpu::Texture,
|
||||
run_hash: u64,
|
||||
/// The tables it was made with, which a run's refined tables replace.
|
||||
passes: Arc<Vec<AdjustmentPassTextures>>,
|
||||
last_used: u64,
|
||||
}
|
||||
|
||||
/// The textures of the images recent renders drew, each freed once it goes unused for long enough.
|
||||
@@ -310,21 +401,24 @@ struct ImageTextures {
|
||||
}
|
||||
|
||||
impl ImageTextures {
|
||||
/// A view of the premultiplied texture for `image`, uploading CPU pixels the first time they're drawn.
|
||||
/// A view of the premultiplied texture for `image`, uploading CPU pixels or rendering a generator's tile the first time they're drawn.
|
||||
/// GPU textures are converted again at every render since the texture cache hands their textures out again with new contents.
|
||||
fn prepare(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
alpha_conversion: &AlphaConversion,
|
||||
renderer: &VelloRenderer,
|
||||
image: &SceneImage,
|
||||
max_texture_size: u32,
|
||||
) -> Option<wgpu::TextureView> {
|
||||
let key = match image {
|
||||
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
|
||||
SceneImage::Raster(raster) => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::Raster { raster, .. } => ImageKey::Raster(raster.buffer_id()),
|
||||
SceneImage::Texture(texture) => ImageKey::Texture((**texture).clone()),
|
||||
SceneImage::GeneratorTile { tile, .. } => ImageKey::GeneratorTile(*tile),
|
||||
// Effects results are premultiplied already
|
||||
SceneImage::Rendered(texture) => return Some(texture.create_view(&wgpu::TextureViewDescriptor::default())),
|
||||
};
|
||||
|
||||
if !self.textures.contains_key(&key) {
|
||||
@@ -337,10 +431,25 @@ impl ImageTextures {
|
||||
|
||||
upload_pixels(device, queue, data.data.data(), data.width, data.height, data.alpha_type, max_texture_size)?
|
||||
}
|
||||
SceneImage::Raster(raster) => {
|
||||
SceneImage::Raster { raster, .. } => {
|
||||
let (pixels, width, height) = raster.to_flat_u8();
|
||||
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
SceneImage::GeneratorTile { pattern, tile } => {
|
||||
// Rendered on the GPU, or on the CPU where 32-bit floats can't place its pixels
|
||||
let (corner, texel) = tile.corner_and_texel();
|
||||
match renderer.generator_passes.render_tile(device, encoder, pattern, corner, texel, GeneratorTile::SAMPLES) {
|
||||
Some(texture) => {
|
||||
renderer.effect_passes.record_mipmaps(device, encoder, &texture);
|
||||
texture
|
||||
}
|
||||
None => {
|
||||
let (pixels, width, height) = tile.render(pattern).ok()?.to_flat_u8();
|
||||
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
|
||||
}
|
||||
}
|
||||
}
|
||||
SceneImage::Rendered(_) => return None,
|
||||
SceneImage::Texture(texture) => create_texture(
|
||||
device,
|
||||
"vello_gpu_premultiplied_image",
|
||||
@@ -349,10 +458,18 @@ impl ImageTextures {
|
||||
),
|
||||
};
|
||||
let raster = match image {
|
||||
SceneImage::Raster(raster) => Some(raster.downgrade()),
|
||||
SceneImage::Pixels(_) | SceneImage::Texture(_) => None,
|
||||
SceneImage::Raster { raster, .. } => Some(raster.downgrade()),
|
||||
SceneImage::Pixels(_) | SceneImage::Texture(_) | SceneImage::Rendered(_) | SceneImage::GeneratorTile { .. } => None,
|
||||
};
|
||||
self.textures.insert(key.clone(), ImageTexture { texture, last_used: 0, raster });
|
||||
self.textures.insert(
|
||||
key.clone(),
|
||||
ImageTexture {
|
||||
texture,
|
||||
last_used: 0,
|
||||
raster,
|
||||
adjusted: Vec::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let image_texture = self.textures.get_mut(&key)?;
|
||||
@@ -361,23 +478,90 @@ impl ImageTextures {
|
||||
|
||||
if let SceneImage::Texture(source) = image {
|
||||
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
alpha_conversion.premultiply(device, encoder, &source_view, source.format().is_srgb(), &view);
|
||||
renderer.alpha_conversion.premultiply(device, encoder, &source_view, source.format().is_srgb(), &view);
|
||||
}
|
||||
|
||||
Some(view)
|
||||
}
|
||||
|
||||
/// A view of the copy of the texture of the `raster` already prepared, with the `run` of adjustments carried out on it, made with the run's latest tables.
|
||||
fn prepare_adjusted(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, effects: (&EffectPasses, &mut EffectTextures), raster: &Raster<CPU>, run: &[Adjustment]) -> Option<wgpu::TextureView> {
|
||||
let (effect_passes, effect_textures) = effects;
|
||||
let run: Vec<&Adjustment> = run.iter().collect();
|
||||
let run_hash = adjustment_run_hash(&run);
|
||||
let passes = effect_textures.adjustment_passes(device, queue, &run);
|
||||
let render_count = self.render_count;
|
||||
let image_texture = self.textures.get_mut(&ImageKey::Raster(raster.buffer_id()))?;
|
||||
|
||||
// A run seen before has its copy, and a new run takes over the copy longest unused, as when dragging a slider makes a new run every render
|
||||
let reusable = || {
|
||||
image_texture
|
||||
.adjusted
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, copy)| copy.last_used < render_count)
|
||||
.min_by_key(|(_, copy)| copy.last_used)
|
||||
};
|
||||
let index = match image_texture.adjusted.iter().position(|copy| copy.run_hash == run_hash) {
|
||||
Some(index) => index,
|
||||
None => match reusable().map(|(index, _)| index) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("vello_gpu_adjusted_image"),
|
||||
size: image_texture.texture.size(),
|
||||
mip_level_count: image_texture.texture.mip_level_count(),
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
});
|
||||
image_texture.adjusted.push(AdjustedTexture {
|
||||
texture,
|
||||
run_hash,
|
||||
passes: Arc::new(Vec::new()),
|
||||
last_used: render_count,
|
||||
});
|
||||
image_texture.adjusted.len() - 1
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let copy = &mut image_texture.adjusted[index];
|
||||
if copy.run_hash != run_hash || !Arc::ptr_eq(©.passes, &passes) {
|
||||
effect_passes.adjust_image(device, queue, effect_textures, &image_texture.texture, &passes, ©.texture);
|
||||
copy.run_hash = run_hash;
|
||||
copy.passes = passes;
|
||||
}
|
||||
copy.last_used = render_count;
|
||||
|
||||
Some(copy.texture.create_view(&wgpu::TextureViewDescriptor::default()))
|
||||
}
|
||||
|
||||
fn free_unused(&mut self) {
|
||||
let render_count = self.render_count;
|
||||
self.textures.retain(|key, image_texture| {
|
||||
let unused_renders = render_count - image_texture.last_used;
|
||||
match key {
|
||||
// CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return
|
||||
ImageKey::Blob(_) => unused_renders == 0,
|
||||
ImageKey::Raster(_) => unused_renders == 0 || (unused_renders < UNUSED_IMAGE_RENDER_LIMIT && image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive)),
|
||||
ImageKey::Texture(_) => unused_renders < UNUSED_IMAGE_RENDER_LIMIT,
|
||||
}
|
||||
let in_use = |last_used: u64| render_count - last_used < UNUSED_IMAGE_RENDER_LIMIT;
|
||||
|
||||
self.textures.retain(|key, image_texture| match key {
|
||||
// CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return
|
||||
ImageKey::Blob(_) => image_texture.last_used == render_count,
|
||||
ImageKey::Raster(_) => image_texture.last_used == render_count || (in_use(image_texture.last_used) && image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive)),
|
||||
ImageKey::Texture(_) | ImageKey::GeneratorTile(_) => in_use(image_texture.last_used),
|
||||
});
|
||||
self.textures.values_mut().for_each(|image_texture| image_texture.adjusted.retain(|copy| in_use(copy.last_used)));
|
||||
|
||||
// Panning and zooming across a generator leaves tiles behind faster than they go unused for long, so the least recent beyond a limit are freed too
|
||||
let mut tile_ages: Vec<u64> = (self.textures.iter())
|
||||
.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_)))
|
||||
.map(|(_, image_texture)| image_texture.last_used)
|
||||
.collect();
|
||||
if tile_ages.len() > MAX_CACHED_GENERATOR_TILES {
|
||||
let excess = tile_ages.len() - MAX_CACHED_GENERATOR_TILES;
|
||||
let (_, &mut oldest_kept, _) = tile_ages.select_nth_unstable(excess);
|
||||
self.textures
|
||||
.retain(|key, image_texture| !matches!(key, ImageKey::GeneratorTile(_)) || image_texture.last_used >= oldest_kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -274,6 +274,697 @@ fn degenerate_strokes_render() {
|
||||
let Some(_) = render(size, draw) else { return };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dial_gradients_match_their_cpu_evaluation() {
|
||||
use rendering::dial_gradient::PencilParameters;
|
||||
|
||||
let size = UVec2::new(200, 200);
|
||||
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100)
|
||||
let gradient_to_pixels = Affine::new([50., 0., 0., 50., 60., 100.]);
|
||||
|
||||
for dials in [(1., 0.6), (0.6, 0.6), (-0.5, 0.2952), (1., 1.), (0.5, 0.25), (0.3, -0.3)] {
|
||||
let parameters = PencilParameters::new(dials.0, dials.1);
|
||||
let ramp = peniko::Gradient::new_linear((0., 0.), (1., 0.)).with_stops([Color::from_rgb8(0, 0, 0), Color::from_rgb8(255, 255, 255)]);
|
||||
let gradient = vello_gpu::PencilGradient {
|
||||
ramp,
|
||||
geometry: parameters.to_vello(),
|
||||
};
|
||||
|
||||
let draw = |scene: &mut VelloSceneBuilder| scene.fill_viewport(gradient.clone(), Some(gradient_to_pixels));
|
||||
|
||||
let Some(pixels) = render(size, draw) else { return };
|
||||
|
||||
let mut worst = 0_i32;
|
||||
for y in (5..195).step_by(10) {
|
||||
for x in (5..195).step_by(10) {
|
||||
let point = gradient_to_pixels.inverse() * vello_gpu::kurbo::Point::new(x as f64 + 0.5, y as f64 + 0.5);
|
||||
let t = parameters.t(glam::DVec2::new(point.x, point.y)).clamp(0., 1.);
|
||||
let expected = (t * 255.).round() as i32;
|
||||
let actual = pixel(&pixels, size, x, y)[0] as i32;
|
||||
worst = worst.max((expected - actual).abs());
|
||||
}
|
||||
}
|
||||
assert!(worst <= 3, "dials {dials:?} differ from the CPU evaluation by up to {worst} levels");
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders an opaque white square from (`min`, `min`) to (`max`, `max`) through `effects` with `fill`.
|
||||
fn render_square_with_effects(effects: Vec<graphic_types::EffectOperation>, fill: f32, min: f64, max: f64, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let square = Rect::new(min, min, max, max);
|
||||
|
||||
// The paint overlays' paints, drawn as the renderer does for content placed in the scene's space
|
||||
let paints: Vec<graphic_types::Graphic> = (effects.iter())
|
||||
.filter_map(|operation| match operation {
|
||||
graphic_types::EffectOperation::PaintOverlay { paint, .. } => Some(paint),
|
||||
_ => None,
|
||||
})
|
||||
.map(|paint| graphic_types::fitted_paint(paint, [glam::DVec2::splat(min), glam::DVec2::splat(max)]).unwrap_or_else(|| paint.clone()))
|
||||
.collect();
|
||||
let mut draw_paint = |index: usize, scene: &mut VelloSceneBuilder| {
|
||||
if let Some(paint) = paints.get(index) {
|
||||
paint.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default().for_pattern());
|
||||
}
|
||||
};
|
||||
|
||||
let effects = graphic_types::Effects::from_operations(effects);
|
||||
render(size, |scene| {
|
||||
scene.draw_effects(&effects, fill, Some(square), &mut draw_paint, &mut |scene| {
|
||||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
/// The standard normal cumulative distribution, from the Abramowitz and Stegun approximation of the error function, accurate to 1e-7.
|
||||
fn normal_cdf(x: f64) -> f64 {
|
||||
let z = x.abs() / std::f64::consts::SQRT_2;
|
||||
let t = 1. / (1. + 0.327_591_1 * z);
|
||||
let polynomial = t * (0.254_829_592 + t * (-0.284_496_736 + t * (1.421_413_741 + t * (-1.453_152_027 + t * 1.061_405_429))));
|
||||
let erf = 1. - polynomial * (-z * z).exp();
|
||||
|
||||
if x >= 0. { 0.5 * (1. + erf) } else { 0.5 * (1. - erf) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaussian_blur_follows_the_normal_distribution() {
|
||||
use graphic_types::EffectOperation;
|
||||
|
||||
let size = UVec2::new(512, 256);
|
||||
// Small kernels run directly, and larger ones on halved textures
|
||||
for sigma in [2., 6., 20.] {
|
||||
let blur = EffectOperation::Blur {
|
||||
radius: sigma,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
// A square much larger than the blur, so across its left edge at x = 100, on a row far from its other edges, the coverage is the one-dimensional profile
|
||||
let Some(pixels) = render_square_with_effects(vec![blur], 1., 100., 400., size) else { return };
|
||||
|
||||
let mut worst = 0_f64;
|
||||
for x in 40..160 {
|
||||
let expected = normal_cdf((x as f64 + 0.5 - 100.) / sigma);
|
||||
let actual = pixel(&pixels, size, x, 200)[3] as f64 / 255.;
|
||||
worst = worst.max((expected - actual).abs());
|
||||
}
|
||||
assert!(worst < 0.03, "σ {sigma} strays from the normal distribution by {worst}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadows_and_glows_fall_where_they_should() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use glam::DVec2;
|
||||
use graphic_types::EffectOperation;
|
||||
|
||||
let size = UVec2::new(128, 128);
|
||||
let black = GraphicColor::BLACK;
|
||||
|
||||
// A hard drop shadow offset down and right shows past the square's bottom right corner, beneath it
|
||||
let shadow = EffectOperation::DropShadow {
|
||||
color: black,
|
||||
offset: DVec2::new(10., 10.),
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
};
|
||||
let Some(pixels) = render_square_with_effects(vec![shadow.clone()], 1., 30., 80., size) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(pixel(&pixels, size, 50, 50), [255, 255, 255, 255], "the content covers its shadow");
|
||||
assert_eq!(pixel(&pixels, size, 85, 85), [0, 0, 0, 255], "the shadow shows past the content");
|
||||
assert_eq!(pixel(&pixels, size, 25, 25)[3], 0, "no shadow before the offset");
|
||||
|
||||
// With no fill, the content vanishes and its shadow stays knocked out where the content would be
|
||||
let Some(pixels) = render_square_with_effects(vec![shadow], 0., 30., 80., size) else { return };
|
||||
assert_eq!(pixel(&pixels, size, 50, 50)[3], 0, "the shadow is knocked out by the faded content");
|
||||
assert_eq!(pixel(&pixels, size, 85, 85), [0, 0, 0, 255], "the shadow stays at full strength");
|
||||
|
||||
// An inner shadow darkens the content's top left edges from inside and stays within it
|
||||
let inner_shadow = EffectOperation::InnerShadow {
|
||||
color: black,
|
||||
offset: DVec2::new(6., 6.),
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
};
|
||||
let Some(pixels) = render_square_with_effects(vec![inner_shadow], 1., 30., 80., size) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(pixel(&pixels, size, 32, 50), [0, 0, 0, 255], "inside the left edge");
|
||||
assert_eq!(pixel(&pixels, size, 50, 50), [255, 255, 255, 255], "deep inside");
|
||||
assert_eq!(pixel(&pixels, size, 78, 50), [255, 255, 255, 255], "inside the right edge, away from the offset");
|
||||
assert_eq!(pixel(&pixels, size, 25, 50)[3], 0, "outside");
|
||||
|
||||
// A glow grown by its spread surrounds the content evenly
|
||||
let glow = EffectOperation::OuterGlow {
|
||||
color: GraphicColor::from_rgbaf32_unchecked(1., 0., 0., 1.),
|
||||
blur: 0.,
|
||||
spread: 5.,
|
||||
};
|
||||
let Some(pixels) = render_square_with_effects(vec![glow], 1., 30., 80., size) else { return };
|
||||
for (x, y) in [(27, 55), (82, 55), (55, 27), (55, 82)] {
|
||||
assert_eq!(pixel(&pixels, size, x, y), [255, 0, 0, 255], "glow at ({x}, {y})");
|
||||
}
|
||||
for (x, y) in [(23, 55), (87, 55)] {
|
||||
assert_eq!(pixel(&pixels, size, x, y)[3], 0, "past the glow at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inner_glows_satins_outlines_and_bevels_fall_where_they_should() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use glam::DVec2;
|
||||
use graphic_types::vector_types::vector::style::StrokeAlign;
|
||||
use graphic_types::{BevelDirection, BevelStyle, EffectOperation, GlowSource};
|
||||
|
||||
let size = UVec2::new(128, 128);
|
||||
let black = GraphicColor::BLACK;
|
||||
let render_square = |effect| render_square_with_effects(vec![effect], 1., 30., 80., size);
|
||||
let (white, clear) = ([255, 255, 255, 255], 0);
|
||||
|
||||
// A hard inner glow from the edges covers a band inside them, and one from the center covers the rest
|
||||
let inner_glow = |source| EffectOperation::InnerGlow {
|
||||
color: black,
|
||||
blur: 0.,
|
||||
choke: 3.,
|
||||
source,
|
||||
};
|
||||
let Some(pixels) = render_square(inner_glow(GlowSource::Edge)) else { return };
|
||||
assert_eq!(pixel(&pixels, size, 31, 55), [0, 0, 0, 255], "the edge glows");
|
||||
assert_eq!(pixel(&pixels, size, 55, 55), white, "the center doesn't");
|
||||
assert_eq!(pixel(&pixels, size, 25, 55)[3], clear, "nothing outside");
|
||||
let Some(pixels) = render_square(inner_glow(GlowSource::Center)) else { return };
|
||||
assert_eq!(pixel(&pixels, size, 31, 55), white, "the edge doesn't glow");
|
||||
assert_eq!(pixel(&pixels, size, 55, 55), [0, 0, 0, 255], "the center does");
|
||||
|
||||
// Satin shades where the two casts of the silhouette disagree, which for a horizontal offset is a band along each side
|
||||
let satin = EffectOperation::Satin {
|
||||
color: black,
|
||||
offset: DVec2::new(10., 0.),
|
||||
blur: 0.,
|
||||
invert: false,
|
||||
};
|
||||
let Some(pixels) = render_square(satin) else { return };
|
||||
assert_eq!(pixel(&pixels, size, 35, 55), [0, 0, 0, 255], "the left band");
|
||||
assert_eq!(pixel(&pixels, size, 55, 55), white, "the middle, where both casts cover");
|
||||
assert_eq!(pixel(&pixels, size, 75, 55), [0, 0, 0, 255], "the right band");
|
||||
|
||||
// An outline outside the edge rounds the corners it grows around, and one inside stays within the content
|
||||
let outline = |align| EffectOperation::Outline { color: black, weight: 5., align };
|
||||
let Some(pixels) = render_square(outline(StrokeAlign::Outside)) else { return };
|
||||
assert_eq!(pixel(&pixels, size, 26, 55), [0, 0, 0, 255], "within the weight of the edge");
|
||||
assert_eq!(pixel(&pixels, size, 23, 55)[3], clear, "past the weight");
|
||||
assert_eq!(pixel(&pixels, size, 27, 27), [0, 0, 0, 255], "near the corner");
|
||||
assert!(pixel(&pixels, size, 26, 26)[3] < 128, "beyond the rounded corner, where a square would reach");
|
||||
assert_eq!(pixel(&pixels, size, 55, 55), white, "the content shows");
|
||||
let Some(pixels) = render_square(outline(StrokeAlign::Inside)) else { return };
|
||||
assert_eq!(pixel(&pixels, size, 32, 55), [0, 0, 0, 255], "inside the edge");
|
||||
assert_eq!(pixel(&pixels, size, 40, 55), white, "past the weight inside");
|
||||
assert_eq!(pixel(&pixels, size, 28, 55)[3], clear, "nothing outside");
|
||||
|
||||
// Lit from the upper left, a raised bevel's top slope catches the highlight and its bottom slope falls into shadow, which swap when it sinks
|
||||
let bevel = |style, direction| EffectOperation::BevelAndEmboss {
|
||||
style,
|
||||
depth: 100.,
|
||||
direction,
|
||||
size: 5.,
|
||||
soften: 0.,
|
||||
angle: 120.,
|
||||
altitude: 30.,
|
||||
highlight_color: GraphicColor::RED,
|
||||
shadow_color: GraphicColor::BLUE,
|
||||
};
|
||||
let reddish = |[red, green, blue, alpha]: [u8; 4]| red > 200 && green < 128 && blue < 128 && alpha > 128;
|
||||
let bluish = |[red, green, blue, alpha]: [u8; 4]| blue > 200 && red < 128 && green < 128 && alpha > 128;
|
||||
let Some(pixels) = render_square(bevel(BevelStyle::InnerBevel, BevelDirection::Up)) else { return };
|
||||
assert!(reddish(pixel(&pixels, size, 55, 32)), "the top slope is highlighted: {:?}", pixel(&pixels, size, 55, 32));
|
||||
assert!(bluish(pixel(&pixels, size, 55, 77)), "the bottom slope is shaded: {:?}", pixel(&pixels, size, 55, 77));
|
||||
assert_eq!(pixel(&pixels, size, 55, 55), white, "the flat top inside the slopes is unlit");
|
||||
assert_eq!(pixel(&pixels, size, 55, 20)[3], clear, "nothing outside");
|
||||
let Some(pixels) = render_square(bevel(BevelStyle::InnerBevel, BevelDirection::Down)) else {
|
||||
return;
|
||||
};
|
||||
assert!(bluish(pixel(&pixels, size, 55, 32)), "a sunken top slope is shaded: {:?}", pixel(&pixels, size, 55, 32));
|
||||
assert!(reddish(pixel(&pixels, size, 55, 77)), "a sunken bottom slope is highlighted: {:?}", pixel(&pixels, size, 55, 77));
|
||||
|
||||
// An outer bevel's slopes lie outside the content, beneath it
|
||||
let Some(pixels) = render_square(bevel(BevelStyle::OuterBevel, BevelDirection::Up)) else { return };
|
||||
assert!(reddish(pixel(&pixels, size, 55, 27)), "the top slope outside is highlighted: {:?}", pixel(&pixels, size, 55, 27));
|
||||
assert!(bluish(pixel(&pixels, size, 55, 82)), "the bottom slope outside is shaded: {:?}", pixel(&pixels, size, 55, 82));
|
||||
assert_eq!(pixel(&pixels, size, 55, 40), white, "the content inside is unlit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlays_stretch_unplaced_paints_across_the_content() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::Item;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||||
use graphic_types::{EffectOperation, Graphic};
|
||||
|
||||
let size = UVec2::new(128, 128);
|
||||
let overlay = |paint: Graphic| EffectOperation::PaintOverlay {
|
||||
paint,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
};
|
||||
let reddish = |[red, green, blue, alpha]: [u8; 4]| red > 200 && green < 64 && blue < 64 && alpha == 255;
|
||||
let bluish = |[red, green, blue, alpha]: [u8; 4]| blue > 200 && red < 64 && green < 64 && alpha == 255;
|
||||
|
||||
// A gradient from red to blue runs from the square's left edge to its right edge
|
||||
let stops = [(0., GraphicColor::RED), (1., GraphicColor::BLUE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||||
let Some(pixels) = render_square_with_effects(vec![overlay(Graphic::from(Gradient::new(stops)))], 1., 30., 80., size) else {
|
||||
return;
|
||||
};
|
||||
assert!(reddish(pixel(&pixels, size, 31, 55)), "the start at the left edge: {:?}", pixel(&pixels, size, 31, 55));
|
||||
assert!(bluish(pixel(&pixels, size, 78, 55)), "the end at the right edge: {:?}", pixel(&pixels, size, 78, 55));
|
||||
assert_eq!(pixel(&pixels, size, 25, 55)[3], 0, "nothing outside the content");
|
||||
|
||||
// An image of a red pixel beside a blue one covers the square, each pixel half of it
|
||||
let image = Image {
|
||||
width: 2,
|
||||
height: 1,
|
||||
data: vec![GraphicColor::RED, GraphicColor::BLUE],
|
||||
};
|
||||
let Some(pixels) = render_square_with_effects(vec![overlay(Graphic::from(Item::new_from_element(Raster::new_cpu(image))))], 1., 30., 80., size) else {
|
||||
return;
|
||||
};
|
||||
assert!(reddish(pixel(&pixels, size, 35, 40)), "the left half: {:?}", pixel(&pixels, size, 35, 40));
|
||||
assert!(bluish(pixel(&pixels, size, 75, 70)), "the right half: {:?}", pixel(&pixels, size, 75, 70));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_shadows_stack_over_earlier_ones_beneath_the_content() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use glam::DVec2;
|
||||
use graphic_types::EffectOperation;
|
||||
|
||||
let size = UVec2::new(128, 128);
|
||||
let shadow = |color, offset: f64| EffectOperation::DropShadow {
|
||||
color,
|
||||
offset: DVec2::splat(offset),
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
};
|
||||
|
||||
// Both shadows are cast from the content rather than from each other, and the later one is on top where they overlap
|
||||
let effects = vec![shadow(GraphicColor::BLACK, 10.), shadow(GraphicColor::from_rgbaf32_unchecked(0., 0., 1., 1.), 5.)];
|
||||
let Some(pixels) = render_square_with_effects(effects, 1., 30., 80., size) else { return };
|
||||
assert_eq!(pixel(&pixels, size, 82, 82), [0, 0, 255, 255], "the later shadow is on top");
|
||||
assert_eq!(pixel(&pixels, size, 88, 88), [0, 0, 0, 255], "the earlier shadow reaches further");
|
||||
assert_eq!(pixel(&pixels, size, 93, 93)[3], 0, "no shadow of a shadow");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_effects_groups_render_inside_out() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use glam::DVec2;
|
||||
use graphic_types::{EffectOperation, Effects};
|
||||
|
||||
let size = UVec2::new(128, 128);
|
||||
let square = Rect::new(30., 30., 80., 80.);
|
||||
|
||||
// A hard shadow around a group whose content is itself a blurred square
|
||||
let shadow = Effects::from_operations([EffectOperation::DropShadow {
|
||||
color: GraphicColor::BLACK,
|
||||
offset: DVec2::new(20., 0.),
|
||||
blur: 0.,
|
||||
spread: 0.,
|
||||
}]);
|
||||
let blur = Effects::from_operations([EffectOperation::Blur {
|
||||
radius: 3.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
}]);
|
||||
let draw = |scene: &mut VelloSceneBuilder| {
|
||||
scene.draw_effects(&shadow, 1., Some(square.inflate(12., 12.)), &mut |_, _| {}, &mut |scene| {
|
||||
scene.draw_effects(&blur, 1., Some(square), &mut |_, _| {}, &mut |scene| {
|
||||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
let Some(pixels) = render(size, draw) else { return };
|
||||
let edge = pixel(&pixels, size, 30, 55);
|
||||
assert!((100..=155).contains(&edge[3]), "the blur softens the edge to half coverage, not {edge:?}");
|
||||
// Ten pixels past the content's blurred edge, where the shadow is cast from ten pixels inside it
|
||||
let shadow = pixel(&pixels, size, 90, 55);
|
||||
assert!(shadow[3] >= 250 && shadow[0] <= 5, "the shadow is cast by the blurred group, not {shadow:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::ATTR_GRADIENT_FORM;
|
||||
use core_types::list::{ATTR_EFFECTS, Item};
|
||||
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM};
|
||||
use glam::DVec2;
|
||||
use graphic_types::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientForm, GradientStop};
|
||||
use graphic_types::vector_types::vector::style::StrokeAlign;
|
||||
use graphic_types::{BevelDirection, BevelStyle, EffectOperation, Effects, GlowSource, Graphic};
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
|
||||
let size = UVec2::new(160, 160);
|
||||
let (min, max) = (50, 100);
|
||||
let shadow_color = GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75);
|
||||
let blur = |radius, box_blur, gamma| EffectOperation::Blur { radius, box_blur, gamma };
|
||||
let bevel = |style, direction, size, soften| EffectOperation::BevelAndEmboss {
|
||||
style,
|
||||
depth: 150.,
|
||||
direction,
|
||||
size,
|
||||
soften,
|
||||
angle: 120.,
|
||||
altitude: 30.,
|
||||
highlight_color: GraphicColor::from_rgbaf32_unchecked(1., 0.9, 0.2, 0.75),
|
||||
shadow_color,
|
||||
};
|
||||
let identity = LevelsRecord {
|
||||
shadows: 0.,
|
||||
midtones: 1.,
|
||||
highlights: 100.,
|
||||
output_minimums: 0.,
|
||||
output_maximums: 100.,
|
||||
};
|
||||
|
||||
let cases = [
|
||||
vec![blur(3., false, false)],
|
||||
vec![blur(20., false, true)],
|
||||
vec![blur(5.5, true, false)],
|
||||
vec![EffectOperation::DropShadow {
|
||||
color: shadow_color,
|
||||
offset: DVec2::new(6.5, -3.),
|
||||
blur: 4.,
|
||||
spread: 2.,
|
||||
}],
|
||||
vec![EffectOperation::InnerShadow {
|
||||
color: shadow_color,
|
||||
offset: DVec2::new(4., 4.),
|
||||
blur: 3.,
|
||||
spread: 0.,
|
||||
}],
|
||||
vec![
|
||||
EffectOperation::OuterGlow {
|
||||
color: shadow_color,
|
||||
blur: 6.,
|
||||
spread: 3.,
|
||||
},
|
||||
blur(2., false, false),
|
||||
],
|
||||
vec![EffectOperation::InnerGlow {
|
||||
color: shadow_color,
|
||||
blur: 5.,
|
||||
choke: 2.,
|
||||
source: GlowSource::Edge,
|
||||
}],
|
||||
vec![EffectOperation::InnerGlow {
|
||||
color: shadow_color,
|
||||
blur: 8.,
|
||||
choke: 0.,
|
||||
source: GlowSource::Center,
|
||||
}],
|
||||
vec![EffectOperation::Satin {
|
||||
color: shadow_color,
|
||||
offset: DVec2::new(7., 3.),
|
||||
blur: 6.,
|
||||
invert: true,
|
||||
}],
|
||||
vec![EffectOperation::Satin {
|
||||
color: shadow_color,
|
||||
offset: DVec2::new(-4., 9.),
|
||||
blur: 3.,
|
||||
invert: false,
|
||||
}],
|
||||
vec![EffectOperation::Outline {
|
||||
color: shadow_color,
|
||||
weight: 6.,
|
||||
align: StrokeAlign::Outside,
|
||||
}],
|
||||
vec![EffectOperation::Outline {
|
||||
color: shadow_color,
|
||||
weight: 5.,
|
||||
align: StrokeAlign::Inside,
|
||||
}],
|
||||
vec![EffectOperation::Outline {
|
||||
color: shadow_color,
|
||||
weight: 9.,
|
||||
align: StrokeAlign::Center,
|
||||
}],
|
||||
vec![bevel(BevelStyle::InnerBevel, BevelDirection::Up, 8., 0.)],
|
||||
vec![bevel(BevelStyle::OuterBevel, BevelDirection::Down, 6., 2.)],
|
||||
vec![bevel(BevelStyle::Emboss, BevelDirection::Up, 10., 0.)],
|
||||
vec![bevel(BevelStyle::PillowEmboss, BevelDirection::Up, 12., 1.)],
|
||||
// Bends alpha, so the fill must fade the content before it on both
|
||||
vec![EffectOperation::Adjustment(Adjustment::Levels(Box::new(LevelsSettings {
|
||||
composite: identity,
|
||||
red: identity,
|
||||
green: identity,
|
||||
blue: identity,
|
||||
alpha: LevelsRecord { midtones: 2.2, ..identity },
|
||||
})))],
|
||||
];
|
||||
|
||||
// Paint overlays over a colored backdrop, their paints placed on their own since the raster and the square fit unplaced paints to different bounds
|
||||
let backdrop = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: GraphicColor::from_rgbaf32_unchecked(0.3, 0.6, 0.2, 1.),
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let gradient = |form: GradientForm, transform: DAffine2| {
|
||||
let stops = [(0., [0.9, 0.1, 0.4, 1.]), (0.5, [0.2, 0.3, 0.9, 0.5]), (1., [1., 0.9, 0.7, 1.])].map(|(position, [red, green, blue, alpha])| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: GraphicColor::from_rgbaf32_unchecked(red, green, blue, alpha),
|
||||
});
|
||||
let item = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform);
|
||||
Graphic::from(item.with_attribute(ATTR_GRADIENT_FORM, form))
|
||||
};
|
||||
let linear = gradient(GradientForm::Linear, DAffine2::from_translation(DVec2::new(45., 60.)) * DAffine2::from_scale(DVec2::splat(60.)));
|
||||
let radial = gradient(GradientForm::Radial, DAffine2::from_translation(DVec2::splat(75.)) * DAffine2::from_scale(DVec2::splat(30.)));
|
||||
|
||||
// A checkerboard with a pixel for each of the square's, so sampling it needs no interpolation
|
||||
let checker = Image {
|
||||
width: 50,
|
||||
height: 50,
|
||||
data: (0..2500)
|
||||
.map(|index| match (index % 50 / 5 + index / 50 / 5) % 2 {
|
||||
0 => GraphicColor::RED,
|
||||
_ => GraphicColor::from_rgbaf32_unchecked(0., 0., 1., 0.5),
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let checker_placement = DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_scale(DVec2::splat(50.));
|
||||
let checker = Graphic::from(Item::new_from_element(Raster::new_cpu(checker)).with_attribute(ATTR_TRANSFORM, checker_placement));
|
||||
|
||||
let overlay = |paint: &Graphic, blend_mode, opacity| {
|
||||
vec![
|
||||
backdrop.clone(),
|
||||
EffectOperation::PaintOverlay {
|
||||
paint: paint.clone(),
|
||||
blend_mode,
|
||||
opacity,
|
||||
},
|
||||
]
|
||||
};
|
||||
// Hard Mix's threshold and the hue of the gradient's grays turn the slightest rounding into large differences, so they take the checkerboard's exact colors instead
|
||||
let ill_conditioned = [BlendMode::HardMix, BlendMode::Hue];
|
||||
let mut paint_cases: Vec<_> = (BlendMode::list().into_iter().flatten())
|
||||
.filter(|blend_mode| !ill_conditioned.contains(blend_mode))
|
||||
.map(|&blend_mode| overlay(&linear, blend_mode, 100.))
|
||||
.collect();
|
||||
paint_cases.extend(ill_conditioned.map(|blend_mode| overlay(&checker, blend_mode, 100.)));
|
||||
paint_cases.extend([
|
||||
overlay(&linear, BlendMode::Normal, 40.),
|
||||
overlay(&radial, BlendMode::Multiply, 100.),
|
||||
overlay(&checker, BlendMode::Screen, 100.),
|
||||
]);
|
||||
|
||||
for effects in cases.into_iter().chain(paint_cases) {
|
||||
for fill in [1., 0.5] {
|
||||
let Some(gpu) = render_square_with_effects(effects.clone(), fill, min as f64, max as f64, size) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// The same square as a raster covering the render one pixel to one pixel
|
||||
let mut image = Image::new(size.x, size.y, GraphicColor::TRANSPARENT);
|
||||
for y in min..max {
|
||||
for x in min..max {
|
||||
image.data[(y * size.x + x) as usize] = GraphicColor::WHITE;
|
||||
}
|
||||
}
|
||||
let item = Item::new_from_element(Raster::new_cpu(image))
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(size.as_dvec2()))
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations(effects.clone()))
|
||||
.with_attribute(ATTR_OPACITY_FILL, fill as f64);
|
||||
let evaluated = evaluate_raster_effects(item);
|
||||
|
||||
// Reads the evaluated image at the center of each render pixel through its grown placement
|
||||
let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let raster = evaluated.element();
|
||||
let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse();
|
||||
|
||||
let mut worst = 0;
|
||||
for y in 0..size.y {
|
||||
for x in 0..size.x {
|
||||
let point = document_to_pixels.transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5)).floor();
|
||||
let cpu = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize];
|
||||
let [red, green, blue, alpha] = cpu.to_gamma_srgb_channels();
|
||||
let cpu = [red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.);
|
||||
|
||||
// Compared premultiplied, so a nearly transparent pixel's color can't dominate
|
||||
let gpu = pixel(&gpu, size, x, y);
|
||||
let gpu_alpha = gpu[3] as f32 / 255.;
|
||||
for channel in 0..4 {
|
||||
let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha };
|
||||
worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Modes that divide, or land near black where the gamma encoding is steepest, amplify the rounding of the rendered paint's eight bits
|
||||
use BlendMode::*;
|
||||
let tolerance = match effects.last() {
|
||||
Some(EffectOperation::PaintOverlay { blend_mode: VividLight, .. }) => 16,
|
||||
Some(EffectOperation::PaintOverlay {
|
||||
blend_mode: ColorBurn | LinearBurn | ColorDodge | HardLight | LinearLight | PinLight,
|
||||
..
|
||||
}) => 8,
|
||||
_ => 2,
|
||||
};
|
||||
assert!(worst <= tolerance, "{effects:?} at fill {fill} differs from the GPU by up to {worst} levels");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_adjustment_passes_match_the_cpu_kernels() {
|
||||
use core_types::Color as GraphicColor;
|
||||
use core_types::list::Item;
|
||||
use graphic_types::adjustment::*;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::{EffectOperation, Effects};
|
||||
|
||||
// Opaque colors spread across the RGB cube, one per pixel, on whole 8-bit levels as the content's 8-bit render holds them
|
||||
let size = UVec2::new(64, 64);
|
||||
let channel = |value: u32| ((value % 64) * 4) as f32 / 255.;
|
||||
let colors: Vec<GraphicColor> = (0..size.x * size.y)
|
||||
.map(|index| GraphicColor::from_gamma_srgb_channels(channel(index % 64), channel(index / 64), channel(index * 7 + index / 64 * 13), 1.))
|
||||
.collect();
|
||||
let raster = Raster::new_cpu(Image {
|
||||
width: size.x,
|
||||
height: size.y,
|
||||
data: colors.clone(),
|
||||
});
|
||||
|
||||
let levels_record = |shadows, midtones, highlights| LevelsRecord {
|
||||
shadows,
|
||||
midtones,
|
||||
highlights,
|
||||
output_minimums: 0.,
|
||||
output_maximums: 100.,
|
||||
};
|
||||
let identity = levels_record(0., 1., 100.);
|
||||
let sliders = |hue, saturation, lightness| HueSaturationSliders { hue, saturation, lightness };
|
||||
let range = |sliders, falloff_start, range_start, range_end, falloff_end| HueRangeSettings {
|
||||
sliders,
|
||||
falloff_start,
|
||||
range_start,
|
||||
range_end,
|
||||
falloff_end,
|
||||
};
|
||||
let zero = sliders(0., 0., 0.);
|
||||
|
||||
// Each run with the most levels it may stray: curves and luma tables by under a level, the cube by its interpolation
|
||||
let runs: Vec<(Vec<Adjustment>, u8)> = vec![
|
||||
(
|
||||
vec![
|
||||
Adjustment::Levels(Box::new(LevelsSettings {
|
||||
composite: levels_record(10., 1.4, 90.),
|
||||
red: identity,
|
||||
green: levels_record(5., 0.8, 100.),
|
||||
blue: identity,
|
||||
alpha: identity,
|
||||
})),
|
||||
Adjustment::Exposure {
|
||||
exposure: 0.5,
|
||||
offset: 0.,
|
||||
gamma_correction: 1.2,
|
||||
},
|
||||
Adjustment::Invert,
|
||||
],
|
||||
2,
|
||||
),
|
||||
(
|
||||
vec![
|
||||
Adjustment::HueSaturation(Box::new(HueSaturationSettings {
|
||||
master: sliders(25., 30., 5.),
|
||||
colorize: false,
|
||||
colorize_sliders: zero,
|
||||
reds: range(sliders(-15., 40., 0.), 315., 345., 15., 45.),
|
||||
yellows: range(zero, 15., 45., 75., 105.),
|
||||
greens: range(zero, 75., 105., 135., 165.),
|
||||
cyans: range(zero, 135., 165., 195., 225.),
|
||||
blues: range(zero, 195., 225., 255., 285.),
|
||||
magentas: range(zero, 255., 285., 315., 345.),
|
||||
})),
|
||||
Adjustment::Desaturate { method: DesaturateMethod::LumaRec601 },
|
||||
],
|
||||
5,
|
||||
),
|
||||
(
|
||||
vec![Adjustment::GradientMap {
|
||||
gradient: Item::new_from_element(graphic_types::vector_types::Gradient::from(vec![
|
||||
GraphicColor::from_rgbaf32_unchecked(0.1, 0., 0.4, 1.),
|
||||
GraphicColor::from_rgbaf32_unchecked(1., 0.8, 0.2, 1.),
|
||||
])),
|
||||
reverse: false,
|
||||
}],
|
||||
2,
|
||||
),
|
||||
(vec![Adjustment::Vibrance { vibrance: 60., saturation: 20. }], 2),
|
||||
// Runs of two and three passes, which hand their colors between textures
|
||||
(vec![Adjustment::Vibrance { vibrance: 40., saturation: 0. }, Adjustment::Invert], 3),
|
||||
(vec![Adjustment::Invert, Adjustment::Vibrance { vibrance: -30., saturation: 10. }, Adjustment::Invert], 3),
|
||||
];
|
||||
|
||||
for (run, tolerance) in runs {
|
||||
let mut expected = colors.clone();
|
||||
run.iter().for_each(|adjustment| raster_kernels::adjustments::adjust_colors(adjustment, &mut expected));
|
||||
|
||||
// Carried out on the rendered content by an effects group, and on the image's own texture as it's drawn
|
||||
let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment));
|
||||
let through_effects_group = |scene: &mut VelloSceneBuilder| {
|
||||
let bounds = Rect::new(0., 0., size.x as f64, size.y as f64);
|
||||
scene.draw_effects(&effects, 1., Some(bounds), &mut |_, _| {}, &mut |scene| {
|
||||
scene.draw_raster(raster.clone(), Vec::new(), peniko::ImageSampler::new(), Affine::IDENTITY)
|
||||
});
|
||||
};
|
||||
let on_image_texture = |scene: &mut VelloSceneBuilder| scene.draw_raster(raster.clone(), run.clone(), peniko::ImageSampler::new(), Affine::IDENTITY);
|
||||
let paths = [
|
||||
("through an effects group", &through_effects_group as &dyn Fn(&mut VelloSceneBuilder)),
|
||||
("on the image's texture", &on_image_texture),
|
||||
];
|
||||
|
||||
for (path, draw) in paths {
|
||||
// The first render bakes any cube as a draft, which rendering the same run again refines
|
||||
let Some(_) = render(size, draw) else { return };
|
||||
let Some(gpu) = render(size, draw) else { return };
|
||||
|
||||
let mut worst = 0;
|
||||
for (index, color) in expected.iter().enumerate() {
|
||||
let cpu = color.to_gamma_srgb_channels().map(|channel| (channel * 255.).round() as i32);
|
||||
for channel in 0..3 {
|
||||
worst = worst.max((cpu[channel] - gpu[index][channel] as i32).unsigned_abs());
|
||||
}
|
||||
}
|
||||
let names = run.iter().map(|adjustment| adjustment.kind().to_string()).collect::<Vec<_>>().join(" + ");
|
||||
assert!(worst <= tolerance as u32, "{names} {path} differs from the CPU kernels by up to {worst} levels");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minified_images_average_their_pixels() {
|
||||
use raster_types::{Image, Raster};
|
||||
@@ -288,7 +979,7 @@ fn minified_images_average_their_pixels() {
|
||||
.collect(),
|
||||
};
|
||||
let stripes = Raster::new_cpu(stripes);
|
||||
let draw = |scene: &mut VelloSceneBuilder| scene.draw_raster(stripes.clone(), peniko::ImageSampler::new(), Affine::scale(1. / 8.));
|
||||
let draw = |scene: &mut VelloSceneBuilder| scene.draw_raster(stripes.clone(), Vec::new(), peniko::ImageSampler::new(), Affine::scale(1. / 8.));
|
||||
|
||||
let size = UVec2::new(8, 8);
|
||||
let Some(pixels) = render(size, draw) else { return };
|
||||
@@ -300,18 +991,34 @@ fn minified_images_average_their_pixels() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minified_adjusted_images_sample_their_adjusted_mipmaps() {
|
||||
use graphic_types::Adjustment;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
|
||||
// White inverted to black, drawn at an eighth of its size where only the smaller levels are sampled
|
||||
let white = Raster::new_cpu(Image::new(64, 64, core_types::Color::WHITE));
|
||||
let draw = |scene: &mut VelloSceneBuilder| scene.draw_raster(white.clone(), vec![Adjustment::Invert], peniko::ImageSampler::new(), Affine::scale(1. / 8.));
|
||||
|
||||
let Some(pixels) = render(UVec2::new(8, 8), draw) else { return };
|
||||
for (index, pixel) in pixels.iter().enumerate() {
|
||||
assert!(pixel[0] <= 1 && pixel[3] == 255, "pixel {index} is {pixel:?} rather than black");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasters_upload_once_across_scenes_until_modified() {
|
||||
use raster_types::{Image, Raster};
|
||||
|
||||
let Some(executor) = executor() else { return };
|
||||
let _turn = take_turn();
|
||||
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
|
||||
let raster = Raster::new_cpu(Image::new(8, 8, core_types::Color::WHITE));
|
||||
|
||||
// Each render draws its scene anew, as the editor does whenever the graph runs
|
||||
let scene_drawing = |raster: &Raster<raster_types::CPU>| {
|
||||
let mut scene = VelloSceneBuilder::new(64, 64, Affine::IDENTITY, max_texture_size);
|
||||
scene.draw_raster(raster.clone(), peniko::ImageSampler::new(), Affine::scale(8.));
|
||||
scene.draw_raster(raster.clone(), Vec::new(), peniko::ImageSampler::new(), Affine::scale(8.));
|
||||
scene
|
||||
};
|
||||
|
||||
@@ -338,8 +1045,190 @@ fn textures_of_dropped_rasters_are_freed() {
|
||||
let mut canvas = crate::VelloCanvas::default();
|
||||
for _ in 0..10 {
|
||||
let mut scene = VelloSceneBuilder::new(64, 64, Affine::IDENTITY, max_texture_size);
|
||||
scene.draw_raster(Raster::new_cpu(Image::new(8, 8, core_types::Color::WHITE)), peniko::ImageSampler::new(), Affine::scale(8.));
|
||||
scene.draw_raster(Raster::new_cpu(Image::new(8, 8, core_types::Color::WHITE)), Vec::new(), peniko::ImageSampler::new(), Affine::scale(8.));
|
||||
executor.render_vello_scene_on_canvas(&mut canvas, scene).unwrap();
|
||||
}
|
||||
assert_eq!(canvas.images.textures.len(), 1, "only the texture of pixels that still exist stays");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjusted_images_remake_one_copy_as_their_adjustments_change() {
|
||||
use graphic_types::Adjustment;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
|
||||
let Some(executor) = executor() else { return };
|
||||
let _turn = take_turn();
|
||||
let new_scene = || VelloSceneBuilder::new(64, 64, Affine::IDENTITY, executor.context().device.limits().max_texture_dimension_2d);
|
||||
let raster = Raster::new_cpu(Image::new(8, 8, core_types::Color::WHITE));
|
||||
let exposure = |exposure| Adjustment::Exposure {
|
||||
exposure,
|
||||
offset: 0.,
|
||||
gamma_correction: 1.,
|
||||
};
|
||||
let copies = |canvas: &crate::VelloCanvas| canvas.images.textures.values().map(|image_texture| image_texture.adjusted.len()).sum::<usize>();
|
||||
|
||||
// Dragging a slider adjusts the same pixels differently in every render
|
||||
let mut canvas = crate::VelloCanvas::default();
|
||||
for amount in [0.1, 0.2, 0.3] {
|
||||
let mut scene = new_scene();
|
||||
scene.draw_raster(raster.clone(), vec![exposure(amount)], peniko::ImageSampler::new(), Affine::scale(8.));
|
||||
executor.render_vello_scene_on_canvas(&mut canvas, scene).unwrap();
|
||||
}
|
||||
assert_eq!(copies(&canvas), 1, "each new run takes over the copy the last render drew");
|
||||
|
||||
// Two layers sharing the pixels with different adjustments need a copy each
|
||||
let mut scene = new_scene();
|
||||
scene.draw_raster(raster.clone(), vec![exposure(0.4)], peniko::ImageSampler::new(), Affine::scale(4.));
|
||||
scene.draw_raster(raster.clone(), vec![Adjustment::Invert], peniko::ImageSampler::new(), Affine::scale(8.));
|
||||
executor.render_vello_scene_on_canvas(&mut canvas, scene).unwrap();
|
||||
assert_eq!(copies(&canvas), 2);
|
||||
}
|
||||
|
||||
/// The settings of a noise pattern with features a few units across.
|
||||
fn noise_settings() -> graphic_types::generator::NoiseSettings {
|
||||
use graphic_types::generator::*;
|
||||
|
||||
NoiseSettings {
|
||||
seed: 11,
|
||||
scale: 6.,
|
||||
noise_type: NoiseType::OpenSimplex2,
|
||||
domain_warp_type: DomainWarpType::None,
|
||||
domain_warp_amplitude: 0.,
|
||||
fractal_type: FractalType::FBm,
|
||||
fractal_octaves: 3,
|
||||
fractal_lacunarity: 2.,
|
||||
fractal_gain: 0.5,
|
||||
fractal_weighted_strength: 0.,
|
||||
fractal_ping_pong_strength: 2.,
|
||||
cellular_distance_function: CellularDistanceFunction::Euclidean,
|
||||
cellular_return_type: CellularReturnType::Nearest,
|
||||
cellular_jitter: 1.,
|
||||
}
|
||||
}
|
||||
|
||||
/// A noise pattern with features a few units across.
|
||||
fn noise_pattern() -> graphic_types::generator::GeneratorPattern {
|
||||
graphic_types::generator::GeneratorPattern::Noise(noise_settings())
|
||||
}
|
||||
|
||||
/// Draws `pattern` with `pixels_per_unit` pixels to a unit, from `origin` in its space, comparing 64 by 64 pixels with the generator's own samples.
|
||||
/// Returns how many pixels differ by more than 2 levels and the most any differs by, or `None` without a GPU.
|
||||
fn drawing_differences(pattern: &graphic_types::generator::GeneratorPattern, pixels_per_unit: f64, origin: glam::DVec2) -> Option<(usize, u8)> {
|
||||
let size = UVec2::new(80, 80);
|
||||
let pixels = render(size, |scene| {
|
||||
scene.draw_generator(pattern, Affine::translate((8., 8.)) * Affine::scale(pixels_per_unit) * Affine::translate((-origin.x, -origin.y)))
|
||||
})?;
|
||||
|
||||
// The pattern fills the plane, past the area compared
|
||||
assert_eq!(pixel(&pixels, size, 2, 2)[3], 255);
|
||||
assert_eq!(pixel(&pixels, size, 76, 76)[3], 255);
|
||||
|
||||
let (expected, _, _) = raster_kernels::generators::render_pattern(pattern, [origin, origin + 64. / pixels_per_unit], 64, 64)
|
||||
.unwrap()
|
||||
.to_flat_u8();
|
||||
let differences: Vec<u8> = (0..64 * 64)
|
||||
.map(|index| {
|
||||
let drawn = pixel(&pixels, size, index % 64 + 8, index / 64 + 8);
|
||||
let sampled = &expected[(index * 4) as usize..][..4];
|
||||
(0..3).map(|channel| drawn[channel].abs_diff(sampled[channel])).max().unwrap_or(0)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mismatched = differences.iter().filter(|&&difference| difference > 2).count();
|
||||
Some((mismatched, differences.into_iter().max().unwrap_or(0)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generators_draw_their_pattern_at_the_resolution_in_view() {
|
||||
// Each unit of the pattern drawn across two pixels, so its tiles sample the pattern at every pixel's center
|
||||
let Some((_, worst)) = drawing_differences(&noise_pattern(), 2., glam::DVec2::ZERO) else { return };
|
||||
assert!(worst <= 2, "the drawn pattern differs from the generator's own samples by up to {worst} levels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_noise_setting_renders_on_the_gpu_like_on_the_cpu() {
|
||||
use core_types::choice_type::ChoiceTypeStatic;
|
||||
use graphic_types::generator::*;
|
||||
|
||||
fn every<T: ChoiceTypeStatic + 'static>() -> impl Iterator<Item = T> {
|
||||
T::list().iter().flat_map(|section| section.iter().map(|(variant, _)| *variant))
|
||||
}
|
||||
|
||||
// Each noise type, fractal type, and domain warp, and each pairing of the cellular noise's distance function and return type
|
||||
let base = || NoiseSettings {
|
||||
fractal_type: FractalType::None,
|
||||
..noise_settings()
|
||||
};
|
||||
let warps = [FractalType::None, FractalType::DomainWarpProgressive, FractalType::DomainWarpIndependent];
|
||||
let variations = (every::<NoiseType>().map(|noise_type| NoiseSettings { noise_type, ..base() }))
|
||||
.chain(every::<FractalType>().map(|fractal_type| NoiseSettings {
|
||||
fractal_type,
|
||||
fractal_weighted_strength: 0.5,
|
||||
..base()
|
||||
}))
|
||||
.chain(every::<DomainWarpType>().flat_map(|domain_warp_type| {
|
||||
warps.map(|fractal_type| NoiseSettings {
|
||||
domain_warp_type,
|
||||
domain_warp_amplitude: 4.,
|
||||
fractal_type,
|
||||
..base()
|
||||
})
|
||||
}))
|
||||
.chain(every::<CellularDistanceFunction>().flat_map(|cellular_distance_function| {
|
||||
every::<CellularReturnType>().map(move |cellular_return_type| NoiseSettings {
|
||||
noise_type: NoiseType::Cellular,
|
||||
cellular_distance_function,
|
||||
cellular_return_type,
|
||||
..base()
|
||||
})
|
||||
}));
|
||||
|
||||
// Another GPU's rounding may put a few pixels on the other side of a cell's edge
|
||||
for settings in variations {
|
||||
let Some((mismatched, _)) = drawing_differences(&GeneratorPattern::Noise(settings.clone()), 2., glam::DVec2::ZERO) else {
|
||||
return;
|
||||
};
|
||||
assert!(mismatched <= 8, "{mismatched} pixels differ from the CPU's samples with {settings:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mandelbrot_set_renders_on_the_gpu_like_on_the_cpu() {
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
|
||||
// Its whole unit square across the pixels compared, where the GPU's 32-bit floats may escape a few points on the set's edge at another iteration
|
||||
let Some((mismatched, _)) = drawing_differences(&GeneratorPattern::Mandelbrot, 64., glam::DVec2::ZERO) else {
|
||||
return;
|
||||
};
|
||||
assert!(mismatched <= 40, "{mismatched} pixels differ from the CPU's samples");
|
||||
|
||||
// Pixels a billionth of a unit across, too fine for 32-bit floats, on the edge of the set's second largest bulb
|
||||
let Some((_, worst)) = drawing_differences(&GeneratorPattern::Mandelbrot, 2_f64.powi(30), glam::DVec2::new(0.25, 0.5)) else {
|
||||
return;
|
||||
};
|
||||
assert!(worst <= 2, "deep zooms differ from the CPU's samples by up to {worst} levels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generator_tiles_are_reused_across_a_pan() {
|
||||
let Some(executor) = executor() else { return };
|
||||
let _turn = take_turn();
|
||||
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
|
||||
let tiles = |canvas: &crate::VelloCanvas| canvas.images.textures.len();
|
||||
|
||||
// A pattern drawn two pixels to a unit, in tiles of 256 pixels, panned by part of a tile
|
||||
let mut canvas = crate::VelloCanvas::default();
|
||||
let draw = |offset: f64| {
|
||||
let mut scene = VelloSceneBuilder::new(512, 512, Affine::IDENTITY, max_texture_size);
|
||||
scene.draw_generator(&noise_pattern(), Affine::translate((offset, 0.)) * Affine::scale(2.));
|
||||
scene
|
||||
};
|
||||
executor.render_vello_scene_on_canvas(&mut canvas, draw(0.)).unwrap();
|
||||
let first = tiles(&canvas);
|
||||
executor.render_vello_scene_on_canvas(&mut canvas, draw(0.)).unwrap();
|
||||
assert_eq!(tiles(&canvas), first, "drawing the same view again renders no tiles");
|
||||
|
||||
executor.render_vello_scene_on_canvas(&mut canvas, draw(-100.)).unwrap();
|
||||
let panned = tiles(&canvas) - first;
|
||||
assert!(panned < first, "panning renders only the tiles newly in view, not all {first} again (rendered {panned})");
|
||||
}
|
||||
@@ -22,6 +22,7 @@ default = ["serde"]
|
||||
core-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::Item;
|
||||
use core_types::{Color, Ctx};
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{BevelDirection, BevelStyle, Effect, EffectOperation, Generator, GlowSource, Graphic, Vector, stamp_effect};
|
||||
use raster_kernels::evaluate_color_effects;
|
||||
use vector_types::Gradient;
|
||||
use vector_types::vector::style::StrokeAlign;
|
||||
|
||||
/// Blurs the input graphics, whether vector shapes, images, or text.
|
||||
#[node_macro::node(category("Raster: Filter"), icon("NodeBlur"), version(2))]
|
||||
fn blur<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to blur.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// How far the blur spreads each point of the content.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
radius: Item<f64>,
|
||||
/// Use a box kernel instead of a circular Gaussian kernel, which averages evenly and leaves boxy artifacts.
|
||||
box_blur: Item<bool>,
|
||||
/// Opt to incorrectly blend the colors in gamma space for compatibility with the results from other software.
|
||||
gamma: Item<bool>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::Blur {
|
||||
radius: *radius.element(),
|
||||
box_blur: *box_blur.element(),
|
||||
gamma: *gamma.element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
|
||||
/// Casts a soft shadow of the input graphics' silhouette beneath them.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeBlur"))]
|
||||
fn drop_shadow<T>(
|
||||
_: impl Ctx,
|
||||
/// The content casting the shadow.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The shadow's color, with its opacity.
|
||||
#[default("#00000080")]
|
||||
color: Item<Color>,
|
||||
/// How far the shadow sits from the content.
|
||||
#[unit(" px")]
|
||||
#[default(4., 4.)]
|
||||
offset: Item<DVec2>,
|
||||
/// How soft the shadow's edges are.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
#[default(4.)]
|
||||
blur: Item<f64>,
|
||||
/// How far the shadow grows past the content's silhouette before it softens.
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
spread: Item<f64>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::DropShadow {
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
offset: *offset.element(),
|
||||
blur: *blur.element(),
|
||||
spread: *spread.element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
|
||||
/// Casts a soft shadow inward from the edges of the input graphics, as if they were cut out of the surface.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeBlur"))]
|
||||
fn inner_shadow<T>(
|
||||
_: impl Ctx,
|
||||
/// The content the shadow falls inside.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The shadow's color, with its opacity.
|
||||
#[default("#00000080")]
|
||||
color: Item<Color>,
|
||||
/// How far the shadow sits from the edges it falls from.
|
||||
#[unit(" px")]
|
||||
#[default(4., 4.)]
|
||||
offset: Item<DVec2>,
|
||||
/// How soft the shadow's edges are.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
#[default(4.)]
|
||||
blur: Item<f64>,
|
||||
/// How far the shadow reaches in from the content's edges before it softens.
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
spread: Item<f64>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::InnerShadow {
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
offset: *offset.element(),
|
||||
blur: *blur.element(),
|
||||
spread: *spread.element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
|
||||
/// Surrounds the input graphics with a soft glow of their silhouette.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeBlur"))]
|
||||
fn outer_glow<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to glow around.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The glow's color, with its opacity.
|
||||
#[default("#ffffbebf")]
|
||||
color: Item<Color>,
|
||||
/// How soft the glow's edges are.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
#[default(8.)]
|
||||
blur: Item<f64>,
|
||||
/// How far the glow grows past the content's silhouette before it softens.
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
spread: Item<f64>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::OuterGlow {
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
blur: *blur.element(),
|
||||
spread: *spread.element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
|
||||
/// Glows inward from the edges of the input graphics, or outward from their center.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeBlur"))]
|
||||
fn inner_glow<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to glow within.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The glow's color, with its opacity.
|
||||
#[default("#ffffbebf")]
|
||||
color: Item<Color>,
|
||||
/// How soft the glow's edges are.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
#[default(8.)]
|
||||
blur: Item<f64>,
|
||||
/// How far the glow grows into the content before it softens.
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
choke: Item<f64>,
|
||||
/// Whether the glow starts from the edges or the center.
|
||||
source: Item<GlowSource>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::InnerGlow {
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
blur: *blur.element(),
|
||||
choke: *choke.element(),
|
||||
source: *source.element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
|
||||
/// Shades the inside of the input graphics with soft, glossy bands that follow their shape.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeBlur"))]
|
||||
fn satin<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to shade.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The shading's color, with its opacity.
|
||||
#[default("#00000080")]
|
||||
color: Item<Color>,
|
||||
/// How far apart the bands are drawn, and in which direction.
|
||||
#[unit(" px")]
|
||||
#[default(10., 4.)]
|
||||
offset: Item<DVec2>,
|
||||
/// How soft the bands are.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
#[default(14.)]
|
||||
blur: Item<f64>,
|
||||
/// Shade where the bands overlap rather than where they don't.
|
||||
#[default(true)]
|
||||
invert: Item<bool>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::Satin {
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
offset: *offset.element(),
|
||||
blur: *blur.element(),
|
||||
invert: *invert.element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
|
||||
/// Draws a band of color along the edge of the input graphics, outside, inside, or centered on it.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeBlur"))]
|
||||
fn outline<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to outline.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The outline's color, with its opacity.
|
||||
#[default(Color::BLACK)]
|
||||
color: Item<Color>,
|
||||
/// How thick the outline is.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
#[default(3.)]
|
||||
weight: Item<f64>,
|
||||
/// Whether the outline is drawn outside the edge, inside it, or centered on it.
|
||||
#[default(StrokeAlign::Outside)]
|
||||
align: Item<StrokeAlign>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::Outline {
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
weight: *weight.element(),
|
||||
align: *align.element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
|
||||
/// Raises the input graphics into a lit relief, with highlights on the slopes facing the light and shadows on those facing away.
|
||||
#[node_macro::node(name("Bevel & Emboss"), category("Raster: Effect"), icon("NodeBlur"))]
|
||||
fn bevel_and_emboss<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to raise.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// Where the slope lies: inside the edge, outside it, across it, or across it with the edge pressed in.
|
||||
style: Item<BevelStyle>,
|
||||
/// How steep the slope is.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..1000)]
|
||||
#[default(100.)]
|
||||
depth: Item<f64>,
|
||||
/// Whether the slope rises out of the surface or sinks into it.
|
||||
direction: Item<BevelDirection>,
|
||||
/// How wide the slope is.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..250)]
|
||||
#[default(5.)]
|
||||
size: Item<f64>,
|
||||
/// How much the shading is blurred.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..16)]
|
||||
soften: Item<f64>,
|
||||
/// The direction the light comes from.
|
||||
#[unit("°")]
|
||||
#[range]
|
||||
#[soft(-180..180)]
|
||||
#[default(120.)]
|
||||
angle: Item<f64>,
|
||||
/// How high above the surface the light is, from the horizon to straight overhead.
|
||||
#[unit("°")]
|
||||
#[range]
|
||||
#[hard(0..90)]
|
||||
#[default(30.)]
|
||||
altitude: Item<f64>,
|
||||
/// The highlight's color, with its opacity.
|
||||
#[default("#ffffffbf")]
|
||||
highlight_color: Item<Color>,
|
||||
/// The shadow's color, with its opacity.
|
||||
#[default("#000000bf")]
|
||||
shadow_color: Item<Color>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::BevelAndEmboss {
|
||||
style: *style.element(),
|
||||
depth: *depth.element(),
|
||||
direction: *direction.element(),
|
||||
size: *size.element(),
|
||||
soften: *soften.element(),
|
||||
angle: *angle.element(),
|
||||
altitude: *altitude.element(),
|
||||
highlight_color: evaluate_color_effects(highlight_color).into_element(),
|
||||
shadow_color: evaluate_color_effects(shadow_color).into_element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
|
||||
/// Paints over the input graphics within their shape, mixing the paint with their colors by a blend mode.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"), version(2))]
|
||||
fn paint_overlay<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to paint over.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The color, gradient, image, or other graphic to paint with. A gradient or image without its own placement stretches across the content.
|
||||
#[default(Color::BLACK)]
|
||||
paint: Item<Graphic>,
|
||||
/// How the paint mixes with the content's colors.
|
||||
blend_mode: Item<BlendMode>,
|
||||
/// How strongly the paint shows.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
opacity: Item<f64>,
|
||||
) -> Item<T> {
|
||||
// The paint is the element alone, since the wire envelope's attributes would nest it as a group
|
||||
let paint = match paint.into_element() {
|
||||
Graphic::None(_) | Graphic::NoneList(_) => return content,
|
||||
Graphic::Color(color) => Graphic::from(evaluate_color_effects(color).into_element()),
|
||||
paint => paint,
|
||||
};
|
||||
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
&mut content,
|
||||
Effect::new(&EffectOperation::PaintOverlay {
|
||||
paint,
|
||||
blend_mode: blend_mode.into_element(),
|
||||
opacity: opacity.into_element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::Item;
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
|
||||
#[test]
|
||||
fn paint_overlay_multiplies_a_color_into_the_content() {
|
||||
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
|
||||
let image = Image::new(1, 1, image_color);
|
||||
|
||||
let result = super::paint_overlay(
|
||||
(),
|
||||
Item::new_from_element(Raster::new_cpu(image)),
|
||||
Item::new_from_element(Graphic::from(Color::GREEN)),
|
||||
BlendMode::Multiply.into(),
|
||||
100_f64.into(),
|
||||
);
|
||||
let result = raster_kernels::evaluate_raster_effects(result).into_element();
|
||||
|
||||
// Multiplying by green keeps only the green channel, and the content keeps its own alpha
|
||||
assert_eq!(result.data[0], Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
pub mod effects;
|
||||
|
||||
use core_types::list::Item;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, BlendMode, Color, Ctx};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::Vector;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Generator, Graphic};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies the blend mode to the input graphics. Setting this allows for customizing how overlapping content is composited together.
|
||||
@@ -10,7 +12,7 @@ use vector_types::Gradient;
|
||||
fn blend_mode<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
|
||||
blend_mode: Item<BlendMode>,
|
||||
@@ -29,7 +31,7 @@ fn blend_mode<T>(
|
||||
fn opacity<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// Whether the *Opacity* property is enabled, multiplying the existing opacity by the chosen percentage.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
@@ -76,7 +78,7 @@ fn opacity<T>(
|
||||
fn clipping_mask<T>(
|
||||
_: impl Ctx,
|
||||
/// The content that will be composited when rendering.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// Whether the content inherits the alpha of the content beneath it.
|
||||
clip: Item<bool>,
|
||||
|
||||
@@ -3,6 +3,7 @@ use core_types::transform::Footprint;
|
||||
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -89,6 +90,7 @@ fn step_real_time<T>(
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> List<String>,
|
||||
Context -> List<f64>,
|
||||
@@ -99,6 +101,7 @@ fn step_real_time<T>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
value: impl Node<Context<'static>, Output = T>,
|
||||
@@ -135,6 +138,7 @@ fn step_animation_time<T>(
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> List<String>,
|
||||
Context -> List<f64>,
|
||||
@@ -145,6 +149,7 @@ fn step_animation_time<T>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
value: impl Node<Context<'static>, Output = T>,
|
||||
|
||||
@@ -5,6 +5,7 @@ use core_types::transform::Footprint;
|
||||
use core_types::{Color, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::vector_types::Gradient;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -30,6 +31,7 @@ fn context_modification<T>(
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<NodeIdPath>,
|
||||
Context -> Item<AttributeValueDyn>,
|
||||
Context -> Item<AnimationCurve>,
|
||||
@@ -43,6 +45,7 @@ fn context_modification<T>(
|
||||
Context -> List<Color>,
|
||||
Context -> List<Artboard>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<AnimationCurve>,
|
||||
Context -> ListDyn,
|
||||
)]
|
||||
|
||||
@@ -18,6 +18,7 @@ workspace = true
|
||||
core-types = { workspace = true }
|
||||
brush-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
raster-types = { workspace = true }
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ use core_types::list::{Item, List};
|
||||
use core_types::transform::TransformMut;
|
||||
use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -20,6 +21,7 @@ fn create_artboard<T: IntoGraphicList>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> Item<DAffine2>, // TODO: Remove this
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = T>,
|
||||
@@ -51,7 +53,7 @@ fn create_artboard<T: IntoGraphicList>(
|
||||
let normalized_location = location.min(location + dimensions);
|
||||
let normalized_dimensions = dimensions.abs().max(DVec2::ONE);
|
||||
|
||||
let background = background.into_element();
|
||||
let background = raster_kernels::evaluate_color_effects(background).into_element();
|
||||
|
||||
// Name is not stored here, it's resolved live from the parent layer's display name
|
||||
Ok(Item::new_from_element(Artboard::new(content))
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
use brush_types::Stroke;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
|
||||
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl};
|
||||
use core_types::{
|
||||
ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EFFECTS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl,
|
||||
};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
use graphic_types::{Artboard, Effects, Generator, Vector};
|
||||
use rand::SeedableRng;
|
||||
use rand::seq::SliceRandom;
|
||||
use raster_kernels::value_effects;
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use std::cmp::Ordering;
|
||||
use vector_types::gradient::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread};
|
||||
@@ -31,6 +34,7 @@ fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: T,
|
||||
@@ -64,6 +68,7 @@ fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
|
||||
List<Raster<CPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -102,6 +107,7 @@ fn filter<T: Send + Sync + Clone + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -135,6 +141,7 @@ fn reverse<T: Send + Sync + Clone + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -160,6 +167,7 @@ fn shift<T: Send + Sync + Clone + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -205,6 +213,7 @@ fn shuffle<T: Send + Sync + Clone + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -277,6 +286,7 @@ fn slice<T: Send + Sync + Clone + 'static>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
list: List<T>,
|
||||
@@ -412,6 +422,7 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
)]
|
||||
content: List<Item>,
|
||||
@@ -428,6 +439,7 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
mapped: impl Node<Context<'static>, Output = List<Item>>,
|
||||
@@ -634,6 +646,7 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
List<BlendMode>,
|
||||
List<GradientForm>,
|
||||
@@ -937,6 +950,7 @@ fn extend<T: Send + Clone>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
List<Stroke>,
|
||||
)]
|
||||
@@ -956,6 +970,7 @@ fn extend<T: Send + Clone>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<Artboard>,
|
||||
List<Stroke>,
|
||||
)]
|
||||
@@ -973,9 +988,9 @@ fn extend<T: Send + Clone>(
|
||||
#[node_macro::node(category(""))]
|
||||
fn legacy_layer_extend<T: Send + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)] base: List<T>,
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Generator>)] base: List<T>,
|
||||
#[expose]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Generator>)]
|
||||
new: List<T>,
|
||||
nested_node_path: Item<NodeIdPath>,
|
||||
) -> List<T> {
|
||||
@@ -1007,6 +1022,7 @@ fn into_group<T: Into<Graphic>>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<DVec2>,
|
||||
Item<DAffine2>, // TODO: Remove this
|
||||
@@ -1151,7 +1167,14 @@ fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Item<Gradient> {
|
||||
/// Unwraps a gradient into a `Color[]` of its stops, keeping any `position` and `midpoint` attributes that place them along the ramp. Attributes belonging to the gradient as a whole (like spread and interpolation), rather than its individual color stops, are not preserved.
|
||||
#[node_macro::node(category("Gradient"), icon("NodeGradientToColors"), name("Gradient to Colors"))]
|
||||
fn gradient_to_colors(_: impl Ctx, gradient: Item<Gradient>) -> List<Color> {
|
||||
gradient.into_element().into_color_list()
|
||||
// The adjustments the gradient carries change each stop's color
|
||||
let adjustments = gradient.attribute::<Effects>(ATTR_EFFECTS).map(value_effects::adjustments).unwrap_or_default();
|
||||
|
||||
let mut colors = gradient.into_element().into_color_list();
|
||||
for color in colors.iter_element_values_mut() {
|
||||
*color = value_effects::adjusted_color(*color, &adjustments);
|
||||
}
|
||||
colors
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -45,6 +45,7 @@ wgpu-executor = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
blending-nodes = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
transform-nodes = { workspace = true }
|
||||
|
||||
@@ -13,7 +13,7 @@ pub use graphene_application_io as application_io;
|
||||
pub use graphene_core;
|
||||
pub use graphene_core::debug;
|
||||
pub use graphic_nodes;
|
||||
pub use graphic_types::{Appearance, Artboard, Cover, CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||
pub use graphic_types::{Appearance, Artboard, BevelDirection, BevelStyle, Cover, CoverPlacement, Coverage, Effect, EffectKind, EffectOperation, Effects, GlowSource, Graphic, Vector, stamp_coverage};
|
||||
pub use math_nodes;
|
||||
pub use path_bool_nodes;
|
||||
pub use raster_nodes;
|
||||
@@ -61,6 +61,10 @@ pub mod gradient {
|
||||
pub use vector_types::{Gradient, GradientStop};
|
||||
}
|
||||
|
||||
pub mod generator {
|
||||
pub use graphic_types::generator::*;
|
||||
}
|
||||
|
||||
pub mod transform {
|
||||
pub use core_types::transform::*;
|
||||
pub use vector_types::ReferencePoint;
|
||||
|
||||
@@ -173,7 +173,7 @@ fn string_to_bytes(_: impl Ctx, string: Item<String>) -> Item<Resource> {
|
||||
/// Converts extracted raw RGBA pixel data from an input image. Each pixel becomes 4 sequential bytes. Useful for transmission over HTTP or writing to files.
|
||||
#[node_macro::node(category("Data: I/O"), icon("NodeImageToBytes"), name("Image to Bytes"))]
|
||||
fn image_to_bytes(_: impl Ctx, image: Item<Raster<CPU>>) -> Item<Resource> {
|
||||
let bytes: Vec<u8> = image
|
||||
let bytes: Vec<u8> = raster_kernels::evaluate_raster_effects(image)
|
||||
.element()
|
||||
.data
|
||||
.iter()
|
||||
|
||||
@@ -4,6 +4,7 @@ use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs};
|
||||
use core_types::{Color, Context, Ctx, ExtractFootprint, Interrupt, NodeError, OwnedContextImpl, WasmNotSend};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphene_application_io::{ExportFormat, RenderConfig};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
@@ -34,6 +35,7 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
data: impl Node<Context<'static>, Output = T>,
|
||||
|
||||
@@ -19,6 +19,7 @@ core-types = { workspace = true }
|
||||
graphene-core = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
|
||||
@@ -5,7 +5,7 @@ use core_types::{Color, Ctx, OwnedContextImpl, num_traits};
|
||||
use core_types::{Context, Interrupt};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use graphic_types::{Artboard, Generator, Graphic, Vector};
|
||||
use math_parser::ast;
|
||||
use math_parser::context::{EvalContext, NothingMap, ValueProvider};
|
||||
use math_parser::executer::EvalError;
|
||||
@@ -1717,6 +1717,7 @@ fn switch<T: Send>(
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Bundle<String>>,
|
||||
Context -> Item<Bundle<bool>>,
|
||||
@@ -1747,6 +1748,7 @@ fn switch<T: Send>(
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
Context -> Item<Artboard>,
|
||||
Context -> Item<Bundle<String>>,
|
||||
Context -> Item<Bundle<bool>>,
|
||||
@@ -1918,11 +1920,25 @@ fn gradient_value(_: impl Ctx, _primary: (), #[default(Color::BLACK, Color::WHIT
|
||||
gradient
|
||||
}
|
||||
|
||||
/// Sets the form (linear or radial) of each gradient in the input list.
|
||||
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"))]
|
||||
fn gradient_form(_: impl Ctx, gradient: Item<Gradient>, gradient_form: Item<vector_types::GradientForm>) -> Item<Gradient> {
|
||||
/// Curves the contours at the start and end of each gradient in the input list between straight lines, circles, and points, with the contours between following along.
|
||||
///
|
||||
/// Each end runs from -1 to 1. At 0 its contour is a straight line, at 1 or -1 it shrinks to the end's own point, and between it is a circle through the end that bows toward the other end when positive or away from it when negative. A linear gradient is 0 at both ends, and a radial gradient is 1 at its start and 0.5 at its end.
|
||||
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"), inspector("gradient_curvature_inspector"), version(2))]
|
||||
fn gradient_curvature(
|
||||
_: impl Ctx,
|
||||
gradient: Item<Gradient>,
|
||||
/// The curve of the contour through the start.
|
||||
#[range]
|
||||
#[soft(-1..1)]
|
||||
start_curvature: Item<f64>,
|
||||
/// The curve of the contour through the end.
|
||||
#[range]
|
||||
#[soft(-1..1)]
|
||||
end_curvature: Item<f64>,
|
||||
) -> Item<Gradient> {
|
||||
let mut gradient = gradient;
|
||||
gradient.set_attribute(core_types::ATTR_GRADIENT_FORM, *gradient_form.element());
|
||||
gradient.set_attribute(core_types::ATTR_GRADIENT_START_CURVATURE, *start_curvature.element());
|
||||
gradient.set_attribute(core_types::ATTR_GRADIENT_END_CURVATURE, *end_curvature.element());
|
||||
gradient
|
||||
}
|
||||
|
||||
@@ -2050,6 +2066,7 @@ fn evaluate_gradient(
|
||||
#[soft(0..1)]
|
||||
position: Item<f64>,
|
||||
) -> Item<Color> {
|
||||
let gradient = raster_kernels::evaluate_gradient_effects(gradient);
|
||||
let settings = vector_types::GradientSettings::from(&gradient);
|
||||
let color = gradient.element().evaluate(*position.element(), settings);
|
||||
Item::new_from_element(color)
|
||||
|
||||
@@ -281,9 +281,9 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> Result<List<Vector>, BooleanO
|
||||
boolean_operation_on_vector_list(&flattened, BooleanOperation::Union)?.into_iter().collect::<Vec<_>>()
|
||||
}
|
||||
}
|
||||
// Rasters, colors, and gradients bound no region, so they contribute no operand
|
||||
Graphic::None(_) | Graphic::NoneList(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) => Vec::new(),
|
||||
Graphic::RasterCPUList(_) | Graphic::RasterGPUList(_) | Graphic::ColorList(_) | Graphic::GradientList(_) => Vec::new(),
|
||||
// Rasters, colors, gradients, and generators bound no region, so they contribute no operand
|
||||
Graphic::None(_) | Graphic::NoneList(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) => Vec::new(),
|
||||
Graphic::RasterCPUList(_) | Graphic::RasterGPUList(_) | Graphic::ColorList(_) | Graphic::GradientList(_) | Graphic::GeneratorList(_) => Vec::new(),
|
||||
// Strokes have no vector outline representation; a brush node renders them to rasters
|
||||
Graphic::StrokeList(_) => Vec::new(),
|
||||
// Normalized to GraphicList above
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
use core_types::color::Color;
|
||||
use graphic_types::Adjustment;
|
||||
use raster_kernels::adjustments::{PreparedAdjustment, adjust_color, adjust_colors};
|
||||
use raster_types::{CPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
|
||||
pub trait Adjust {
|
||||
fn adjust(&mut self, adjustment: &Adjustment);
|
||||
}
|
||||
|
||||
impl Adjust for Color {
|
||||
fn adjust(&mut self, adjustment: &Adjustment) {
|
||||
*self = adjust_color(adjustment, *self);
|
||||
}
|
||||
}
|
||||
|
||||
impl Adjust for Raster<CPU> {
|
||||
fn adjust(&mut self, adjustment: &Adjustment) {
|
||||
adjust_colors(adjustment, &mut self.data_mut().data);
|
||||
}
|
||||
}
|
||||
|
||||
impl Adjust for Gradient {
|
||||
fn adjust(&mut self, adjustment: &Adjustment) {
|
||||
let adjustment = PreparedAdjustment::new(adjustment);
|
||||
*self = self.map_colors(|color| adjustment.adjust(*color));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use crate::adjust::Adjust;
|
||||
use crate::color_lookup_table::{LutParseError, parse_cached};
|
||||
use core_types::color::Color;
|
||||
use core_types::context::Ctx;
|
||||
@@ -14,25 +13,27 @@ use graphic_types::adjustment::{
|
||||
};
|
||||
pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute};
|
||||
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use raster_types::{CPU, Image, Raster};
|
||||
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||
use raster_kernels::{evaluate_color_effects, evaluate_gradient_effects};
|
||||
use raster_types::{CPU, GPU, Image, Raster};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies the adjustment to the item's element.
|
||||
fn adjust<T: Adjust>(item: Item<T>, adjustment: Adjustment) -> Item<T> {
|
||||
/// Stamps the adjustment onto the item's effects, to be carried out wherever its content is rendered or read.
|
||||
pub(crate) fn adjust<T>(item: Item<T>, adjustment: Adjustment) -> Item<T> {
|
||||
let mut item = item;
|
||||
item.element_mut().adjust(&adjustment);
|
||||
stamp_effect(&mut item, Effect::new(&EffectOperation::Adjustment(adjustment)));
|
||||
item
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeDesaturate"))]
|
||||
fn desaturate<T: Adjust>(_: impl Ctx, #[implementations(Raster<CPU>, Color, Gradient)] input: Item<T>, method: Item<DesaturateMethod>) -> Item<T> {
|
||||
fn desaturate<T>(_: impl Ctx, #[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>, method: Item<DesaturateMethod>) -> Item<T> {
|
||||
adjust(input, Adjustment::Desaturate { method: method.into_element() })
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeGammaCorrection"))]
|
||||
fn gamma_correction<T: Adjust>(
|
||||
fn gamma_correction<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[default(2.2)]
|
||||
#[range]
|
||||
#[hard(0.0001..)]
|
||||
@@ -65,7 +66,7 @@ pub struct ImageChannels {
|
||||
/// Separates an image into its red, green, blue, and alpha channels, each provided as a grayscale image.
|
||||
#[node_macro::node(category("Raster"), icon("NodeImageToChannels"), name("Image to Channels"))]
|
||||
fn image_to_channels(_: impl Ctx, image: Item<Raster<CPU>>) -> ImageChannels {
|
||||
let (image, attributes) = image.into_parts();
|
||||
let (image, attributes) = raster_kernels::evaluate_raster_effects(image).into_parts();
|
||||
let (width, height) = (image.width, image.height);
|
||||
|
||||
// O(4 × pixels), since all four channels are written even when only some outputs are connected
|
||||
@@ -86,7 +87,7 @@ fn image_to_channels(_: impl Ctx, image: Item<Raster<CPU>>) -> ImageChannels {
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"))]
|
||||
fn make_opaque<T: Adjust>(_: impl Ctx, #[implementations(Raster<CPU>, Color, Gradient)] input: Item<T>) -> Item<T> {
|
||||
fn make_opaque<T>(_: impl Ctx, #[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>) -> Item<T> {
|
||||
adjust(input, Adjustment::MakeOpaque)
|
||||
}
|
||||
|
||||
@@ -99,9 +100,9 @@ fn make_opaque<T: Adjust>(_: impl Ctx, #[implementations(Raster<CPU>, Color, Gra
|
||||
//
|
||||
// TODO: A Lab-only mode once Graphite supports the CIE Lab color space.
|
||||
#[node_macro::node(name("Brightness/Contrast"), category("Raster: Adjustment"), icon("NodeBrightnessContrast"), inspector("brightness_contrast_inspector"))]
|
||||
fn brightness_contrast<T: Adjust>(
|
||||
fn brightness_contrast<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(-150..150)]
|
||||
@@ -148,9 +149,9 @@ pub enum AdjustmentChannel {
|
||||
// Some further analysis available at:
|
||||
// https://geraldbakker.nl/psnumbers/levels.html
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeLevels"), inspector("levels_inspector"))]
|
||||
fn levels<T: Adjust>(
|
||||
fn levels<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
@@ -319,9 +320,9 @@ fn levels<T: Adjust>(
|
||||
// points, and the per-channel curves apply before the composite one, like Levels. The value between those two stages
|
||||
// stays exact rather than rounding through an 8-bit table, which can leave results a level away from 8-bit pipelines.
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeCurves"), inspector("transfer_curves_inspector"))]
|
||||
fn curves<T: Adjust + Send>(
|
||||
fn curves<T: Send>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
curve: Item<TransferCurve>,
|
||||
#[name("(Red) Curve")] red_curve: Item<TransferCurve>,
|
||||
#[name("(Green) Curve")] green_curve: Item<TransferCurve>,
|
||||
@@ -366,9 +367,9 @@ fn points_to_transfer_curve(
|
||||
// https://stackoverflow.com/a/55233732/775283
|
||||
// Works the same for gamma and linear color
|
||||
#[node_macro::node(name("Black & White"), category("Raster: Adjustment"), icon("NodeBlackAndWhite"), inspector("black_and_white_inspector"))]
|
||||
fn black_and_white<T: Adjust>(
|
||||
fn black_and_white<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
use_tint: Item<bool>,
|
||||
#[default("#e1d3b3")] tint: Item<Color>,
|
||||
#[unit("%")]
|
||||
@@ -404,7 +405,7 @@ fn black_and_white<T: Adjust>(
|
||||
) -> Item<T> {
|
||||
let settings = BlackAndWhiteSettings {
|
||||
use_tint: use_tint.into_element(),
|
||||
tint: tint.into_element(),
|
||||
tint: evaluate_color_effects(tint).into_element(),
|
||||
reds: reds.into_element(),
|
||||
yellows: yellows.into_element(),
|
||||
greens: greens.into_element(),
|
||||
@@ -437,9 +438,9 @@ pub enum HueSaturationRange {
|
||||
//
|
||||
// TODO: Residuals in 8-bit PSD interop: the byte-hue colorize table, the colorize lightness slider (up to 2.5 levels), and the range edges (a few tenths of a degree)
|
||||
#[node_macro::node(name("Hue/Saturation"), category("Raster: Adjustment"), icon("NodeHueSaturation"), inspector("hue_saturation_inspector"))]
|
||||
fn hue_saturation<T: Adjust>(
|
||||
fn hue_saturation<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[unit("°")]
|
||||
#[range]
|
||||
#[soft(-180..180)]
|
||||
@@ -773,16 +774,16 @@ fn hue_saturation<T: Adjust>(
|
||||
// Aims for interoperable compatibility with:
|
||||
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27%20%3D%20Color%20Lookup-,%27nvrt%27%20%3D%20Invert,-%27post%27%20%3D%20Posterize
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeInvert"))]
|
||||
fn invert<T: Adjust>(_: impl Ctx, #[implementations(Raster<CPU>, Color, Gradient)] input: Item<T>) -> Item<T> {
|
||||
fn invert<T>(_: impl Ctx, #[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>) -> Item<T> {
|
||||
adjust(input, Adjustment::Invert)
|
||||
}
|
||||
|
||||
// Aims for interoperable compatibility with:
|
||||
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=post%27%20%3D%20Posterize-,%27thrs%27%20%3D%20Threshold,-%27grdm%27%20%3D%20Gradient
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeThreshold"), inspector("threshold_inspector"))]
|
||||
fn threshold<T: Adjust>(
|
||||
fn threshold<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
@@ -817,16 +818,16 @@ fn threshold<T: Adjust>(
|
||||
// TODO: `(c[i + 1] - c[i - 1]) / 2`, the end stops repeated past the ends, so two stops give `0.5 p + 1.5 p^2 - p^3`.
|
||||
// TODO: - The ramp is `(1 - s) * linear + s * smooth` for smoothness s, clamped per interval to its two stop colors.
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeGradientMap"))]
|
||||
fn gradient_map<T: Adjust + Send>(
|
||||
fn gradient_map<T: Send>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[default(Color::BLACK, Color::WHITE)] gradient: Item<Gradient>,
|
||||
reverse: Item<bool>,
|
||||
) -> Item<T> {
|
||||
adjust(
|
||||
image,
|
||||
Adjustment::GradientMap {
|
||||
gradient,
|
||||
gradient: evaluate_gradient_effects(gradient),
|
||||
reverse: reverse.into_element(),
|
||||
},
|
||||
)
|
||||
@@ -836,9 +837,9 @@ fn gradient_map<T: Adjust + Send>(
|
||||
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27-,vibA%27%20%3D%20Vibrance,-%27hue%20%27%20%3D%20Old
|
||||
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Vibrance%20(Photoshop%20CS3)
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeVibrance"), inspector("vibrance_inspector"))]
|
||||
fn vibrance<T: Adjust>(
|
||||
fn vibrance<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(-100..100)]
|
||||
@@ -885,9 +886,9 @@ pub enum RedGreenBlueAlpha {
|
||||
//
|
||||
// TODO: CMYK source channels once Graphite supports the CMYK color space.
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeChannelMixer"), inspector("channel_mixer_inspector"))]
|
||||
fn channel_mixer<T: Adjust>(
|
||||
fn channel_mixer<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
|
||||
monochrome: Item<bool>,
|
||||
|
||||
@@ -1036,9 +1037,9 @@ pub enum SelectiveColorChoice {
|
||||
// Algorithm based on:
|
||||
// https://blog.pkh.me/p/22-understanding-selective-coloring-in-adobe-photoshop.html
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeSelectiveColor"), inspector("selective_color_inspector"))]
|
||||
fn selective_color<T: Adjust>(
|
||||
fn selective_color<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
|
||||
mode: Item<RelativeAbsolute>,
|
||||
|
||||
@@ -1258,9 +1259,9 @@ fn selective_color<T: Adjust>(
|
||||
// Aims for interoperable compatibility with:
|
||||
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=nvrt%27%20%3D%20Invert-,%27post%27%20%3D%20Posterize,-%27thrs%27%20%3D%20Threshold
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodePosterize"))]
|
||||
fn posterize<T: Adjust>(
|
||||
fn posterize<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[default(4)]
|
||||
#[hard(2..)]
|
||||
levels: Item<i64>,
|
||||
@@ -1275,9 +1276,9 @@ fn posterize<T: Adjust>(
|
||||
// The exposure, offset, and gamma operations follow:
|
||||
// https://geraldbakker.nl/psnumbers/exposure.html
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeExposure"), inspector("exposure_inspector"))]
|
||||
fn exposure<T: Adjust>(
|
||||
fn exposure<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] input: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
|
||||
#[range]
|
||||
#[soft(-20..20)]
|
||||
exposure: Item<f64>,
|
||||
@@ -1317,9 +1318,9 @@ pub enum TonalRange {
|
||||
// Every channel is a Levels curve whose black point, white point, and two-decimal gamma are derived from
|
||||
// the nine sliders, see `color_balance_curve` in the adjustment kernels.
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeColorBalance"), inspector("color_balance_inspector"))]
|
||||
fn color_balance<T: Adjust>(
|
||||
fn color_balance<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
|
||||
#[name("(Shadows) Cyan-Red")]
|
||||
#[unit("%")]
|
||||
@@ -1393,9 +1394,9 @@ fn color_balance<T: Adjust>(
|
||||
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27phfl%27%20%3D%20Photo%20Filter
|
||||
// https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=of%20the%20file.-,Photo%20Filter,-Key%20is%20%27phfl
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodePhotoFilter"))]
|
||||
fn photo_filter<T: Adjust>(
|
||||
fn photo_filter<T>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Raster<CPU>, Color, Gradient)] image: Item<T>,
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] image: Item<T>,
|
||||
#[default("#ec8a00")] color: Item<Color>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
@@ -1407,7 +1408,7 @@ fn photo_filter<T: Adjust>(
|
||||
adjust(
|
||||
image,
|
||||
Adjustment::PhotoFilter {
|
||||
color: color.into_element(),
|
||||
color: evaluate_color_effects(color).into_element(),
|
||||
density: density.into_element(),
|
||||
preserve_luminosity: preserve_luminosity.into_element(),
|
||||
},
|
||||
@@ -1421,10 +1422,10 @@ fn photo_filter<T: Adjust>(
|
||||
// TODO: Support dither, which needs the pixel position that a per-color adjustment never sees.
|
||||
// TODO: Verify the tetrahedral interpolation, which is unconfirmed against other implementations.
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeColorLookup"))]
|
||||
fn color_lookup<T: Adjust + Send>(
|
||||
fn color_lookup<T: Send>(
|
||||
_: impl Ctx,
|
||||
/// The image whose colors are remapped by the LUT (lookup table).
|
||||
#[implementations(Raster<CPU>, Color, Gradient)]
|
||||
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)]
|
||||
image: Item<T>,
|
||||
/// A LUT (lookup table) file in the `.cube`, `.3dl`, `.look`, `.csp`, or `.icc` (*abstract* or *device link* ICC profile) format.
|
||||
#[name("LUT File")]
|
||||
@@ -1468,7 +1469,7 @@ mod tests {
|
||||
fn run_brightness_contrast(value: f32, brightness: f64, contrast: f64, use_classic: bool) -> f32 {
|
||||
let pixel = Color::from_gamma_srgb_channels(value / 255., value / 255., value / 255., 1.);
|
||||
let result = brightness_contrast((), Item::new_from_element(pixel), brightness.into(), contrast.into(), use_classic.into(), 127_f64.into());
|
||||
result.into_element().to_gamma_srgb_channels()[0] * 255.
|
||||
evaluate_color_effects(result).into_element().to_gamma_srgb_channels()[0] * 255.
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1566,7 +1567,7 @@ mod tests {
|
||||
100_f64.into(),
|
||||
AdjustmentChannel::Rgb.into(),
|
||||
);
|
||||
let [r, g, _, _] = result.into_element().to_gamma_srgb_channels();
|
||||
let [r, g, _, _] = evaluate_color_effects(result).into_element().to_gamma_srgb_channels();
|
||||
[r * 255., g * 255.]
|
||||
}
|
||||
|
||||
@@ -1611,7 +1612,7 @@ mod tests {
|
||||
20_f64.into(),
|
||||
80_f64.into(),
|
||||
);
|
||||
let [r, g, b, _] = result.into_element().to_gamma_srgb_channels();
|
||||
let [r, g, b, _] = evaluate_color_effects(result).into_element().to_gamma_srgb_channels();
|
||||
[r * 255., g * 255., b * 255.]
|
||||
}
|
||||
|
||||
@@ -1721,7 +1722,7 @@ mod tests {
|
||||
345_f64.into(),
|
||||
HueSaturationRange::Master.into(),
|
||||
);
|
||||
let [r, g, b, _] = result.into_element().to_gamma_srgb_channels();
|
||||
let [r, g, b, _] = evaluate_color_effects(result).into_element().to_gamma_srgb_channels();
|
||||
[r * 255., g * 255., b * 255.]
|
||||
}
|
||||
|
||||
@@ -1810,7 +1811,7 @@ mod tests {
|
||||
fn invert_flips_straight_channels_and_keeps_alpha() {
|
||||
let color = Color::from_gamma_srgb_channels(1., 0.25, 0., 0.5);
|
||||
|
||||
let inverted = invert((), Item::new_from_element(color)).into_element();
|
||||
let inverted = evaluate_color_effects(invert((), Item::new_from_element(color))).into_element();
|
||||
|
||||
let [r, g, b, a] = inverted.to_gamma_srgb_channels();
|
||||
assert!((r - 0.).abs() < 1e-5 && (g - 0.75).abs() < 1e-5 && (b - 1.).abs() < 1e-5, "inverted channels were {r} {g} {b}");
|
||||
@@ -1821,7 +1822,7 @@ mod tests {
|
||||
fn threshold_is_white(input: [f32; 3], level: f64) -> bool {
|
||||
let pixel = Color::from_gamma_srgb_channels(input[0] / 255., input[1] / 255., input[2] / 255., 1.);
|
||||
let result = threshold((), Item::new_from_element(pixel), (level / 255. * 100.).into(), 100_f64.into());
|
||||
result.into_element().r() == 1.
|
||||
evaluate_color_effects(result).into_element().r() == 1.
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1850,7 +1851,7 @@ mod tests {
|
||||
fn run_vibrance(input: [f32; 3], vibrance_amount: f64, saturation: f64) -> [f32; 3] {
|
||||
let pixel = Color::from_gamma_srgb_channels(input[0] / 255., input[1] / 255., input[2] / 255., 1.);
|
||||
let result = vibrance((), Item::new_from_element(pixel), vibrance_amount.into(), saturation.into());
|
||||
let [r, g, b, _] = result.into_element().to_gamma_srgb_channels();
|
||||
let [r, g, b, _] = evaluate_color_effects(result).into_element().to_gamma_srgb_channels();
|
||||
[r * 255., g * 255., b * 255.]
|
||||
}
|
||||
|
||||
@@ -1906,7 +1907,7 @@ mod tests {
|
||||
g(6, 0), g(6, 1), g(6, 2), g(6, 3), g(7, 0), g(7, 1), g(7, 2), g(7, 3), g(8, 0), g(8, 1), g(8, 2), g(8, 3),
|
||||
SelectiveColorChoice::Reds.into(),
|
||||
);
|
||||
let [r, g, b, _] = result.into_element().to_gamma_srgb_channels();
|
||||
let [r, g, b, _] = evaluate_color_effects(result).into_element().to_gamma_srgb_channels();
|
||||
[r * 255., g * 255., b * 255.]
|
||||
}
|
||||
|
||||
@@ -1942,7 +1943,10 @@ mod tests {
|
||||
/// Runs Posterize on one gamma-space gray value (0..255) and returns the gamma-space result on the same scale.
|
||||
fn run_posterize(value: f32, levels: i64) -> f32 {
|
||||
let pixel = Color::from_gamma_srgb_channels(value / 255., value / 255., value / 255., 1.);
|
||||
posterize((), Item::new_from_element(pixel), levels.into()).into_element().to_gamma_srgb_channels()[0] * 255.
|
||||
evaluate_color_effects(posterize((), Item::new_from_element(pixel), levels.into()))
|
||||
.into_element()
|
||||
.to_gamma_srgb_channels()[0]
|
||||
* 255.
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1966,7 +1970,7 @@ mod tests {
|
||||
fn run_exposure(value: f32, exposure: f64, offset: f64, gamma_correction: f64) -> f32 {
|
||||
let pixel = Color::from_gamma_srgb_channels(value / 255., value / 255., value / 255., 1.);
|
||||
let result = super::exposure((), Item::new_from_element(pixel), exposure.into(), offset.into(), gamma_correction.into());
|
||||
result.into_element().to_gamma_srgb_channels()[0] * 255.
|
||||
evaluate_color_effects(result).into_element().to_gamma_srgb_channels()[0] * 255.
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2018,7 +2022,7 @@ mod tests {
|
||||
preserve_luminosity.into(),
|
||||
TonalRange::Midtones.into(),
|
||||
);
|
||||
let [r, g, b, _] = result.into_element().to_gamma_srgb_channels();
|
||||
let [r, g, b, _] = evaluate_color_effects(result).into_element().to_gamma_srgb_channels();
|
||||
[r * 255., g * 255., b * 255.]
|
||||
}
|
||||
|
||||
@@ -2063,7 +2067,7 @@ mod tests {
|
||||
let pixel = Color::from_gamma_srgb_channels(input[0] / 255., input[1] / 255., input[2] / 255., 1.);
|
||||
let filter = Color::from_gamma_srgb_channels(filter[0] / 255., filter[1] / 255., filter[2] / 255., 1.);
|
||||
let result = photo_filter((), Item::new_from_element(pixel), filter.into(), density.into(), preserve_luminosity.into());
|
||||
let [r, g, b, _] = result.into_element().to_gamma_srgb_channels();
|
||||
let [r, g, b, _] = evaluate_color_effects(result).into_element().to_gamma_srgb_channels();
|
||||
[r * 255., g * 255., b * 255.]
|
||||
}
|
||||
|
||||
@@ -2089,4 +2093,78 @@ mod tests {
|
||||
// A white filter alters nothing, so the pixel keeps its channels once the above-white red is clipped
|
||||
assert_close(run_photo_filter([300., 200., 100.], [255., 255., 255.], 100., true), [255., 200., 100.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustments_stamp_rows_rather_than_changing_the_value() {
|
||||
use core_types::list::ATTR_EFFECTS;
|
||||
use graphic_types::{EffectKind, Effects};
|
||||
|
||||
let color = Color::from_rgbaf32_unchecked(0.2, 0.4, 0.6, 1.);
|
||||
let result = posterize((), invert((), Item::new_from_element(color)), 3_i64.into());
|
||||
assert_eq!(*result.element(), color, "the color itself is left alone");
|
||||
|
||||
let kinds: Vec<EffectKind> = result
|
||||
.attribute::<Effects>(ATTR_EFFECTS)
|
||||
.map(|effects| effects.effects().map(|effect| effect.kind()).collect())
|
||||
.unwrap_or_default();
|
||||
assert_eq!(kinds, [EffectKind::Invert, EffectKind::Posterize]);
|
||||
assert_eq!(
|
||||
result
|
||||
.attribute::<Effects>(ATTR_EFFECTS)
|
||||
.and_then(|effects| effects.effects().nth(1))
|
||||
.and_then(|row| row.0.attribute::<i64>("levels")),
|
||||
Some(&3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn posterizing_a_gradient_bands_its_ramp() {
|
||||
use raster_kernels::evaluate_gradient_effects;
|
||||
use vector_types::GradientSettings;
|
||||
|
||||
// Adjusting only the two end stops would leave a smooth ramp from black to white
|
||||
let result = evaluate_gradient_effects(posterize((), Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])), 2_i64.into()));
|
||||
let settings = GradientSettings::from_item_attributes(&result);
|
||||
|
||||
for t in [0.05, 0.2] {
|
||||
assert_eq!(result.element().evaluate(t, settings), Color::BLACK, "dark band at {t}");
|
||||
}
|
||||
for t in [0.8, 0.95] {
|
||||
assert_eq!(result.element().evaluate(t, settings), Color::WHITE, "light band at {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjusting_a_raster_follows_its_earlier_effects() {
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use glam::DAffine2;
|
||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
|
||||
// A white square in the middle of a transparent image, placed one pixel per document unit, then blurred
|
||||
let mut image = Image::new(20, 20, Color::TRANSPARENT);
|
||||
for y in 5..15 {
|
||||
for x in 5..15 {
|
||||
image.data[y * 20 + x] = Color::WHITE;
|
||||
}
|
||||
}
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(20.)));
|
||||
stamp_effect(
|
||||
&mut item,
|
||||
Effect::new(&EffectOperation::Blur {
|
||||
radius: 1.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
}),
|
||||
);
|
||||
let result = evaluate_raster_effects(super::make_opaque((), item));
|
||||
|
||||
// Just outside the square, the blur's faint white becomes opaque white, where making it opaque first would have blurred in black
|
||||
let transform: DAffine2 = result.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let raster = result.element();
|
||||
let pixel = (DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * transform.inverse()).transform_point2(DVec2::new(4.5, 10.5));
|
||||
let color = raster.data[pixel.y as usize * raster.width as usize + pixel.x as usize];
|
||||
assert_eq!(color.a(), 1.);
|
||||
assert!(color.r() > 0.99 && color.g() > 0.99 && color.b() > 0.99, "expected white, got {color:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,7 @@
|
||||
use crate::adjust::Adjust;
|
||||
use core_types::Ctx;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::Color;
|
||||
use core_types::list::Item;
|
||||
use graphic_types::Adjustment;
|
||||
use raster_types::{CPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
|
||||
pub use core_types::blending::{apply_blend_mode, blend_colors};
|
||||
|
||||
@@ -22,7 +18,8 @@ fn mix_colors(
|
||||
#[default(100.)]
|
||||
opacity: Item<f64>,
|
||||
) -> Item<Color> {
|
||||
let mut under = under;
|
||||
let mut under = raster_kernels::evaluate_color_effects(under);
|
||||
let over = raster_kernels::evaluate_color_effects(over);
|
||||
let blend_mode = blend_mode.into_element();
|
||||
let opacity = (opacity.into_element() / 100.) as f32;
|
||||
|
||||
@@ -30,65 +27,10 @@ fn mix_colors(
|
||||
under
|
||||
}
|
||||
|
||||
// TODO: Rename to "Paint Overlay" and take a `Graphic` paint like the `Fill` node, enabling this to serve the cases of Color Overlay, Gradient Overlay, and Pattern Overlay.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"))]
|
||||
fn color_overlay<T: Adjust>(
|
||||
_: impl Ctx,
|
||||
#[implementations(
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
)]
|
||||
image: Item<T>,
|
||||
#[default(Color::BLACK)] color: Item<Color>,
|
||||
blend_mode: Item<BlendMode>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
opacity: Item<f64>,
|
||||
) -> Item<T> {
|
||||
let mut image = image;
|
||||
let adjustment = Adjustment::ColorOverlay {
|
||||
color: color.into_element(),
|
||||
blend_mode: blend_mode.into_element(),
|
||||
opacity: opacity.into_element(),
|
||||
};
|
||||
image.element_mut().adjust(&adjustment);
|
||||
image
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::Color;
|
||||
use core_types::list::Item;
|
||||
use raster_types::Image;
|
||||
use raster_types::Raster;
|
||||
|
||||
#[test]
|
||||
fn color_overlay_multiply() {
|
||||
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
|
||||
let image = Image::new(1, 1, image_color);
|
||||
|
||||
// Color { red: 0., green: 1., blue: 0., alpha: 1. }
|
||||
let overlay_color = Color::GREEN;
|
||||
|
||||
// 100% of the output should come from the multiplied value
|
||||
let opacity = 100.;
|
||||
|
||||
let result = super::color_overlay(
|
||||
(),
|
||||
Item::new_from_element(Raster::new_cpu(image.clone())),
|
||||
overlay_color.into(),
|
||||
BlendMode::Multiply.into(),
|
||||
opacity.into(),
|
||||
);
|
||||
let result = result.into_element();
|
||||
|
||||
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
|
||||
assert_eq!(result.data[0], Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mix_colors_paints_over_at_its_opacity() {
|
||||
|
||||
@@ -2,6 +2,7 @@ use core_types::context::Ctx;
|
||||
use core_types::list::Item;
|
||||
use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage};
|
||||
use ndarray::{Array2, ArrayBase, Dim, OwnedRepr};
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
use raster_types::Image;
|
||||
use raster_types::{CPU, Raster};
|
||||
use std::cmp::{max, min};
|
||||
@@ -17,7 +18,7 @@ fn dehaze(
|
||||
) -> Item<Raster<CPU>> {
|
||||
let strength = *strength.element();
|
||||
|
||||
let (image, attributes) = image_frame.into_parts();
|
||||
let (image, attributes) = evaluate_raster_effects(image_frame).into_parts();
|
||||
let (width, height) = (image.width, image.height);
|
||||
|
||||
// Prepare the image data for processing
|
||||
|
||||
@@ -1,123 +1,12 @@
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use core_types::color::{Alpha, Color, Pixel, RGB};
|
||||
use core_types::color::Color;
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::Item;
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
use raster_types::Bitmap;
|
||||
use raster_types::Image;
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{Bitmap, BitmapMut};
|
||||
use raster_types::{CPU, Raster};
|
||||
|
||||
/// Working-buffer pixel for the blur algorithms' `gamma` mode: premultiplied sRGB-gamma `f32` channels.
|
||||
/// Only used internally so the working buffer's color space is reflected in the type instead of stuffed into `Color` (which is linear-light by invariant).
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable)]
|
||||
struct PremultipliedGammaPixel {
|
||||
r: f32,
|
||||
g: f32,
|
||||
b: f32,
|
||||
a: f32,
|
||||
}
|
||||
|
||||
impl Pixel for PremultipliedGammaPixel {}
|
||||
|
||||
impl RGB for PremultipliedGammaPixel {
|
||||
type ColorChannel = f32;
|
||||
fn red(&self) -> f32 {
|
||||
self.r
|
||||
}
|
||||
fn green(&self) -> f32 {
|
||||
self.g
|
||||
}
|
||||
fn blue(&self) -> f32 {
|
||||
self.b
|
||||
}
|
||||
}
|
||||
|
||||
impl Alpha for PremultipliedGammaPixel {
|
||||
type AlphaChannel = f32;
|
||||
const TRANSPARENT: Self = Self { r: 0., g: 0., b: 0., a: 0. };
|
||||
fn alpha(&self) -> f32 {
|
||||
self.a
|
||||
}
|
||||
fn multiplied_alpha(&self, mult: f32) -> Self {
|
||||
Self {
|
||||
r: self.r * mult,
|
||||
g: self.g * mult,
|
||||
b: self.b * mult,
|
||||
a: self.a * mult,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn premultiply_gamma(buffer: Image<Color>) -> Image<PremultipliedGammaPixel> {
|
||||
Image {
|
||||
width: buffer.width,
|
||||
height: buffer.height,
|
||||
data: buffer
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|px| {
|
||||
let [r, g, b, a] = px.to_gamma_srgb_channels();
|
||||
PremultipliedGammaPixel { r: r * a, g: g * a, b: b * a, a }
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn unpremultiply_gamma_to_linear(buffer: Image<PremultipliedGammaPixel>) -> Image<Color> {
|
||||
Image {
|
||||
width: buffer.width,
|
||||
height: buffer.height,
|
||||
data: buffer
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|px| {
|
||||
if px.a > 0. {
|
||||
let inv_a = 1. / px.a;
|
||||
Color::from_gamma_srgb_channels(px.r * inv_a, px.g * inv_a, px.b * inv_a, px.a)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Blurs the image with a Gaussian or box blur kernel filter.
|
||||
#[node_macro::node(category("Raster: Filter"), icon("NodeBlur"))]
|
||||
fn blur(
|
||||
_: impl Ctx,
|
||||
/// The image to be blurred.
|
||||
image_frame: Item<Raster<CPU>>,
|
||||
/// The radius of the blur kernel.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
radius: Item<f64>,
|
||||
/// Use a lower-quality box kernel instead of a circular Gaussian kernel. This is faster but produces boxy artifacts.
|
||||
box_blur: Item<bool>,
|
||||
/// Opt to incorrectly apply the filter with color calculations in gamma space for compatibility with the results from other software.
|
||||
gamma: Item<bool>,
|
||||
) -> Item<Raster<CPU>> {
|
||||
let (radius, box_blur, gamma) = (*radius.element(), *box_blur.element(), *gamma.element());
|
||||
|
||||
let (image, attributes) = image_frame.into_parts();
|
||||
|
||||
// TODO: Scale the radius through the footprint so it acts as the document-space length its Pixels unit promises, with a
|
||||
// window that varies continuously rather than snapping to whole source pixels
|
||||
let blurred_image = if radius < 0.1 {
|
||||
// Minimum blur radius
|
||||
image
|
||||
} else if box_blur {
|
||||
Raster::new_cpu(box_blur_algorithm(image.into_data(), radius, gamma))
|
||||
} else {
|
||||
Raster::new_cpu(gaussian_blur_algorithm(image.into_data(), radius, gamma))
|
||||
};
|
||||
|
||||
Item::from_parts(blurred_image, attributes)
|
||||
}
|
||||
|
||||
/// Applies a median filter to reduce noise while preserving edges.
|
||||
#[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"), memoize)]
|
||||
fn median_filter(
|
||||
@@ -133,7 +22,7 @@ fn median_filter(
|
||||
) -> Item<Raster<CPU>> {
|
||||
let radius = *radius.element();
|
||||
|
||||
let (image, attributes) = image_frame.into_parts();
|
||||
let (image, attributes) = evaluate_raster_effects(image_frame).into_parts();
|
||||
|
||||
// TODO: Scale the radius through the footprint so it acts as the document-space length its Pixels unit promises, with a
|
||||
// window that varies continuously rather than snapping to whole source pixels
|
||||
@@ -147,156 +36,6 @@ fn median_filter(
|
||||
Item::from_parts(filtered_image, attributes)
|
||||
}
|
||||
|
||||
// 1D gaussian kernel
|
||||
fn gaussian_kernel(radius: f64, image_extent: u32) -> Vec<f64> {
|
||||
// Given radius, compute the size of the kernel that's approximately three times the radius
|
||||
// Taps further out than the image extends never land on a pixel, so the kernel stops there while its weights keep the full radius
|
||||
let kernel_radius = ((3. * radius).ceil() as usize).min(image_extent as usize);
|
||||
let kernel_size = 2 * kernel_radius + 1;
|
||||
let mut gaussian_kernel: Vec<f64> = vec![0.; kernel_size];
|
||||
|
||||
// Kernel values
|
||||
let two_radius_squared = 2. * radius * radius;
|
||||
let sum = gaussian_kernel
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
.map(|(i, value_at_index)| {
|
||||
let x = i as f64 - kernel_radius as f64;
|
||||
let exponent = -(x * x) / two_radius_squared;
|
||||
*value_at_index = exponent.exp();
|
||||
*value_at_index
|
||||
})
|
||||
.sum::<f64>();
|
||||
|
||||
// Normalize
|
||||
gaussian_kernel.iter_mut().for_each(|value_at_index| *value_at_index /= sum);
|
||||
|
||||
gaussian_kernel
|
||||
}
|
||||
|
||||
fn gaussian_blur_algorithm(buffer: Image<Color>, radius: f64, gamma: bool) -> Image<Color> {
|
||||
let kernel = gaussian_kernel(radius, buffer.width.max(buffer.height));
|
||||
if gamma {
|
||||
let working = premultiply_gamma(buffer);
|
||||
let blurred = gaussian_separable(working, &kernel, |r, g, b, a| PremultipliedGammaPixel { r, g, b, a });
|
||||
unpremultiply_gamma_to_linear(blurred)
|
||||
} else {
|
||||
let mut working = buffer;
|
||||
working.map_pixels(|px| px.to_associated_alpha());
|
||||
let mut blurred = gaussian_separable(working, &kernel, Color::from_rgbaf32_unchecked);
|
||||
blurred.map_pixels(|px| px.to_unassociated_alpha());
|
||||
blurred
|
||||
}
|
||||
}
|
||||
|
||||
fn box_blur_algorithm(buffer: Image<Color>, radius: f64, gamma: bool) -> Image<Color> {
|
||||
if gamma {
|
||||
let working = premultiply_gamma(buffer);
|
||||
let blurred = box_separable(working, radius, |r, g, b, a| PremultipliedGammaPixel { r, g, b, a });
|
||||
unpremultiply_gamma_to_linear(blurred)
|
||||
} else {
|
||||
let mut working = buffer;
|
||||
working.map_pixels(|px| px.to_associated_alpha());
|
||||
let mut blurred = box_separable(working, radius, Color::from_rgbaf32_unchecked);
|
||||
blurred.map_pixels(|px| px.to_unassociated_alpha());
|
||||
blurred
|
||||
}
|
||||
}
|
||||
|
||||
fn gaussian_separable<P, F>(buffer: Image<P>, kernel: &[f64], construct: F) -> Image<P>
|
||||
where
|
||||
P: Pixel + Copy + RGB<ColorChannel = f32> + Alpha<AlphaChannel = f32>,
|
||||
F: Fn(f32, f32, f32, f32) -> P,
|
||||
{
|
||||
let (width, height) = buffer.dimensions();
|
||||
let half_kernel = kernel.len() / 2;
|
||||
|
||||
let mut x_axis = Image::new(width, height, P::default());
|
||||
let mut y_axis = Image::new(width, height, P::default());
|
||||
|
||||
for pass in [false, true] {
|
||||
let (max, old_buffer, current_buffer) = match pass {
|
||||
false => (width, &buffer, &mut x_axis),
|
||||
true => (height, &x_axis, &mut y_axis),
|
||||
};
|
||||
let pass = pass as usize;
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let (mut r_sum, mut g_sum, mut b_sum, mut a_sum, mut weight_sum) = (0., 0., 0., 0., 0.);
|
||||
|
||||
for (i, &weight) in kernel.iter().enumerate() {
|
||||
let p = [x, y][pass] as i32 + (i as i32 - half_kernel as i32);
|
||||
|
||||
if p >= 0
|
||||
&& p < max as i32
|
||||
&& let Some(px) = old_buffer.get_pixel([p as u32, x][pass], [y, p as u32][pass])
|
||||
{
|
||||
r_sum += px.r() as f64 * weight;
|
||||
g_sum += px.g() as f64 * weight;
|
||||
b_sum += px.b() as f64 * weight;
|
||||
a_sum += px.a() as f64 * weight;
|
||||
weight_sum += weight;
|
||||
}
|
||||
}
|
||||
|
||||
let (r, g, b, a) = if weight_sum > 0. {
|
||||
((r_sum / weight_sum) as f32, (g_sum / weight_sum) as f32, (b_sum / weight_sum) as f32, (a_sum / weight_sum) as f32)
|
||||
} else {
|
||||
let px = old_buffer.get_pixel(x, y).unwrap();
|
||||
(px.r(), px.g(), px.b(), px.a())
|
||||
};
|
||||
current_buffer.set_pixel(x, y, construct(r, g, b, a));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
y_axis
|
||||
}
|
||||
|
||||
fn box_separable<P, F>(buffer: Image<P>, radius: f64, construct: F) -> Image<P>
|
||||
where
|
||||
P: Pixel + Copy + RGB<ColorChannel = f32> + Alpha<AlphaChannel = f32>,
|
||||
F: Fn(f32, f32, f32, f32) -> P,
|
||||
{
|
||||
let (width, height) = buffer.dimensions();
|
||||
let mut x_axis = Image::new(width, height, P::default());
|
||||
let mut y_axis = Image::new(width, height, P::default());
|
||||
|
||||
let radius = radius.min(width.max(height) as f64) as i32;
|
||||
|
||||
for pass in [false, true] {
|
||||
let (max, old_buffer, current_buffer) = match pass {
|
||||
false => (width, &buffer, &mut x_axis),
|
||||
true => (height, &x_axis, &mut y_axis),
|
||||
};
|
||||
let pass = pass as usize;
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let (mut r_sum, mut g_sum, mut b_sum, mut a_sum, mut weight_sum) = (0., 0., 0., 0., 0.);
|
||||
|
||||
let i = [x, y][pass];
|
||||
for d in (i as i32 - radius).max(0)..=(i as i32 + radius).min(max as i32 - 1) {
|
||||
if let Some(px) = old_buffer.get_pixel([d as u32, x][pass], [y, d as u32][pass]) {
|
||||
let weight = 1.;
|
||||
r_sum += px.r() as f64 * weight;
|
||||
g_sum += px.g() as f64 * weight;
|
||||
b_sum += px.b() as f64 * weight;
|
||||
a_sum += px.a() as f64 * weight;
|
||||
weight_sum += weight;
|
||||
}
|
||||
}
|
||||
|
||||
let (r, g, b, a) = ((r_sum / weight_sum) as f32, (g_sum / weight_sum) as f32, (b_sum / weight_sum) as f32, (a_sum / weight_sum) as f32);
|
||||
current_buffer.set_pixel(x, y, construct(r, g, b, a));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
y_axis
|
||||
}
|
||||
|
||||
fn median_filter_algorithm(original_buffer: Image<Color>, radius: u32) -> Image<Color> {
|
||||
let (width, height) = original_buffer.dimensions();
|
||||
let mut output = Image::new(width, height, Color::TRANSPARENT);
|
||||
|
||||
@@ -2,6 +2,7 @@ use color::{ColorSpace, Oklab};
|
||||
use core_types::color::Color;
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::{Item, List};
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
use raster_types::{CPU, Raster};
|
||||
use std::collections::BinaryHeap;
|
||||
use std::ops::{AddAssign, SubAssign};
|
||||
@@ -25,6 +26,7 @@ fn image_color_palette(
|
||||
count: Item<i64>,
|
||||
) -> List<Color> {
|
||||
let count = *count.element() as usize;
|
||||
let image = evaluate_raster_effects(image);
|
||||
|
||||
// O(n) binning of the image's n pixels into an OkLab histogram, weighted by alpha so transparent pixels are ignored
|
||||
let mut cumulative = vec![Moments::default(); TABLE_SIDE.pow(3)];
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
pub mod adjust;
|
||||
pub mod adjustments;
|
||||
pub mod blending_nodes;
|
||||
pub use raster_kernels::color_lookup_table;
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::color::Color;
|
||||
use core_types::color::{Alpha, AlphaMut, Channel, LinearChannel, Luminance, RGBMut};
|
||||
use core_types::context::{Ctx, ExtractFootprint};
|
||||
use core_types::color::{Alpha, AlphaMut, LinearChannel, Luminance, RGBMut};
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::Item;
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::transform::Transform;
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::generator::{GeneratorPattern, NoiseSettings};
|
||||
use raster_kernels::generators::render_pattern;
|
||||
use graphic_types::generator::{Generator, NoiseSettings};
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{Bitmap, BitmapMut};
|
||||
use raster_types::{CPU, Raster};
|
||||
@@ -51,51 +51,68 @@ fn channels_to_image(
|
||||
) -> Result<Item<Raster<CPU>>, SizeMismatchError> {
|
||||
// An unconnected channel arrives as the default zero-sized raster, which counts as absent
|
||||
let present = |channel: Item<Raster<CPU>>| (channel.element().width > 0 && channel.element().height > 0).then_some(channel);
|
||||
let (red, green, blue, alpha) = (present(red), present(green), present(blue), present(alpha));
|
||||
|
||||
// Take this item's transform and blending attributes from the first present channel
|
||||
let Some(attributes) = [&red, &green, &blue, &alpha].iter().find_map(|channel| channel.as_ref()).map(|channel| channel.attributes().clone()) else {
|
||||
return Ok(Item::default());
|
||||
};
|
||||
let channels = [red, green, blue, alpha].map(present);
|
||||
|
||||
// All present channels must share the same dimensions
|
||||
let channel_dimensions = [("Red", &red), ("Green", &green), ("Blue", &blue), ("Alpha", &alpha)]
|
||||
.map(|(name, channel)| channel.as_ref().map(|channel| (name, UVec2::new(channel.element().width, channel.element().height))));
|
||||
let Some(&(first, first_size)) = channel_dimensions.iter().flatten().next() else {
|
||||
let dimensions = |channel: &Item<Raster<CPU>>| UVec2::new(channel.element().width, channel.element().height);
|
||||
let mut present_channels = ["Red", "Green", "Blue", "Alpha"]
|
||||
.into_iter()
|
||||
.zip(&channels)
|
||||
.filter_map(|(name, channel)| Some((name, channel.as_ref()?)));
|
||||
let Some((first, first_channel)) = present_channels.next() else {
|
||||
return Ok(Item::default());
|
||||
};
|
||||
if let Some(&(second, second_size)) = channel_dimensions.iter().flatten().find(|&&(_, size)| size != first_size) {
|
||||
let (first_size, transform) = (dimensions(first_channel), first_channel.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM));
|
||||
if let Some((second, second_channel)) = present_channels.find(|(_, channel)| dimensions(channel) != first_size) {
|
||||
return Err(SizeMismatchError {
|
||||
first,
|
||||
first_size,
|
||||
second,
|
||||
second_size,
|
||||
second_size: dimensions(second_channel),
|
||||
});
|
||||
}
|
||||
let (width, height) = (first_size.x, first_size.y);
|
||||
|
||||
// A channel's effects grow it by the margin they cast past its edges, so every channel is placed within the widest margin
|
||||
let channels = channels.map(|channel| channel.map(evaluate_raster_effects));
|
||||
let margin = |channel: &Item<Raster<CPU>>| ((channel.element().width - width) / 2, (channel.element().height - height) / 2);
|
||||
let (margin_x, margin_y) = channels
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(margin)
|
||||
.fold((0, 0), |(x, y), (channel_x, channel_y)| (x.max(channel_x), y.max(channel_y)));
|
||||
|
||||
// Take this item's blending attributes from the first present channel, whose effects are carried out by now
|
||||
let Some(mut attributes) = channels.iter().flatten().next().map(|channel| channel.attributes().clone()) else {
|
||||
return Ok(Item::default());
|
||||
};
|
||||
let size = DVec2::new(width as f64, height as f64);
|
||||
let unit_margin = DVec2::new(margin_x as f64, margin_y as f64) / size;
|
||||
attributes.insert(
|
||||
ATTR_TRANSFORM,
|
||||
transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin),
|
||||
);
|
||||
|
||||
// A channel's value at a pixel of the output, with nothing past its own edges, or `None` if the channel is absent
|
||||
let value = |channel: &Option<Item<Raster<CPU>>>, x: u32, y: u32| {
|
||||
channel.as_ref().map(|channel| {
|
||||
let (channel_margin_x, channel_margin_y) = margin(channel);
|
||||
let (x, y) = ((x + channel_margin_x).checked_sub(margin_x), (y + channel_margin_y).checked_sub(margin_y));
|
||||
x.zip(y).and_then(|(x, y)| channel.element().get_pixel(x, y)).map_or(0., |pixel| pixel.l().cast_linear_channel())
|
||||
})
|
||||
};
|
||||
|
||||
// Set each output pixel's channels from the present inputs, defaulting absent color channels to 0 and absent alpha to 1
|
||||
let mut image = Image::new(width, height, Color::TRANSPARENT);
|
||||
let [red, green, blue, alpha] = &channels;
|
||||
let mut image = Image::new(width + 2 * margin_x, height + 2 * margin_y, Color::TRANSPARENT);
|
||||
for y in 0..image.height() {
|
||||
for x in 0..image.width() {
|
||||
let image_pixel = image.get_pixel_mut(x, y).unwrap();
|
||||
|
||||
match red.as_ref().and_then(|r| r.element().get_pixel(x, y)) {
|
||||
Some(r) => image_pixel.set_red(r.l().cast_linear_channel()),
|
||||
None => image_pixel.set_red(Channel::from_linear(0.)),
|
||||
}
|
||||
match green.as_ref().and_then(|g| g.element().get_pixel(x, y)) {
|
||||
Some(g) => image_pixel.set_green(g.l().cast_linear_channel()),
|
||||
None => image_pixel.set_green(Channel::from_linear(0.)),
|
||||
}
|
||||
match blue.as_ref().and_then(|b| b.element().get_pixel(x, y)) {
|
||||
Some(b) => image_pixel.set_blue(b.l().cast_linear_channel()),
|
||||
None => image_pixel.set_blue(Channel::from_linear(0.)),
|
||||
}
|
||||
match alpha.as_ref().and_then(|a| a.element().get_pixel(x, y)) {
|
||||
Some(a) => image_pixel.set_alpha(a.l().cast_linear_channel()),
|
||||
None => image_pixel.set_alpha(Channel::from_linear(1.)),
|
||||
}
|
||||
image_pixel.set_red(value(red, x, y).unwrap_or(0.));
|
||||
image_pixel.set_green(value(green, x, y).unwrap_or(0.));
|
||||
image_pixel.set_blue(value(blue, x, y).unwrap_or(0.));
|
||||
image_pixel.set_alpha(value(alpha, x, y).unwrap_or(1.));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,6 +128,9 @@ fn mask(
|
||||
#[expose]
|
||||
stencil: Item<Raster<CPU>>,
|
||||
) -> Item<Raster<CPU>> {
|
||||
let image = evaluate_raster_effects(image);
|
||||
let stencil = evaluate_raster_effects(stencil);
|
||||
|
||||
// An absent stencil arrives as the default empty raster, leaving the image unmasked
|
||||
if stencil.element().width == 0 || stencil.element().height == 0 {
|
||||
return image;
|
||||
@@ -150,6 +170,7 @@ fn mask(
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn extend_image_to_bounds(_: impl Ctx, image: Item<Raster<CPU>>, bounds: Item<DAffine2>) -> Result<Item<Raster<CPU>>, (Item<Raster<CPU>>, ImageError)> {
|
||||
let image = evaluate_raster_effects(image);
|
||||
let bounds = *bounds.element();
|
||||
|
||||
let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
@@ -229,12 +250,11 @@ fn image(
|
||||
}
|
||||
|
||||
/// Generates customizable procedural noise patterns.
|
||||
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"))]
|
||||
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"), version(2))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn noise_pattern(
|
||||
ctx: impl ExtractFootprint + Ctx,
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[default(true)] clip: Item<bool>,
|
||||
#[hard(0..)] seed: Item<i64>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_scale")]
|
||||
#[default(10.)]
|
||||
@@ -264,80 +284,66 @@ fn noise_pattern(
|
||||
#[widget(ParsedWidgetOverride::Custom = "noise_inspector_cellular_jitter")]
|
||||
#[default(1.)]
|
||||
cellular_jitter: Item<f64>,
|
||||
) -> Result<Item<Raster<CPU>>, ImageError> {
|
||||
let (clip, seed, scale, domain_warp_amplitude) = (*clip.element(), *seed.element(), *scale.element(), *domain_warp_amplitude.element());
|
||||
let (fractal_octaves, fractal_lacunarity, fractal_gain) = (*fractal_octaves.element(), *fractal_lacunarity.element(), *fractal_gain.element());
|
||||
let (fractal_weighted_strength, fractal_ping_pong_strength, cellular_jitter) = (*fractal_weighted_strength.element(), *fractal_ping_pong_strength.element(), *cellular_jitter.element());
|
||||
let (noise_type, domain_warp_type, fractal_type) = (noise_type.into_element(), domain_warp_type.into_element(), fractal_type.into_element());
|
||||
let (cellular_distance_function, cellular_return_type) = (cellular_distance_function.into_element(), cellular_return_type.into_element());
|
||||
) -> Item<Generator> {
|
||||
let settings = NoiseSettings {
|
||||
seed: seed.into_element(),
|
||||
scale: scale.into_element(),
|
||||
noise_type: noise_type.into_element(),
|
||||
domain_warp_type: domain_warp_type.into_element(),
|
||||
domain_warp_amplitude: domain_warp_amplitude.into_element(),
|
||||
fractal_type: fractal_type.into_element(),
|
||||
fractal_octaves: fractal_octaves.into_element(),
|
||||
fractal_lacunarity: fractal_lacunarity.into_element(),
|
||||
fractal_gain: fractal_gain.into_element(),
|
||||
fractal_weighted_strength: fractal_weighted_strength.into_element(),
|
||||
fractal_ping_pong_strength: fractal_ping_pong_strength.into_element(),
|
||||
cellular_distance_function: cellular_distance_function.into_element(),
|
||||
cellular_return_type: cellular_return_type.into_element(),
|
||||
cellular_jitter: cellular_jitter.into_element(),
|
||||
};
|
||||
|
||||
let footprint = ctx.footprint();
|
||||
let viewport_bounds = footprint.viewport_bounds_in_local_space();
|
||||
|
||||
let mut size = viewport_bounds.size();
|
||||
let mut offset = viewport_bounds.start;
|
||||
if clip {
|
||||
// TODO: Remove "clip" entirely (and its arbitrary 100x100 clipping square) once we have proper resolution-aware layer clipping
|
||||
const CLIPPING_SQUARE_SIZE: f64 = 100.;
|
||||
let image_bounds = Bbox::from_transform(DAffine2::from_scale(DVec2::splat(CLIPPING_SQUARE_SIZE))).to_axis_aligned_bbox();
|
||||
let intersection = viewport_bounds.intersect(&image_bounds);
|
||||
|
||||
offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
|
||||
size = intersection.size();
|
||||
}
|
||||
|
||||
// If the image would not be visible, return an empty image
|
||||
if size.x <= 0. || size.y <= 0. {
|
||||
return Ok(Item::default());
|
||||
}
|
||||
|
||||
let transform = DAffine2::from_translation(offset) * DAffine2::from_scale(size);
|
||||
|
||||
let footprint_scale = footprint.scale();
|
||||
let width = (size.x * footprint_scale.x) as u32;
|
||||
let height = (size.y * footprint_scale.y) as u32;
|
||||
|
||||
let noise = GeneratorPattern::Noise(NoiseSettings {
|
||||
seed,
|
||||
scale,
|
||||
noise_type,
|
||||
domain_warp_type,
|
||||
domain_warp_amplitude,
|
||||
fractal_type,
|
||||
fractal_octaves,
|
||||
fractal_lacunarity,
|
||||
fractal_gain,
|
||||
fractal_weighted_strength,
|
||||
fractal_ping_pong_strength,
|
||||
cellular_distance_function,
|
||||
cellular_return_type,
|
||||
cellular_jitter,
|
||||
});
|
||||
let image = render_pattern(&noise, [offset, offset + size], width, height)?;
|
||||
|
||||
Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform))
|
||||
let mut generator = Item::new_from_element(Generator::Noise);
|
||||
settings.stamp(&mut generator);
|
||||
generator
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"))]
|
||||
fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Result<Item<Raster<CPU>>, ImageError> {
|
||||
let footprint = ctx.footprint();
|
||||
let viewport_bounds = footprint.viewport_bounds_in_local_space();
|
||||
#[node_macro::node(category("Raster"), icon("NodeMandelbrot"), version(2))]
|
||||
fn mandelbrot(_: impl Ctx, _primary: ()) -> Item<Generator> {
|
||||
Item::new_from_element(Generator::Mandelbrot)
|
||||
}
|
||||
|
||||
let image_bounds = Bbox::from_transform(DAffine2::IDENTITY).to_axis_aligned_bbox();
|
||||
let intersection = viewport_bounds.intersect(&image_bounds);
|
||||
let size = intersection.size();
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO);
|
||||
#[test]
|
||||
fn channels_stay_aligned_when_effects_grow_only_one() {
|
||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||
|
||||
// If the image would not be visible, return an empty image
|
||||
if size.x <= 0. || size.y <= 0. {
|
||||
return Ok(Item::default());
|
||||
}
|
||||
let gray = |value: f32| {
|
||||
let image = Image::new(8, 8, Color::from_rgbaf32_unchecked(value, value, value, 1.));
|
||||
Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.)))
|
||||
};
|
||||
|
||||
let scale = footprint.scale();
|
||||
let width = (size.x * scale.x) as u32;
|
||||
let height = (size.y * scale.y) as u32;
|
||||
let image = render_pattern(&GeneratorPattern::Mandelbrot, [offset, offset + size], width, height)?;
|
||||
// Only the red channel is blurred, which grows it by the blur's margin
|
||||
let mut red = gray(1.);
|
||||
stamp_effect(
|
||||
&mut red,
|
||||
Effect::new(&EffectOperation::Blur {
|
||||
radius: 1.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
}),
|
||||
);
|
||||
let image = channels_to_image((), (), red, gray(0.5), gray(0.25), gray(1.)).unwrap();
|
||||
|
||||
Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(offset) * DAffine2::from_scale(size)))
|
||||
// The other channels are placed within the same margin, and the whole image keeps its place in the document
|
||||
let raster = image.element();
|
||||
assert!(raster.width > 8 && raster.height > 8, "the image grows to hold the blur, rather than coming out empty");
|
||||
let transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * transform.inverse();
|
||||
let center = to_pixels.transform_point2(DVec2::splat(4.)).as_uvec2();
|
||||
let pixel = raster.get_pixel(center.x, center.y).unwrap();
|
||||
assert!((pixel.g() - 0.5).abs() < 1e-6 && (pixel.b() - 0.25).abs() < 1e-6, "the unblurred channels line up: {pixel:?}");
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ use core::f64::consts::TAU;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, Interrupt, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Generator;
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
@@ -24,6 +25,7 @@ fn repeat<T: Send + Clone + 'static>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
@@ -69,6 +71,7 @@ fn repeat_array<T: Send + Clone + 'static>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
@@ -130,6 +133,7 @@ fn repeat_radial<T: Send + Clone + 'static>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
@@ -188,6 +192,7 @@ fn repeat_on_points<T: Send + Clone + 'static>(
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<Gradient>,
|
||||
Context -> List<Generator>,
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = List<T>>,
|
||||
|
||||
@@ -7,7 +7,7 @@ use core_types::transform::{ApplyTransform, ScaleType, Transform};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, Interrupt, ModifyFootprint, OwnedContextImpl};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use graphic_types::{Artboard, Generator, Graphic, Vector};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies the specified transform to the input content.
|
||||
@@ -24,6 +24,7 @@ fn transform<T: Send + 'static>(
|
||||
Context -> Item<Raster<GPU>>,
|
||||
Context -> Item<Color>,
|
||||
Context -> Item<Gradient>,
|
||||
Context -> Item<Generator>,
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = Item<T>>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_translation")] translation: Item<DVec2>,
|
||||
@@ -158,7 +159,7 @@ fn replace_transform<T>(
|
||||
|
||||
/// Obtains the transform of the input content.
|
||||
#[node_macro::node(category("Transform"), icon("NodeExtractTransform"), path(core_types::vector))]
|
||||
fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
|
||||
fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, Generator, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
|
||||
Item::new_from_element(content.attribute_cloned_or_default(ATTR_TRANSFORM))
|
||||
}
|
||||
|
||||
@@ -224,7 +225,7 @@ fn decompose_skew(_: impl Ctx, transform: Item<DAffine2>) -> Item<f64> {
|
||||
fn vary_rotations<T: Send>(
|
||||
_: impl Ctx,
|
||||
/// The content with items to rotate individually.
|
||||
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<String>)]
|
||||
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Generator>, List<String>)]
|
||||
content: List<T>,
|
||||
/// The lower end of the range of angles given to the items.
|
||||
#[unit("°")]
|
||||
@@ -278,7 +279,7 @@ fn vary_rotations<T: Send>(
|
||||
fn vary_scales<T: Send>(
|
||||
_: impl Ctx,
|
||||
/// The content with items to scale individually.
|
||||
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<String>)]
|
||||
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Generator>, List<String>)]
|
||||
content: List<T>,
|
||||
/// The lower end of the range of scale factors given to the items.
|
||||
#[unit("x")]
|
||||
|
||||
@@ -26,6 +26,7 @@ graphene-core = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
repeat-nodes = { workspace = true }
|
||||
|
||||
|
||||
@@ -354,6 +354,7 @@ fn vary_cover_colors<T: VectorListIterMut>(
|
||||
repeat_every: Item<i64>,
|
||||
) -> Result<T, VaryColorsError> {
|
||||
let (reverse, randomize, seed, repeat_every) = (reverse.into_element(), randomize.into_element(), seed.into_element(), repeat_every.into_element());
|
||||
let gradient = raster_kernels::evaluate_gradient_effects(gradient);
|
||||
|
||||
if gradient.element().is_empty() {
|
||||
return Err(VaryColorsError::EmptyGradient);
|
||||
|
||||
@@ -68,7 +68,7 @@ Without a compile server, all the nodes are precompiled when Graphite is built.
|
||||
|
||||
### GPU rendering
|
||||
|
||||
Nodes run on the CPU, and the renderer draws their results on the GPU with [Vello](https://github.com/linebender/vello) through [`wgpu`](https://wgpu.rs/) (WebGL2 in browsers). Raster nodes, like the adjustments and filters, process their pixels on the CPU.
|
||||
The values that flow through the graph stay on the CPU, and the renderer is what uses the GPU. Raster operations like adjustments and effects are recorded as data on the content they apply to, then carried out by the renderer with [WGSL](https://www.w3.org/TR/WGSL/) shaders through [`wgpu`](https://wgpu.rs/) (WebGL2 in browsers), only for the pixels being drawn and at the resolution they're drawn at. Nodes that need to read pixels carry out those operations on the CPU instead.
|
||||
|
||||
### A language within a language
|
||||
|
||||
|
||||
Reference in new issue
Block a user