mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7469ecce35 | ||
|
|
d69b21f035 | ||
|
|
7e2e1fe028 | ||
|
|
12daaf8ab0 |
No files matched your search
Generated
+2
@@ -5772,12 +5772,14 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -6,5 +6,6 @@ mod mandelbrot_v2;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod noise_pattern_v2;
|
||||
mod passthrough_from_extend_image_to_bounds;
|
||||
mod pattern_square;
|
||||
mod renames;
|
||||
@@ -0,0 +1,36 @@
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// 'Extend Image to Bounds' is gone, and the transparent pixels it padded an image with drew nothing, so it passes its image on and drops its bounds.
|
||||
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
||||
pub fn passthrough_from_extend_image_to_bounds(inputs: &mut Inputs) {
|
||||
inputs.truncate(1);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PassthroughFromExtendImageToBounds, &contract());
|
||||
check_undo(&PassthroughFromExtendImageToBounds, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_image_and_drops_the_bounds() {
|
||||
let (image, bounds) = (literal(1.), literal(2.));
|
||||
|
||||
let mut fixture = Fixture::new(&PassthroughFromExtendImageToBounds);
|
||||
let extend = fixture.add(decl!("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1), vec![image.clone(), bounds]);
|
||||
let migrated = fixture.migrate(&PassthroughFromExtendImageToBounds).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, extend), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, extend), [image]);
|
||||
}
|
||||
}
|
||||
@@ -4,3 +4,12 @@ use migration_core::rename;
|
||||
|
||||
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
|
||||
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
|
||||
|
||||
// 'Image to Channels' became 'Into Channels', taking and giving graphics, whose stored input and channel outputs keep their places
|
||||
rename!("raster_nodes::adjustments::ImageToChannelsNode"@1 => "raster_nodes::channels::IntoChannelsNode"@2);
|
||||
|
||||
// 'Channels to Image' became 'From Channels', taking and giving graphics, whose stored inputs and output keep their places
|
||||
rename!("raster_nodes::std_nodes::ChannelsToImageNode"@1 => "raster_nodes::channels::FromChannelsNode"@2);
|
||||
|
||||
// 'Median Filter' became an effect taking any graphic, whose stored image and radius keep their places
|
||||
rename!("raster_nodes::filter::MedianFilterNode"@1 => @2);
|
||||
@@ -121,6 +121,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_std::raster::SampleImageNode",
|
||||
"graphene_std::raster::SampleNode",
|
||||
"raster_nodes::std_nodes::SampleImageNode",
|
||||
// The deleted Extend Image to Bounds passes its image through, since the transparent pixels it padded with drew nothing
|
||||
"graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
||||
"graphene_std::raster::ExtendImageToBoundsNode",
|
||||
"raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -545,8 +549,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::channels::into_channels::IDENTIFIER,
|
||||
aliases: &["raster_nodes::adjustments::ImageToChannelsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::channels::from_channels::IDENTIFIER,
|
||||
aliases: &[
|
||||
"raster_nodes::std_nodes::ChannelsToImageNode",
|
||||
"raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_std::raster::CombineChannelsNode",
|
||||
@@ -564,10 +573,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ExposureNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode", "graphene_std::raster::ExtendImageToBoundsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||
@@ -1564,13 +1569,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `image_to_channels` proto nodes.
|
||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `into_channels` proto nodes.
|
||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||
let split_wrapper_replacements = [
|
||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::channels::into_channels::IDENTIFIER),
|
||||
];
|
||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
@@ -1616,7 +1621,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Image to Channels" nodes.
|
||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Into Channels" nodes.
|
||||
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
||||
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
||||
const EXTRACT_CHANNEL: [&str; 4] = [
|
||||
@@ -1635,7 +1640,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if EXTRACT_XY.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||
Some((*node_id, path, graphene_std::raster_nodes::channels::into_channels::IDENTIFIER, "Extract Channel"))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -3247,9 +3252,17 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||
}
|
||||
|
||||
// Sample Image nodes, now passthroughs, drop their old title
|
||||
// Sample Image and Extend Image to Bounds nodes, now passthroughs, drop their old titles and any inputs past the first, like Extend Image to Bounds's bounds
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) {
|
||||
reset_default_display_name(document, node_id, network_path, "Sample Image");
|
||||
reset_default_display_name(document, node_id, network_path, "Extend Image to Bounds");
|
||||
|
||||
if inputs_count > 1 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize became As String, whose input converts a wired value to text, while a stored value keeps the JSON text Serialize made of it
|
||||
@@ -6318,6 +6331,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_image_to_bounds_opens_as_a_passthrough_of_its_image() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let (image, extend) = (NodeId(1), NodeId(2));
|
||||
let image_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
||||
.expect("the Image definition should exist")
|
||||
.default_node_template();
|
||||
let extend_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("raster_nodes::std_nodes::ExtendImageToBoundsNode")),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::DAffine2(DAffine2::IDENTITY), false)],
|
||||
display_name: "Extend Image to Bounds".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node(image, image_template, &[]);
|
||||
document.network_interface.insert_node(extend, extend_template, &[]);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(extend, 0), NodeInput::node(image, 0), &[]);
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let node = opened.network_interface.document_node(&extend, &[]).expect("the node should still exist");
|
||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||
assert!(matches!(node.inputs[..], [NodeInput::Node { node_id, output_index: 0, .. }] if node_id == image), "{:?}", node.inputs);
|
||||
assert_ne!(opened.network_interface.display_name(&extend, &[]), "Extend Image to Bounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
|
||||
@@ -86,6 +86,8 @@ pub enum Adjustment {
|
||||
opacity: f64,
|
||||
},
|
||||
Solarize,
|
||||
/// Shows the alpha as a gray of the same gamma-encoded level, keeping the alpha, so a luminance mask of the gray shows as much as the alpha.
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl Adjustment {
|
||||
@@ -112,6 +114,7 @@ impl Adjustment {
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Solarize => EffectKind::Solarize,
|
||||
Self::AlphaToGray => EffectKind::AlphaToGray,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,7 +154,7 @@ impl Adjustment {
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
||||
Self::Invert | Self::Solarize => {}
|
||||
Self::Invert | Self::Solarize | Self::AlphaToGray => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
|
||||
@@ -490,6 +490,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Median { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
|
||||
@@ -15,7 +15,7 @@ use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, List};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, ItemAttributeValues, List};
|
||||
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
@@ -60,6 +60,8 @@ pub enum EffectKind {
|
||||
FindEdges,
|
||||
/// Spreads each pixel's darkest or lightest neighboring colors.
|
||||
MinimumMaximum,
|
||||
/// Gives each pixel the middle value of each channel among those around it, removing specks while keeping edges.
|
||||
Median,
|
||||
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
||||
Sharpen,
|
||||
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
||||
@@ -117,6 +119,8 @@ pub enum EffectKind {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
/// Shows the content's alpha as a gray, as 'Into Channels' does for its alpha output.
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
@@ -137,6 +141,7 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::Emboss => "Emboss",
|
||||
Self::FindEdges => "Find Edges",
|
||||
Self::MinimumMaximum => "Minimum/Maximum",
|
||||
Self::Median => "Median",
|
||||
Self::Sharpen => "Sharpen",
|
||||
Self::HighPass => "High Pass",
|
||||
Self::Speckle => "Speckle",
|
||||
@@ -175,6 +180,7 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
Self::Solarize => "Solarize",
|
||||
Self::AlphaToGray => "Alpha to Gray",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -218,6 +224,9 @@ pub enum MinimumMaximumMode {
|
||||
Maximum,
|
||||
}
|
||||
|
||||
/// The most pixels a median's square reaches out from its center on its grid, whose cost grows with the square's area. Past it, the grid coarsens instead.
|
||||
pub const MAX_MEDIAN_GRID_RADIUS: f64 = 16.;
|
||||
|
||||
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct EffectCapture {
|
||||
@@ -486,17 +495,30 @@ impl Effects {
|
||||
self.operations().map(|operation| operation.required_reach()).sum()
|
||||
}
|
||||
|
||||
/// How many pixels per unit of their effect space a run of these effects renders at, at most, if any of them works on the content's own grid (see [`EffectOperation::works_on_content_grid`]).
|
||||
/// It's one, except that a median reaching past [`MAX_MEDIAN_GRID_RADIUS`] whole units coarsens the grid to bound its cost.
|
||||
pub fn content_grid_resolution(&self) -> Option<f64> {
|
||||
let grid_resolution = |operation: EffectOperation| match operation {
|
||||
EffectOperation::Median { radius } => (MAX_MEDIAN_GRID_RADIUS / radius.floor()).min(1.),
|
||||
_ => 1.,
|
||||
};
|
||||
self.operations().filter(EffectOperation::works_on_content_grid).map(grid_resolution).reduce(f64::min)
|
||||
}
|
||||
|
||||
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
||||
/// A transform applied between two effects starts a new run, which renders around the result of those before it.
|
||||
/// A transform applied between two effects, or an effect on the content's own grid (which runs alone at its grid's resolution), starts a new run around the result of those before it.
|
||||
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
||||
pub fn runs(&self) -> Vec<(DAffine2, Range<usize>)> {
|
||||
let mut runs: Vec<(DAffine2, Range<usize>)> = Vec::new();
|
||||
let mut run_changes_something = false;
|
||||
let (mut run_changes_something, mut run_on_content_grid) = (false, false);
|
||||
for (index, effect) in self.effects().enumerate() {
|
||||
let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let changes_something = !effect.operation().changes_nothing();
|
||||
let operation = effect.operation();
|
||||
let (changes_something, on_content_grid) = (!operation.changes_nothing(), operation.works_on_content_grid());
|
||||
|
||||
let shares_grid = !(on_content_grid && run_changes_something) && !(run_on_content_grid && changes_something);
|
||||
if let Some((transform, rows)) = runs.last_mut()
|
||||
&& shares_grid
|
||||
&& (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2))
|
||||
{
|
||||
if changes_something && !run_changes_something {
|
||||
@@ -504,9 +526,10 @@ impl Effects {
|
||||
}
|
||||
rows.end = index + 1;
|
||||
run_changes_something |= changes_something;
|
||||
run_on_content_grid |= on_content_grid;
|
||||
} else {
|
||||
runs.push((stamped_transform, index..index + 1));
|
||||
run_changes_something = changes_something;
|
||||
(run_changes_something, run_on_content_grid) = (changes_something, on_content_grid);
|
||||
}
|
||||
}
|
||||
runs
|
||||
@@ -846,8 +869,14 @@ pub fn contour_gradient_position(distance: f32, start: f32, span: f32) -> f32 {
|
||||
/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point.
|
||||
/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect.
|
||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||
let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS)
|
||||
stamp_effect_on(item.attributes_mut(), effect);
|
||||
}
|
||||
|
||||
/// Like [`stamp_effect`], given the item's attributes.
|
||||
pub fn stamp_effect_on(attributes: &mut ItemAttributeValues, effect: Effect) {
|
||||
let transform = stamped_transform(attributes.get::<DAffine2>(ATTR_TRANSFORM).copied().unwrap_or_default());
|
||||
attributes
|
||||
.get_or_insert_default_mut::<Effects>(ATTR_EFFECTS)
|
||||
.0
|
||||
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
||||
}
|
||||
@@ -1097,6 +1126,11 @@ pub enum EffectOperation {
|
||||
radius: f64,
|
||||
mode: MinimumMaximumMode,
|
||||
},
|
||||
/// Carried out on the content's own grid of pixels (see [`Self::works_on_content_grid`]), then resampled to the view.
|
||||
Median {
|
||||
/// How many pixels the square neighborhood reaches out from its center, of which the whole pixels count.
|
||||
radius: f64,
|
||||
},
|
||||
Sharpen {
|
||||
/// Percent.
|
||||
amount: f64,
|
||||
@@ -1298,6 +1332,7 @@ impl EffectOperation {
|
||||
Self::Emboss { .. } => EffectKind::Emboss,
|
||||
Self::FindEdges => EffectKind::FindEdges,
|
||||
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
||||
Self::Median { .. } => EffectKind::Median,
|
||||
Self::Sharpen { .. } => EffectKind::Sharpen,
|
||||
Self::HighPass { .. } => EffectKind::HighPass,
|
||||
Self::Speckle { .. } => EffectKind::Speckle,
|
||||
@@ -1398,6 +1433,8 @@ impl EffectOperation {
|
||||
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
||||
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
||||
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
||||
// Only whole pixels count, so one of less than a pixel reads the pixel alone
|
||||
Self::Median { radius } => *radius < 1.,
|
||||
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
|
||||
}
|
||||
}
|
||||
@@ -1424,7 +1461,7 @@ impl EffectOperation {
|
||||
Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => {
|
||||
true
|
||||
}
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Median { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
|
||||
Self::DropShadow { .. }
|
||||
| Self::InnerShadow { .. }
|
||||
@@ -1438,6 +1475,12 @@ impl EffectOperation {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this operation is carried out on the content's own grid of pixels, one to each unit of its effect space, and the result resampled to the view, since it doesn't commute with resampling.
|
||||
/// So it looks the same at every zoom, and on an image at its own size when stamped, it reads the image's pixels.
|
||||
pub fn works_on_content_grid(&self) -> bool {
|
||||
matches!(self, Self::Median { .. }) && !self.changes_nothing()
|
||||
}
|
||||
|
||||
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
||||
pub fn painted_reach(&self) -> f64 {
|
||||
let keeps_coverage = matches!(
|
||||
@@ -1451,6 +1494,8 @@ impl EffectOperation {
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
..
|
||||
}
|
||||
// Its coverage is the window's middle one, which past the content's bounds comes from a window at least half beyond them
|
||||
| Self::Median { .. }
|
||||
| Self::Sharpen { .. }
|
||||
| Self::HighPass { .. }
|
||||
);
|
||||
@@ -1493,6 +1538,7 @@ impl EffectOperation {
|
||||
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
||||
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
||||
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
||||
Self::Median { radius } => radius.max(0.).floor() + 1.,
|
||||
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
||||
Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3.,
|
||||
// They reach as far as `Effects::reach_around` measures from where the content lies
|
||||
@@ -1587,7 +1633,7 @@ impl EffectOperation {
|
||||
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
||||
Self::Feather { distance } => finite(distance),
|
||||
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
||||
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
|
||||
Self::MinimumMaximum { radius, .. } | Self::Median { radius } | Self::HighPass { radius } => finite(radius),
|
||||
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
||||
Self::Speckle { amount, .. } => finite(amount),
|
||||
Self::Dissolve { opacity, .. } => finite(opacity),
|
||||
@@ -1758,6 +1804,7 @@ impl EffectOperation {
|
||||
radius: 0.,
|
||||
mode: MinimumMaximumMode::default(),
|
||||
},
|
||||
EffectKind::Median => Self::Median { radius: 0. },
|
||||
EffectKind::Sharpen => Self::Sharpen {
|
||||
amount: 0.,
|
||||
radius: 0.,
|
||||
@@ -1886,6 +1933,7 @@ impl EffectOperation {
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
||||
EffectKind::AlphaToGray => Self::Adjustment(Adjustment::AlphaToGray),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2099,6 +2147,7 @@ impl EffectOperation {
|
||||
visitor.parameter("radius", radius, 1.);
|
||||
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
||||
}
|
||||
Self::Median { radius } => visitor.parameter("radius", radius, 0.),
|
||||
Self::Sharpen {
|
||||
amount,
|
||||
radius,
|
||||
@@ -2401,6 +2450,7 @@ mod tests {
|
||||
radius: 7.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Median { radius: 3.5 },
|
||||
EffectOperation::Adjustment(Adjustment::Solarize),
|
||||
EffectOperation::Sharpen {
|
||||
amount: 180.,
|
||||
@@ -2899,6 +2949,7 @@ mod tests {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
AlphaToGray,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
@@ -2998,6 +3049,7 @@ mod tests {
|
||||
radius: 3.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Median { radius: 3.5 },
|
||||
EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 3.,
|
||||
@@ -3021,6 +3073,28 @@ mod tests {
|
||||
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_median_works_on_the_content_grid_coarsened_past_its_largest_radius() {
|
||||
let median = |radius| Effects::from_operations([EffectOperation::Median { radius }]);
|
||||
assert_eq!(median(0.5).content_grid_resolution(), None, "less than a whole pixel changes nothing");
|
||||
assert_eq!(median(5.9).content_grid_resolution(), Some(1.));
|
||||
assert_eq!(median(64.).content_grid_resolution(), Some(MAX_MEDIAN_GRID_RADIUS / 64.));
|
||||
assert_eq!(Effects::from_operations([EffectOperation::FindEdges]).content_grid_resolution(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_median_runs_alone_at_its_own_grid_resolution() {
|
||||
let median = |radius| EffectOperation::Median { radius };
|
||||
let nothing = median(0.);
|
||||
let effects = Effects::from_operations([nothing.clone(), median(1.), median(64.), nothing, EffectOperation::FindEdges, median(2.)]);
|
||||
|
||||
// Effects changing nothing join a median's run, but nothing else does
|
||||
let runs: Vec<_> = effects.runs().into_iter().map(|(_, rows)| rows).collect();
|
||||
assert_eq!(runs, vec![0..2, 2..4, 4..5, 5..6]);
|
||||
let resolutions: Vec<_> = runs.into_iter().map(|rows| effects.run(rows).content_grid_resolution()).collect();
|
||||
assert_eq!(resolutions, [Some(1.), Some(MAX_MEDIAN_GRID_RADIUS / 64.), None, Some(1.)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baking_the_content_placement_into_its_geometry_keeps_its_mask_in_place() {
|
||||
fn nested_placement(graphic: &Graphic) -> DAffine2 {
|
||||
|
||||
@@ -164,6 +164,7 @@ pub fn is_filter(operation: &EffectOperation) -> bool {
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Median { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
|
||||
@@ -24,7 +24,7 @@ pub use artboard::Artboard;
|
||||
pub use blend_if::BlendIfChannel;
|
||||
pub use effects::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||
stamp_effect, stamped_transform,
|
||||
stamp_effect, stamp_effect_on, stamped_transform,
|
||||
};
|
||||
pub use filters::NoiseDistribution;
|
||||
pub use generator::Generator;
|
||||
|
||||
@@ -1715,10 +1715,10 @@ impl EffectOperation {
|
||||
FrameWarp::of(self).is_some() || warp_of(self).is_some()
|
||||
}
|
||||
|
||||
/// Whether this operation takes the content's frame, which displacements and lattices measure from, unless it changes nothing.
|
||||
/// Whether this operation takes the content's frame, which displacements and lattices measure from and a median reads within, unless it changes nothing.
|
||||
pub fn takes_frame(&self) -> bool {
|
||||
match self {
|
||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } => !self.changes_nothing(),
|
||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } | Self::Median { .. } => !self.changes_nothing(),
|
||||
Self::Twirl { .. }
|
||||
| Self::Pinch { .. }
|
||||
| Self::Spherize { .. }
|
||||
|
||||
@@ -30,11 +30,12 @@ pub enum StepKind {
|
||||
ColorLookup,
|
||||
ColorOverlay,
|
||||
Solarize,
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl StepKind {
|
||||
/// Every kind, in the order of their codes.
|
||||
pub const ALL: [StepKind; 21] = [
|
||||
pub const ALL: [StepKind; 22] = [
|
||||
StepKind::Desaturate,
|
||||
StepKind::GammaCorrection,
|
||||
StepKind::MakeOpaque,
|
||||
@@ -56,6 +57,7 @@ impl StepKind {
|
||||
StepKind::ColorLookup,
|
||||
StepKind::ColorOverlay,
|
||||
StepKind::Solarize,
|
||||
StepKind::AlphaToGray,
|
||||
];
|
||||
|
||||
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
||||
@@ -269,6 +271,7 @@ mod tests {
|
||||
opacity: 50.,
|
||||
},
|
||||
Adjustment::Solarize,
|
||||
Adjustment::AlphaToGray,
|
||||
];
|
||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||
|
||||
|
||||
@@ -226,6 +226,7 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
||||
}
|
||||
Adjustment::Invert => visitor.visit(Invert),
|
||||
Adjustment::Solarize => visitor.visit(Solarize),
|
||||
Adjustment::AlphaToGray => visitor.visit(AlphaToGray),
|
||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||
min_luminance: (min_luminance / 100.) as f32,
|
||||
max_luminance: (max_luminance / 100.) as f32,
|
||||
@@ -1121,6 +1122,20 @@ impl MapColor for Solarize {
|
||||
}
|
||||
}
|
||||
|
||||
/// Grays each color to the gamma-encoded level of its alpha, keeping the alpha.
|
||||
struct AlphaToGray;
|
||||
|
||||
impl MapColor for AlphaToGray {
|
||||
fn map_cpu(&self, color: Color) -> Color {
|
||||
let gray = srgb_to_linear(color.a());
|
||||
color.map_rgb(|_| gray)
|
||||
}
|
||||
|
||||
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
||||
steps.push(StepKind::AlphaToGray, []);
|
||||
}
|
||||
}
|
||||
|
||||
struct Threshold {
|
||||
min_luminance: f32,
|
||||
max_luminance: f32,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The pixel filters on the CPU, which mirror the renderer's GPU passes on premultiplied gamma-encoded channels.
|
||||
|
||||
use crate::effect_kernels::{BlurKernel, Plane};
|
||||
use crate::resample_kernels::sample_bilinear;
|
||||
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use graphic_types::effects::{MAX_MEDIAN_GRID_RADIUS, spans_along_axes};
|
||||
use graphic_types::filters::{
|
||||
Convolution, FieldSampling, GAUSSIAN_NOISE_LIMIT, HIGH_PASS_GRAY, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, average_weight,
|
||||
edge_gain, fill_shifts, neighborhood_radii, noise_extent, unsharp, unsharp_change,
|
||||
@@ -10,6 +11,7 @@ use graphic_types::filters::{
|
||||
use graphic_types::generator::pcg3d;
|
||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Carries out a filter effect on premultiplied gamma-encoded pixels, which `pixels_to_effect` places in the effect space, or returns them as they are for any other operation.
|
||||
/// The pixels visible in the `full`-strength content (the plane itself for `None`) are those whose colors the filter reads.
|
||||
@@ -475,6 +477,105 @@ fn window_extremes(source: &[[f32; 4]], target: &mut [[f32; 4]], radius: usize,
|
||||
}
|
||||
}
|
||||
|
||||
/// The GPU's median of `radius` whole effect-space units, which `pixels_per_length` makes pixels along each axis, on a grid of a pixel to each unit coarsened past [`MAX_MEDIAN_GRID_RADIUS`] as the GPU's is.
|
||||
/// The `image` is the range of pixels along each axis holding the image, whose own pixels read only each other, and `origin` its corner, where the coarse grid starts.
|
||||
pub fn median_on_content_grid(plane: &Plane<[f32; 4]>, radius: f64, pixels_per_length: DVec2, origin: DVec2, image: [Range<usize>; 2]) -> Plane<[f32; 4]> {
|
||||
let whole = radius.max(0.).floor();
|
||||
let coarsening = (MAX_MEDIAN_GRID_RADIUS / whole).min(1.);
|
||||
if coarsening >= 1. {
|
||||
let radii = (pixels_per_length * whole).round().min(DVec2::new(plane.width as f64, plane.height as f64));
|
||||
return match radii == DVec2::ZERO {
|
||||
true => plane.clone(),
|
||||
false => median(plane, [radii.x as usize, radii.y as usize], image),
|
||||
};
|
||||
}
|
||||
|
||||
// The coarse grid's texels, each spanning this many pixels, lie on a lattice from the image's corner, as the GPU's lattice lies from the content's origin
|
||||
let texel = pixels_per_length / coarsening;
|
||||
let first = ((DVec2::ZERO - origin) / texel).floor();
|
||||
let end = ((DVec2::new(plane.width as f64, plane.height as f64) - origin) / texel).ceil();
|
||||
let size = (end - first).max(DVec2::ONE);
|
||||
let texel_center = |index: DVec2| origin + (first + index + 0.5) * texel;
|
||||
|
||||
// The content drawn onto the coarse grid by sampling it at each texel's center, as the GPU draws it
|
||||
let (coarse_width, coarse_height) = (size.x as usize, size.y as usize);
|
||||
let mut coarse = Plane::new(coarse_width, coarse_height);
|
||||
fill_rows(&mut coarse.data, coarse_width, |y, row| {
|
||||
for (x, texel) in row.iter_mut().enumerate() {
|
||||
*texel = sample_bilinear(plane, texel_center(DVec2::new(x as f64, y as f64)));
|
||||
}
|
||||
});
|
||||
|
||||
// The texels whose centers lie within the image, and the median over a window of the radius in texels, then resampled back onto the pixels
|
||||
let within = |axis: usize, count: usize| {
|
||||
let inside = |index: usize| image[axis].contains(&(texel_center(DVec2::splat(index as f64))[axis].floor().max(0.) as usize));
|
||||
let start = (0..count).find(|&index| inside(index)).unwrap_or(count);
|
||||
let end = (start..count).find(|&index| !inside(index)).unwrap_or(count);
|
||||
start..end
|
||||
};
|
||||
let radius_in_texels = (coarsening * whole).round() as usize;
|
||||
let medians = median(&coarse, [radius_in_texels; 2], [within(0, coarse_width), within(1, coarse_height)]);
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let center = DVec2::new(x as f64, y as f64) + 0.5;
|
||||
*pixel = sample_bilinear(&medians, (center - origin) / texel - first);
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// The median of each pixel's window reaching `across` and `down` pixels, as the GPU's median finds it: the alpha's among the window's pixels, with those past the plane's edges transparent,
|
||||
/// and each straight color's among those with coverage, taking the upper median of an even count. A pixel within the `within` range along each axis reads only pixels within it. O(width × height × across × down).
|
||||
pub fn median(plane: &Plane<[f32; 4]>, [across, down]: [usize; 2], within: [Range<usize>; 2]) -> Plane<[f32; 4]> {
|
||||
let inside = |x: isize, y: isize| x >= 0 && y >= 0 && within[0].contains(&(x as usize)) && within[1].contains(&(y as usize));
|
||||
let upper_median = |values: &mut [f32]| *values.select_nth_unstable_by(values.len() / 2, f32::total_cmp).1;
|
||||
let window_capacity = (2 * across + 1) * (2 * down + 1);
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
// Allocated once for the row and reused for each of its pixels
|
||||
let mut alphas: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut colors: [Vec<f32>; 3] = std::array::from_fn(|_| Vec::with_capacity(window_capacity));
|
||||
|
||||
let y = y as isize;
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let x = x as isize;
|
||||
alphas.clear();
|
||||
colors.iter_mut().for_each(Vec::clear);
|
||||
|
||||
let clips = inside(x, y);
|
||||
for read_y in y - down as isize..=y + down as isize {
|
||||
for read_x in x - across as isize..=x + across as isize {
|
||||
if clips && !inside(read_x, read_y) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let on_plane = read_x >= 0 && read_y >= 0 && (read_x as usize) < plane.width && (read_y as usize) < plane.height;
|
||||
let [red, green, blue, alpha] = if on_plane { plane.data[read_y as usize * plane.width + read_x as usize] } else { [0.; 4] };
|
||||
alphas.push(alpha.min(1.));
|
||||
if alpha > 0. {
|
||||
// Kept within the finite range of the GPU's half floats
|
||||
let straight = |channel: f32| (channel / alpha).max(0.).min(65504.);
|
||||
colors.iter_mut().zip([red, green, blue]).for_each(|(values, channel)| values.push(straight(channel)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let alpha = upper_median(&mut alphas);
|
||||
*pixel = match colors[0].is_empty() || !(alpha > 0.) {
|
||||
true => [0.; 4],
|
||||
false => {
|
||||
let [red, green, blue] = colors.each_mut().map(|values| upper_median(values));
|
||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// A value strictly between 0 and 1 from the top 23 bits of a hash, which an f32 holds exactly with the half added, matching the GPU's.
|
||||
fn unit_interval(hash: u32) -> f32 {
|
||||
((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32
|
||||
|
||||
@@ -550,6 +550,16 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
}
|
||||
// An image of its own has nothing beneath it to blur, or for Blend If to read, which fades the content where it acts
|
||||
EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => {}
|
||||
EffectOperation::Median { radius } => {
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
let origin = DVec2::new(margin_x as f64, margin_y as f64);
|
||||
let median = |plane: &Plane<[f32; 4]>| {
|
||||
let image = [margin_x..margin_x + width, margin_y..margin_y + height];
|
||||
crate::filter_kernels::median_on_content_grid(plane, radius, pixels_per_length, origin, image)
|
||||
};
|
||||
full = median(&full);
|
||||
filled = filled.map(|filled| median(&filled));
|
||||
}
|
||||
// A solid paint overlay paints within the content alone, like any other paint overlay
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => {
|
||||
let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32));
|
||||
|
||||
@@ -1755,7 +1755,7 @@ fn svg_expresses_adjustment(adjustment: &Adjustment) -> bool {
|
||||
use graphic_types::adjustment::DesaturateMethod;
|
||||
|
||||
match adjustment {
|
||||
Adjustment::Threshold { .. } | Adjustment::GradientMap { .. } | Adjustment::ChannelMixer(_) | Adjustment::ColorOverlay { .. } => true,
|
||||
Adjustment::Threshold { .. } | Adjustment::GradientMap { .. } | Adjustment::ChannelMixer(_) | Adjustment::ColorOverlay { .. } | Adjustment::AlphaToGray => true,
|
||||
Adjustment::Desaturate { method } => matches!(
|
||||
method,
|
||||
DesaturateMethod::LuminanceRec709 | DesaturateMethod::ChannelsAverage | DesaturateMethod::LumaRec709 | DesaturateMethod::LumaRec601
|
||||
@@ -2095,6 +2095,10 @@ impl SvgFilterPrimitives {
|
||||
};
|
||||
self.push("feColorMatrix", &format!(r#"in="{image}" color-interpolation-filters="{space}" {}"#, matrix([weights; 3])), "")
|
||||
}
|
||||
Adjustment::AlphaToGray => {
|
||||
let values = "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0";
|
||||
self.push("feColorMatrix", &format!(r#"{} type="matrix" values="{values}""#, in_gamma(image)), "")
|
||||
}
|
||||
// TODO: Express the other cross-channel adjustments, which no SVG primitive covers exactly
|
||||
_ => image.to_string(),
|
||||
}
|
||||
@@ -2472,6 +2476,7 @@ fn write_svg_effects_filter_on_lattice(
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Median { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
@@ -2482,7 +2487,8 @@ fn write_svg_effects_filter_on_lattice(
|
||||
primitives.merge_beneath(&mut full, &mut filled, beneath.take());
|
||||
|
||||
// Those keeping the content's coverage leave alone all a layer cutting its pieces within the content reads
|
||||
let changes_coverage = matches!(operation, EffectOperation::MinimumMaximum { .. } | EffectOperation::Dissolve { .. }) || graphic_types::filters::sharpens_coverage(&operation);
|
||||
let changes_coverage = matches!(operation, EffectOperation::MinimumMaximum { .. } | EffectOperation::Median { .. } | EffectOperation::Dissolve { .. })
|
||||
|| graphic_types::filters::sharpens_coverage(&operation);
|
||||
if !shows_content && !changes_coverage {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -98,6 +98,8 @@ impl SvgFilterPrimitives {
|
||||
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
||||
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
|
||||
// No SVG primitive ranks values, and the GPU's median runs on the content's own grid besides
|
||||
EffectOperation::Median { .. } => self.map_showing(capture, image),
|
||||
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
|
||||
EffectOperation::Speckle { amount, distribution, .. } => self.speckle(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
||||
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
|
||||
|
||||
@@ -584,9 +584,12 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
square && !operation.changes_nothing()
|
||||
});
|
||||
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
|
||||
let (frame_to_device, lengths_to_frame) = match follows_viewport {
|
||||
true => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
||||
false => {
|
||||
// Effects that don't commute with resampling, like a median, work on the content's own grid of a texel to each unit of the effect space, then resample to the view
|
||||
let content_grid_resolution = effects.content_grid_resolution();
|
||||
let (frame_to_device, lengths_to_frame) = match (content_grid_resolution, follows_viewport) {
|
||||
(Some(_), _) => (effect_to_device, DMat2::IDENTITY),
|
||||
(None, true) => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
||||
(None, false) => {
|
||||
let density = largest_stretch(effect_to_device.matrix2);
|
||||
(effect_to_device * DAffine2::from_scale(DVec2::splat(1. / density)), DMat2::from_diagonal(DVec2::splat(density)))
|
||||
}
|
||||
@@ -647,7 +650,15 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
|
||||
// A region too large for one texture, or for its memory, renders at a lower resolution, which the blurs and shadows that make it so large hide.
|
||||
// Its size rounds up to a size class so a group that moves between renders keeps reusing the same textures.
|
||||
let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt()).min(1.);
|
||||
let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt());
|
||||
let resolution = resolution.min(content_grid_resolution.unwrap_or(1.)).min(1.);
|
||||
|
||||
// A coarsened content grid keeps its texels on one lattice of the effect space, so they don't slide across the content as the view pans
|
||||
if content_grid_resolution.is_some() && resolution < 1. {
|
||||
let snap = |coordinate: f64| (coordinate * resolution).floor() / resolution;
|
||||
region = Rect::new(snap(region.x0), snap(region.y0), region.x1, region.y1);
|
||||
}
|
||||
|
||||
let size_along = |length: f64| ((length * resolution).ceil() as u32).next_multiple_of(EFFECTS_SIZE_CLASS).min(max_size);
|
||||
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
||||
let origin = region.origin().to_vec2();
|
||||
|
||||
@@ -109,6 +109,7 @@ fn step_function(kind: StepKind) -> (&'static str, Option<[Encoding; 2]>) {
|
||||
StepKind::ColorLookup => ("color_lookup", Some([Gamma, Gamma])),
|
||||
StepKind::ColorOverlay => ("color_overlay", Some([Gamma, Gamma])),
|
||||
StepKind::Solarize => ("solarize", Some([Gamma, Gamma])),
|
||||
StepKind::AlphaToGray => ("alpha_to_gray", Some([Gamma, Gamma])),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -365,6 +365,11 @@ fn solarize(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||
return vec4<f32>(min(color.rgb, 1. - color.rgb), color.a);
|
||||
}
|
||||
|
||||
// The alpha as a gray of the same gamma-encoded level, keeping the alpha
|
||||
fn alpha_to_gray(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||
return vec4<f32>(vec3<f32>(color.a), color.a);
|
||||
}
|
||||
|
||||
// Matches `apply_levels` with the gamma of 1 that every caller here passes, so its power is left out
|
||||
fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, output_minimum: f32, output_maximum: f32) -> f32 {
|
||||
let highlights_minus_shadows = clamp(input_highlights - input_shadows, F32_EPSILON, 1.);
|
||||
|
||||
@@ -853,6 +853,18 @@ impl EffectPasses {
|
||||
capture_plane(recorder, plane, map, true)
|
||||
});
|
||||
}
|
||||
// The fill's plane takes a median of its own, which an SVG takes as its map where the fill forks the content
|
||||
EffectOperation::Median { radius } => {
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
let median_full = recorder.median(full.as_ref().unwrap_or(content), radius, lengths_to_pixels, frame.as_ref());
|
||||
capture_plane(&mut recorder, 0, &median_full, true);
|
||||
if let Some(filled) = filled.as_mut() {
|
||||
let median_filled = recorder.median(filled, radius, lengths_to_pixels, frame.as_ref());
|
||||
capture_plane(&mut recorder, 1, &median_filled, true);
|
||||
recorder.replace(filled, median_filled);
|
||||
}
|
||||
recorder.replace_or_fill(&mut full, median_full);
|
||||
}
|
||||
EffectOperation::MotionBlur { angle, distance, gamma } => {
|
||||
// Anchored at the effect space's origin, which is the content's, so the shear moves with it
|
||||
let Some(shear) = MotionBlurShear::new(angle, distance, lengths_to_pixels, effect_to_pixels.translation) else {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! The GPU passes of the filter effects, matching the CPU's `filter_kernels`.
|
||||
|
||||
use super::{PARAMETER_TAPS, Parameters, PassRecorder, SUMS_FORMAT, WORKING_FORMAT};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use glam::{DAffine2, DMat2, DVec2, UVec2};
|
||||
use graphic_types::effects::{MAX_MEDIAN_GRID_RADIUS, spans_along_axes};
|
||||
use graphic_types::filters::{
|
||||
Convolution, FieldSampling, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, neighborhood_radii, noise_extent, sharpens_coverage, unsharp,
|
||||
};
|
||||
use graphic_types::resampling::EffectFrame;
|
||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||
use raster_kernels::effect_kernels::BlurKernel;
|
||||
use raster_kernels::filter_kernels::pixel_fill_shifts;
|
||||
@@ -13,6 +14,11 @@ use raster_kernels::filter_kernels::pixel_fill_shifts;
|
||||
/// The most texels a neighborhood's first pass reads each way, beyond which each further pass at most doubles its reach by reading two texels.
|
||||
const MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS: u32 = 8;
|
||||
|
||||
/// How many bits a median ranks the values of half floats by: their 32-bit float bit patterns without the low 13 bits a half float leaves empty, which order as the values do.
|
||||
const MEDIAN_KEY_BITS: u32 = 18;
|
||||
/// How many bits of each median's key a median pass decides, by three thresholds for each channel.
|
||||
const MEDIAN_BITS_PER_PASS: u32 = 2;
|
||||
|
||||
/// The `convolution`'s shifts mapped onto texels by `lengths_to_pixels`, with their weights divided by its divisor.
|
||||
fn convolution_taps(convolution: &Convolution, lengths_to_pixels: DMat2) -> Vec<[f32; 4]> {
|
||||
let tap = |&(shift, weight): &(DVec2, f64)| {
|
||||
@@ -455,6 +461,48 @@ impl PassRecorder<'_> {
|
||||
}
|
||||
widened
|
||||
}
|
||||
|
||||
/// The image with each texel's alpha the median of those in the square of `radius` whole document pixels around it, and each straight color the median among those with coverage,
|
||||
/// a texel inside the content's `frame` reading only those inside it. Exact, deciding two more bits of the medians' keys (see [`MEDIAN_KEY_BITS`]) a pass.
|
||||
/// O(width × height × radius²), with the radius in texels at most [`MAX_MEDIAN_GRID_RADIUS`], past which the content's grid coarsens instead.
|
||||
pub(super) fn median(&mut self, image: &wgpu::Texture, radius: f64, lengths_to_pixels: DMat2, frame: Option<&EffectFrame>) -> wgpu::Texture {
|
||||
let radii = (spans_along_axes(lengths_to_pixels) * radius.max(0.).floor()).round().min(DVec2::splat(MAX_MEDIAN_GRID_RADIUS));
|
||||
let radii = radii.as_uvec2().min(self.size);
|
||||
if radii == UVec2::ZERO {
|
||||
return self.scale(image, 1.);
|
||||
}
|
||||
|
||||
let prepared = self.run("median_prepare", WORKING_FORMAT, self.size, image, None, None, Parameters::default());
|
||||
|
||||
// The frame's unit square, which a texel center within the frame lies in, placed on the texels
|
||||
let (pixels_to_frame, clips) = match frame {
|
||||
Some(frame) => (frame.to_pixels.inverse(), 1.),
|
||||
None => (DAffine2::IDENTITY, 0.),
|
||||
};
|
||||
let [x_axis, y_axis] = [pixels_to_frame.matrix2.x_axis, pixels_to_frame.matrix2.y_axis].map(|axis| axis.as_vec2());
|
||||
|
||||
// Each pass decides more bits of every channel's median, carried between passes as whole numbers in 32-bit floats
|
||||
let passes = MEDIAN_KEY_BITS / MEDIAN_BITS_PER_PASS;
|
||||
let mut decided: Option<wgpu::Texture> = None;
|
||||
for pass in 0..passes {
|
||||
let last = pass + 1 == passes;
|
||||
let lowest_bit = MEDIAN_KEY_BITS - MEDIAN_BITS_PER_PASS * (pass + 1);
|
||||
let flag = |on: bool| if on { 1. } else { 0. };
|
||||
let parameters = Parameters {
|
||||
step: radii.as_vec2().to_array(),
|
||||
offset: pixels_to_frame.translation.as_vec2().to_array(),
|
||||
color: [x_axis.x, x_axis.y, y_axis.x, y_axis.y],
|
||||
values: [lowest_bit as f32, flag(decided.is_some()), flag(last), clips],
|
||||
..Default::default()
|
||||
};
|
||||
let format = if last { WORKING_FORMAT } else { SUMS_FORMAT };
|
||||
let next = self.run("median_bisect", format, self.size, &prepared, None, decided.as_ref(), parameters);
|
||||
self.replace_or_fill(&mut decided, next);
|
||||
}
|
||||
|
||||
self.textures.release(prepared);
|
||||
decided.unwrap_or_else(|| self.scale(image, 1.))
|
||||
}
|
||||
}
|
||||
|
||||
/// The radii a window of extremes widens through from `from` texels each way to `to`, each at most double the one before it, or from none, at most [`MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS`].
|
||||
|
||||
@@ -492,3 +492,92 @@ fn dissolve(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let shown = select(0., field.x, color.a * 255. > field.y + 0.5);
|
||||
return vec4<f32>(color.rgb / color.a * shown, shown);
|
||||
}
|
||||
|
||||
// The straight colors and alpha a median ranks, as half floats kept within their finite range at or above 0, where their bit patterns order as their values do, or nothing without coverage
|
||||
@fragment
|
||||
fn median_prepare(@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.);
|
||||
}
|
||||
let straight = color.rgb / color.a;
|
||||
return vec4<f32>(min(select(vec3<f32>(0.), straight, straight > vec3<f32>(0.)), vec3<f32>(65504.)), min(color.a, 1.));
|
||||
}
|
||||
|
||||
// The 32-bit float bit patterns of the four half float values at or above 0, without the low 13 bits a half float leaves empty, which order as the values do
|
||||
fn median_keys(values: vec4<f32>) -> vec4<u32> {
|
||||
return bitcast<vec4<u32>>(values) >> vec4<u32>(13u);
|
||||
}
|
||||
|
||||
// Whether a texel's center lies within the content's frame, whose unit square the linear part `color` (by columns) and `offset` place texels in
|
||||
fn median_in_frame(texel: vec2<i32>) -> bool {
|
||||
let unit = mat2x2<f32>(parameters.color.xy, parameters.color.zw) * (vec2<f32>(texel) + 0.5) + parameters.offset;
|
||||
return all(unit >= vec2<f32>(0.)) && all(unit < vec2<f32>(1.));
|
||||
}
|
||||
|
||||
// Two more bits (from bit `values.x` up) of each channel's median as `median_keys` (of `source`): the alpha's among the window's texels, and each straight color's among those with coverage,
|
||||
// in the window reaching `step` texels across and down, taking the upper median of an even count. A pass after the first (`values.y` 1) goes on from the bits decided before it (`content`),
|
||||
// and the last (`values.z` 1) writes the medians as a premultiplied color. With `values.w` 1, a texel within the content's frame reads only the texels within it.
|
||||
@fragment
|
||||
fn median_bisect(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let last = vec2<i32>(textureDimensions(source)) - 1;
|
||||
let radii = vec2<i32>(parameters.step);
|
||||
let width = 1u << u32(parameters.values.x);
|
||||
|
||||
var decided = vec4<u32>(0u);
|
||||
if parameters.values.y > 0.5 {
|
||||
decided = vec4<u32>(textureLoad(content, pixel, 0));
|
||||
}
|
||||
let first_threshold = decided + width;
|
||||
let second_threshold = decided + 2u * width;
|
||||
let third_threshold = decided + 3u * width;
|
||||
|
||||
// Only a window crossing the frame's edge has its texels tested, since the frame is convex
|
||||
var clips = parameters.values.w > 0.5 && median_in_frame(pixel);
|
||||
if clips {
|
||||
let corners_within = median_in_frame(pixel - radii) && median_in_frame(pixel + radii) && median_in_frame(pixel + vec2<i32>(radii.x, -radii.y)) && median_in_frame(pixel + vec2<i32>(-radii.x, radii.y));
|
||||
clips = !corners_within;
|
||||
}
|
||||
|
||||
var below_first = vec4<u32>(0u);
|
||||
var below_second = vec4<u32>(0u);
|
||||
var below_third = vec4<u32>(0u);
|
||||
var counted = 0u;
|
||||
var visible = 0u;
|
||||
for (var y = -radii.y; y <= radii.y; y++) {
|
||||
for (var x = -radii.x; x <= radii.x; x++) {
|
||||
let texel = pixel + vec2<i32>(x, y);
|
||||
if clips && !median_in_frame(texel) {
|
||||
continue;
|
||||
}
|
||||
counted += 1u;
|
||||
|
||||
// Past the texture's edges lies nothing, and a texel without coverage has no colors to rank
|
||||
let within = all(texel >= vec2<i32>(0)) && all(texel <= last);
|
||||
let keys = median_keys(select(vec4<f32>(0.), textureLoad(source, clamp(texel, vec2<i32>(0), last), 0), within));
|
||||
// Counts convert from booleans, since WebGL's GLSL can't select between integers
|
||||
let shown = u32(keys.a > 0u);
|
||||
visible += shown;
|
||||
let hidden = (1u - shown) * 0xffffffffu;
|
||||
let ranked = keys | vec4<u32>(hidden, hidden, hidden, 0u);
|
||||
|
||||
below_first += vec4<u32>(ranked < first_threshold);
|
||||
below_second += vec4<u32>(ranked < second_threshold);
|
||||
below_third += vec4<u32>(ranked < third_threshold);
|
||||
}
|
||||
}
|
||||
|
||||
// The median lies past each threshold that fewer keys than its rank lie below
|
||||
let rank = vec4<u32>(vec3<u32>(visible / 2u + 1u), counted / 2u + 1u);
|
||||
decided += (vec4<u32>(below_first < rank) + vec4<u32>(below_second < rank) + vec4<u32>(below_third < rank)) * width;
|
||||
if parameters.values.z < 0.5 {
|
||||
return vec4<f32>(decided);
|
||||
}
|
||||
|
||||
let medians = bitcast<vec4<f32>>(decided << vec4<u32>(13u));
|
||||
if visible == 0u || !(medians.a > 0.) {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
return vec4<f32>(medians.rgb * medians.a, medians.a);
|
||||
}
|
||||
@@ -4871,6 +4871,191 @@ fn gpu_neighborhood_extremes_match_the_cpu_kernels() {
|
||||
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
||||
}
|
||||
|
||||
/// The exact result of a Median of `radius` whole texels on premultiplied `texels` (`width` across) with nothing past their edges: the upper median of each window's alphas,
|
||||
/// and of each straight color among the texels with coverage, which the passes hold as half floats. O(texels × radius² log radius).
|
||||
fn median_reference(texels: &[[f32; 4]], width: usize, radius: isize) -> Vec<[f32; 4]> {
|
||||
use half::f16;
|
||||
|
||||
let height = (texels.len() / width) as isize;
|
||||
let straight: Vec<[f32; 4]> = (texels.iter())
|
||||
.map(|&[red, green, blue, alpha]| match alpha > 0. {
|
||||
true => [red / alpha, green / alpha, blue / alpha, alpha].map(|value| f16::from_f32(value).to_f32()),
|
||||
false => [0.; 4],
|
||||
})
|
||||
.collect();
|
||||
let upper_median = |mut values: Vec<f32>| {
|
||||
values.sort_by(f32::total_cmp);
|
||||
values[values.len() / 2]
|
||||
};
|
||||
|
||||
(0..texels.len())
|
||||
.map(|index| {
|
||||
let (x, y) = ((index % width) as isize, (index / width) as isize);
|
||||
let mut alphas = Vec::new();
|
||||
let mut colors: [Vec<f32>; 3] = Default::default();
|
||||
for (shift_x, shift_y) in (-radius..=radius).flat_map(|shift_y| (-radius..=radius).map(move |shift_x| (shift_x, shift_y))) {
|
||||
let (read_x, read_y) = (x + shift_x, y + shift_y);
|
||||
let within = (0..width as isize).contains(&read_x) && (0..height).contains(&read_y);
|
||||
let texel = if within { straight[(read_y * width as isize + read_x) as usize] } else { [0.; 4] };
|
||||
alphas.push(texel[3]);
|
||||
if texel[3] > 0. {
|
||||
colors.iter_mut().zip(texel).for_each(|(channel, value)| channel.push(value));
|
||||
}
|
||||
}
|
||||
|
||||
let alpha = upper_median(alphas);
|
||||
if alpha <= 0. || colors[0].is_empty() {
|
||||
return [0.; 4];
|
||||
}
|
||||
let [red, green, blue] = colors.map(upper_median);
|
||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_medians_match_the_exact_reference() {
|
||||
use graphic_types::{EffectOperation, Effects};
|
||||
use half::f16;
|
||||
|
||||
// Random colors, opaque but for a fully transparent band and a translucent one, so some windows rank colors among fewer texels than alphas
|
||||
let (width, height) = (37, 23);
|
||||
let texels: Vec<[f16; 4]> = (0..width * height)
|
||||
.map(|index| {
|
||||
let (x, y) = (index % width, index / width);
|
||||
let alpha = match (x, y) {
|
||||
(10..14, _) => 0.,
|
||||
(_, 5..8) => 0.4,
|
||||
_ => 1.,
|
||||
};
|
||||
let random = |seed: u32| ((index as u32).wrapping_mul(2_654_435_761).wrapping_add(seed.wrapping_mul(40_503)) >> 24) as f32 / 255.;
|
||||
[random(1) * alpha, random(2) * alpha, random(3) * alpha, alpha].map(f16::from_f32)
|
||||
})
|
||||
.collect();
|
||||
let unrounded: Vec<[f32; 4]> = texels.iter().map(|texel| texel.map(f16::to_f32)).collect();
|
||||
|
||||
let mut strays = Vec::new();
|
||||
for radius in [1, 2, 3, 6] {
|
||||
let effects = Effects::from_operations([EffectOperation::Median { radius: radius as f64 + 0.5 }]);
|
||||
let Some(gpu) = gpu_effect_texels(&effects, &texels, width, &[]) else { return };
|
||||
let reference = median_reference(&unrounded, width, radius);
|
||||
|
||||
// In 8-bit levels, within the rounding of half floats
|
||||
let levels = (gpu.iter().zip(&reference))
|
||||
.flat_map(|(gpu, reference)| (0..4).map(|channel| (gpu[channel] - reference[channel]).abs() * 255.))
|
||||
.fold(0_f32, f32::max);
|
||||
if levels > 0.5 {
|
||||
strays.push(format!("a median of radius {radius} strays from the exact one by {levels} levels"));
|
||||
}
|
||||
}
|
||||
assert!(strays.is_empty(), "{}", strays.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medians_work_on_an_images_own_pixels_at_any_zoom() {
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::list::{Item, List};
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
// A square of 2×2 white pixels on black, which a median of radius 1 removes, since it fills under half of each 3×3 window
|
||||
let mut image = Image::new(6, 6, core_types::Color::BLACK);
|
||||
for (x, y) in [(2, 2), (3, 2), (2, 3), (3, 3)] {
|
||||
image.data[y * 6 + x] = core_types::Color::WHITE;
|
||||
}
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(6.)));
|
||||
stamp_effect(&mut item, Effect::new(&EffectOperation::Median { radius: 1. }));
|
||||
let list = List::new_from_item(item);
|
||||
|
||||
// Zoomed in, a median of the view's pixels would keep the square, which then fills most of each window
|
||||
for zoom in [1., 4.] {
|
||||
let size = UVec2::splat((6. * zoom) as u32);
|
||||
let view = DAffine2::from_scale(DVec2::splat(zoom));
|
||||
let Some(pixels) = render_in_view(size, view, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
let center = (3. * zoom) as u32;
|
||||
assert_eq!(pixel(&pixels, size, center, center), [0, 0, 0, 255], "at a zoom of {zoom}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn medians_read_within_an_images_rectangle() {
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::list::{Item, List};
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
// An opaque white image a pixel in from the render's corner
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(8.), 0., DVec2::ONE);
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(8, 8, core_types::Color::WHITE))).with_attribute(ATTR_TRANSFORM, placement);
|
||||
stamp_effect(&mut item, Effect::new(&EffectOperation::Median { radius: 2. }));
|
||||
let list = List::new_from_item(item);
|
||||
|
||||
let size = UVec2::splat(10);
|
||||
let Some(pixels) = render(size, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Its corners keep their pixels, read as if the image were all there is, and nothing spreads past it
|
||||
assert_eq!(pixel(&pixels, size, 1, 1), [255; 4]);
|
||||
assert_eq!(pixel(&pixels, size, 8, 8), [255; 4]);
|
||||
assert_eq!(pixel(&pixels, size, 0, 0)[3], 0);
|
||||
assert_eq!(pixel(&pixels, size, 9, 4)[3], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_median_baked_for_pixel_readers_matches_its_gpu_render() {
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::list::{Item, List};
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::{CPU, Image, Raster};
|
||||
use graphic_types::{Effect, EffectOperation, stamp_effect};
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
// Random colors with a fully transparent band, a pixel in from the render's corner, on the content's own grid and on one coarsened past its largest radius
|
||||
let (width, height) = (40, 30);
|
||||
let data = (0..width * height)
|
||||
.map(|index| {
|
||||
let random = |seed: u32| ((index as u32).wrapping_mul(2_654_435_761).wrapping_add(seed.wrapping_mul(40_503)) >> 24) as f32 / 255.;
|
||||
let alpha = if (12..16).contains(&(index % width)) { 0. } else { 1. };
|
||||
core_types::Color::from_gamma_srgb_channels(random(1), random(2), random(3), alpha)
|
||||
})
|
||||
.collect();
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(width as f64, height as f64), 0., DVec2::ONE);
|
||||
let image = Item::new_from_element(Raster::new_cpu(Image {
|
||||
width: width as u32,
|
||||
height: height as u32,
|
||||
data,
|
||||
}))
|
||||
.with_attribute(ATTR_TRANSFORM, placement);
|
||||
|
||||
let size = UVec2::new(width as u32 + 2, height as u32 + 2);
|
||||
let draw = |item: Item<Raster<CPU>>| {
|
||||
let list = List::new_from_item(item);
|
||||
render(size, |scene| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||||
};
|
||||
for radius in [2., 20.] {
|
||||
let mut item = image.clone();
|
||||
stamp_effect(&mut item, Effect::new(&EffectOperation::Median { radius }));
|
||||
|
||||
// A reader bakes the effect into the image's pixels, which must draw as the GPU draws the effect
|
||||
let baked = raster_kernels::evaluate_raster_effects(item.clone());
|
||||
let (Some(gpu), Some(baked)) = (draw(item), draw(baked)) else { return };
|
||||
// Compared premultiplied, since the straight colors of nearly transparent pixels read back in steps as coarse as their alpha, within the rounding of half floats and 8 bits
|
||||
let premultiplied = |[red, green, blue, alpha]: [u8; 4]| [red, green, blue].map(|channel| channel as f32 * alpha as f32 / 255.).into_iter().chain([alpha as f32]);
|
||||
let stray = (gpu.iter().zip(&baked))
|
||||
.flat_map(|(gpu, baked)| premultiplied(*gpu).zip(premultiplied(*baked)).map(|(gpu, baked)| (gpu - baked).abs()))
|
||||
.fold(0_f32, f32::max);
|
||||
assert!(stray <= 3., "a median of radius {radius} baked strays from its GPU render by {stray} levels");
|
||||
assert_ne!(baked, draw(image.clone()).unwrap_or_default(), "the median changes the pixels");
|
||||
}
|
||||
}
|
||||
|
||||
/// Colors across the RGB cube, among them black, white, grays, and saturated and near-black colors, each opaque, with some also translucent or fully transparent.
|
||||
fn adjustment_test_colors() -> Vec<core_types::Color> {
|
||||
const LEVELS: [f32; 12] = [0., 1. / 255., 4. / 255., 0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95, 254. / 255., 1.];
|
||||
@@ -5279,9 +5464,20 @@ fn gpu_color_adjustments_match_the_cpu_kernels() {
|
||||
("Photo Filter", photo_filter(warming, 25., true)),
|
||||
("Photo Filter at full density", photo_filter(cooling, 100., false)),
|
||||
("Photo Filter at full density preserving luminosity", photo_filter(cooling, 100., true)),
|
||||
("Alpha to Gray", Adjustment::AlphaToGray),
|
||||
];
|
||||
let mut runs: Vec<(String, Vec<Adjustment>)> = runs.into_iter().map(|(name, adjustment)| (name.to_string(), vec![adjustment])).collect();
|
||||
|
||||
// The opaque grays of one channel each that 'Into Channels' outputs
|
||||
let opaque = Adjustment::MakeOpaque { strength: 100. };
|
||||
let green_gray = Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||
monochrome: true,
|
||||
monochrome_mix: row(0., 100., 0., 0.),
|
||||
..Default::default()
|
||||
}));
|
||||
runs.push(("Green as an opaque gray".to_string(), vec![green_gray, opaque.clone()]));
|
||||
runs.push(("Alpha as an opaque gray".to_string(), vec![Adjustment::AlphaToGray, opaque]));
|
||||
|
||||
// Every blend mode, overlaying an opaque color and a translucent one, each with a luma apart from every test color's, which Darker Color and Lighter Color compare, and off Hard Mix's steep ramp over them
|
||||
for blend_mode in BlendMode::list().into_iter().flatten().chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha]) {
|
||||
for (color, opacity) in [
|
||||
|
||||
@@ -53,5 +53,10 @@ tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Local dependencies
|
||||
rendering = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
tokio = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
@@ -15,7 +15,7 @@ pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute};
|
||||
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
||||
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||
use raster_kernels::{evaluate_color_parameter, evaluate_gradient_effects};
|
||||
use raster_types::{CPU, GPU, Image, Raster};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Stamps the adjustment onto the item's effects, to be carried out wherever its content is rendered or read.
|
||||
@@ -50,42 +50,6 @@ fn gamma_correction<T>(
|
||||
)
|
||||
}
|
||||
|
||||
/// The red, green, blue, and alpha channels of an image, split into separate node outputs.
|
||||
#[derive(Debug, Clone, dyn_any::DynAny, node_macro::Destructure)]
|
||||
pub struct ImageChannels {
|
||||
/// The red channel of the image, as a grayscale image.
|
||||
pub red: Item<Raster<CPU>>,
|
||||
/// The green channel of the image, as a grayscale image.
|
||||
pub green: Item<Raster<CPU>>,
|
||||
/// The blue channel of the image, as a grayscale image.
|
||||
pub blue: Item<Raster<CPU>>,
|
||||
/// The alpha channel of the image, as a grayscale image.
|
||||
pub alpha: Item<Raster<CPU>>,
|
||||
}
|
||||
|
||||
/// 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) = 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
|
||||
let mut channels: [Vec<Color>; 4] = core::array::from_fn(|_| Vec::with_capacity(image.data.len()));
|
||||
for color in &image.data {
|
||||
for (channel, value) in channels.iter_mut().zip([color.r(), color.g(), color.b(), color.a()]) {
|
||||
channel.push(Color::from_rgbaf32_unchecked(value, value, value, 1.));
|
||||
}
|
||||
}
|
||||
|
||||
// Each channel image keeps the source image's attributes, such as its transform
|
||||
let [red, green, blue, alpha] = channels.map(|data| {
|
||||
let channel_image = Image { width, height, data };
|
||||
Item::from_parts(Raster::new_cpu(channel_image), attributes.clone())
|
||||
});
|
||||
|
||||
ImageChannels { red, green, blue, alpha }
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"), version(2))]
|
||||
fn make_opaque<T>(
|
||||
_: impl Ctx,
|
||||
@@ -1461,6 +1425,7 @@ mod _graphene_hash_impls {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use raster_kernels::evaluate_color_effects;
|
||||
use raster_types::Image;
|
||||
|
||||
/// Matched to within one 8-bit level.
|
||||
fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::{ATTR_EFFECTS, Item, ItemAttributeValues, List};
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL};
|
||||
use glam::DAffine2;
|
||||
use graphic_types::adjustment::{Adjustment, ChannelMixerRow, ChannelMixerSettings};
|
||||
use graphic_types::{Effect, EffectOperation, Effects, Graphic, MaskMode, linked_to_content, stamp_effect_on};
|
||||
|
||||
/// The red, green, blue, and alpha channels of a graphic, split into separate node outputs.
|
||||
#[derive(Debug, Clone, dyn_any::DynAny, node_macro::Destructure)]
|
||||
pub struct Channels {
|
||||
/// The red channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||
pub red: Item<Graphic>,
|
||||
/// The green channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||
pub green: Item<Graphic>,
|
||||
/// The blue channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||
pub blue: Item<Graphic>,
|
||||
/// The alpha channel of the graphic as an opaque grayscale graphic, from black where the graphic is transparent to white where it's opaque.
|
||||
pub alpha: Item<Graphic>,
|
||||
}
|
||||
|
||||
/// Separates the input graphic into its red, green, blue, and alpha channels, each as a grayscale graphic.
|
||||
///
|
||||
/// The color channels keep the graphic's transparency, while the alpha channel is opaque, so it masks by its luminance as the alpha did.
|
||||
#[node_macro::node(category("Raster"), icon("NodeImageToChannels"), version(2))]
|
||||
fn into_channels(_: impl Ctx, content: Item<Graphic>) -> Channels {
|
||||
// Each output is the content with adjustments graying it by one channel, carried out wherever it's rendered or read
|
||||
let channel = |grays: &[Adjustment]| {
|
||||
let mut channel = content.clone();
|
||||
with_effects_holder(&mut channel, |attributes| grays.iter().for_each(|gray| stamp_adjustment(attributes, gray.clone())));
|
||||
channel
|
||||
};
|
||||
|
||||
Channels {
|
||||
red: channel(&[channel_gray([100., 0., 0.])]),
|
||||
green: channel(&[channel_gray([0., 100., 0.])]),
|
||||
blue: channel(&[channel_gray([0., 0., 100.])]),
|
||||
alpha: channel(&[Adjustment::AlphaToGray, Adjustment::MakeOpaque { strength: 100. }]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Combines graphics into the red, green, blue, and alpha channels of one graphic. Each color channel comes from the same channel of its input, and the alpha from the alpha input's red channel, so grayscale graphics like those from 'Into Channels' recombine exactly.
|
||||
///
|
||||
/// The inputs line up where they lie in the document, and the result covers them all, transparent where none lies. Unconnected color channels are black, and an unconnected alpha leaves the result opaque.
|
||||
#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), version(2))]
|
||||
fn from_channels(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
/// The graphic whose red channel becomes the red channel.
|
||||
#[expose]
|
||||
red: Item<Graphic>,
|
||||
/// The graphic whose green channel becomes the green channel.
|
||||
#[expose]
|
||||
green: Item<Graphic>,
|
||||
/// The graphic whose blue channel becomes the blue channel.
|
||||
#[expose]
|
||||
blue: Item<Graphic>,
|
||||
/// The graphic whose red channel becomes the alpha, from transparent where it's black to opaque where it's white. Past its edges, the result is transparent.
|
||||
#[expose]
|
||||
alpha: Item<Graphic>,
|
||||
) -> Item<Graphic> {
|
||||
// An unconnected channel arrives as a graphic drawing nothing, which counts as absent
|
||||
let present = |channel: Item<Graphic>| (!channel.element().draws_nothing()).then_some(channel);
|
||||
let [red, green, blue, alpha] = [red, green, blue, alpha].map(present);
|
||||
|
||||
// Each input made opaque, keeping only its own color channel, or none for the alpha, which also masks the group by a gray of its red channel
|
||||
let opaque = |channel: Item<Graphic>, keep: Adjustment| {
|
||||
let mut channel = without_compositing(channel);
|
||||
with_effects_holder(&mut channel, |attributes| {
|
||||
stamp_adjustment(attributes, Adjustment::MakeOpaque { strength: 100. });
|
||||
stamp_adjustment(attributes, keep);
|
||||
});
|
||||
channel
|
||||
};
|
||||
let mask = alpha.clone().map(|alpha| opaque(alpha, channel_gray([100., 0., 0.])));
|
||||
let kept = [Some(0), Some(1), Some(2), None].map(kept_channel);
|
||||
let channels = [red, green, blue, alpha].into_iter().zip(kept).filter_map(|(channel, keep)| Some(opaque(channel?, keep)));
|
||||
|
||||
// Each channel adds onto those before it, holding none of their channels, so the group covers every input
|
||||
let mut group = List::default();
|
||||
for (index, mut channel) in channels.enumerate() {
|
||||
if index > 0 {
|
||||
channel.set_attribute(ATTR_BLEND_MODE, BlendMode::LinearDodge);
|
||||
}
|
||||
group.push(channel);
|
||||
}
|
||||
if group.is_empty() {
|
||||
return Item::default();
|
||||
}
|
||||
let mut result = Item::new_from_element(Graphic::GraphicList(group));
|
||||
|
||||
// The alpha's gray shows the group by its luminance, which for a gray is its level, or else the group is made opaque.
|
||||
// Either effect also renders the group apart from what lies beneath, so its channels add only onto each other.
|
||||
let effect = match mask {
|
||||
Some(mask) => EffectOperation::Mask {
|
||||
mask: linked_to_content(Graphic::Graphic(Box::new(mask)), DAffine2::IDENTITY),
|
||||
mode: MaskMode::Luminance,
|
||||
density: 100.,
|
||||
feather: 0.,
|
||||
invert: false,
|
||||
},
|
||||
None => EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. }),
|
||||
};
|
||||
stamp_effect_on(result.attributes_mut(), Effect::new(&effect));
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// The graphic without the opacity, fill, blend mode, and clipping a channel takes no part in, on its envelope and the one item it may hold.
|
||||
fn without_compositing(mut graphic: Item<Graphic>) -> Item<Graphic> {
|
||||
let strip = |attributes: &mut ItemAttributeValues| {
|
||||
attributes.remove::<f64>(ATTR_OPACITY);
|
||||
attributes.remove::<f64>(ATTR_OPACITY_FILL);
|
||||
attributes.remove::<BlendMode>(ATTR_BLEND_MODE);
|
||||
attributes.remove::<bool>(ATTR_CLIPPING_MASK);
|
||||
};
|
||||
strip(graphic.attributes_mut());
|
||||
if let Some(attributes) = lone_item_attributes(graphic.element_mut()) {
|
||||
strip(attributes);
|
||||
}
|
||||
graphic
|
||||
}
|
||||
|
||||
/// A Channel Mixer keeping only the red, green, or blue channel by its `index`, or none for black.
|
||||
fn kept_channel(index: Option<usize>) -> Adjustment {
|
||||
let row = |row_index: usize| {
|
||||
let weight = |channel: usize| if index == Some(row_index) && channel == row_index { 100. } else { 0. };
|
||||
ChannelMixerRow {
|
||||
red: weight(0),
|
||||
green: weight(1),
|
||||
blue: weight(2),
|
||||
constant: 0.,
|
||||
}
|
||||
};
|
||||
|
||||
Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||
monochrome: false,
|
||||
monochrome_mix: ChannelMixerRow {
|
||||
red: 40.,
|
||||
green: 40.,
|
||||
blue: 20.,
|
||||
constant: 0.,
|
||||
},
|
||||
red: row(0),
|
||||
green: row(1),
|
||||
blue: row(2),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Gives `edit` the attributes of the item a graphic's effects go on.
|
||||
/// That's the one item the graphic holds, which keeps the handling of its own kind (an image's adjustments reach even its fully transparent pixels) and stays an image for 'Flatten Raster' to take out,
|
||||
/// unless the graphic's own effects or fill, which act before effects appended to the graphic, would then act after them.
|
||||
fn with_effects_holder<R>(graphic: &mut Item<Graphic>, edit: impl FnOnce(&mut ItemAttributeValues) -> R) -> R {
|
||||
let envelope_has_effects = graphic.attribute::<Effects>(ATTR_EFFECTS).is_some_and(|effects| !effects.is_empty());
|
||||
let envelope_acts_first = envelope_has_effects || graphic.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) != 1.;
|
||||
|
||||
if !envelope_acts_first && let Some(attributes) = lone_item_attributes(graphic.element_mut()) {
|
||||
return edit(attributes);
|
||||
}
|
||||
edit(graphic.attributes_mut())
|
||||
}
|
||||
|
||||
/// The attributes of the one item a graphic holds, or `None` if it holds a list.
|
||||
fn lone_item_attributes(graphic: &mut Graphic) -> Option<&mut ItemAttributeValues> {
|
||||
Some(match graphic {
|
||||
Graphic::Graphic(item) => item.attributes_mut(),
|
||||
Graphic::Vector(item) => item.attributes_mut(),
|
||||
Graphic::RasterCPU(item) => item.attributes_mut(),
|
||||
Graphic::RasterGPU(item) => item.attributes_mut(),
|
||||
Graphic::Color(item) => item.attributes_mut(),
|
||||
Graphic::Gradient(item) => item.attributes_mut(),
|
||||
Graphic::Generator(item) => item.attributes_mut(),
|
||||
Graphic::Text(item) => item.attributes_mut(),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Stamps the adjustment onto the effects in these attributes.
|
||||
fn stamp_adjustment(attributes: &mut ItemAttributeValues, adjustment: Adjustment) {
|
||||
stamp_effect_on(attributes, Effect::new(&EffectOperation::Adjustment(adjustment)));
|
||||
}
|
||||
|
||||
/// A monochrome Channel Mixer graying each color by its red, green, and blue channels weighted by the `weights` in percent.
|
||||
fn channel_gray(weights: [f64; 3]) -> Adjustment {
|
||||
let row = |[red, green, blue]: [f64; 3]| ChannelMixerRow { red, green, blue, constant: 0. };
|
||||
|
||||
// The rows a monochrome mixer ignores keep the node's defaults, so they stamp nothing
|
||||
Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||
monochrome: true,
|
||||
monochrome_mix: row(weights),
|
||||
red: row([100., 0., 0.]),
|
||||
green: row([0., 100., 0.]),
|
||||
blue: row([0., 0., 100.]),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::color::Color;
|
||||
use glam::{DVec2, UVec2};
|
||||
use raster_types::{CPU, Image, Raster};
|
||||
|
||||
/// An image of `pixels` in one row, one pixel per document unit, embedded in a graphic as a wire of images embeds it.
|
||||
fn image(pixels: &[Color]) -> Item<Graphic> {
|
||||
let image = Image {
|
||||
width: pixels.len() as u32,
|
||||
height: 1,
|
||||
data: pixels.to_vec(),
|
||||
};
|
||||
let raster = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(pixels.len() as f64, 1.)));
|
||||
Item::new_from_element(Graphic::from(raster))
|
||||
}
|
||||
|
||||
/// The image a graphic holds alone.
|
||||
fn lone_image(graphic: &Item<Graphic>) -> &Item<Raster<CPU>> {
|
||||
let Graphic::RasterCPU(raster) = graphic.element() else { panic!("expected a lone image") };
|
||||
raster
|
||||
}
|
||||
|
||||
/// The graphic's rendered pixels as straight-alpha RGBA8, one pixel per document unit from its origin across a `size` view, or `None` without a GPU.
|
||||
fn rendered(graphic: &Item<Graphic>, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?;
|
||||
let list = core_types::list::List::new_from_item(graphic.clone());
|
||||
let draw = &mut |scene: &mut rendering::vello_scene_builder::VelloSceneBuilder| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
||||
let texture = executor.render_vello(size, DAffine2::IDENTITY, draw).expect("the graphic should render");
|
||||
let pixels = executor.read_texture_pixels(&texture).expect("the render should read back");
|
||||
Some(pixels.as_chunks::<4>().0.to_vec())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_grays_each_color_keeping_its_alpha_and_makes_the_alpha_opaque() {
|
||||
use raster_kernels::adjustments::adjust_color;
|
||||
|
||||
// A translucent pixel and a fully transparent one, whose hidden color its channels still gray
|
||||
let pixels = [Color::from_rgbaf32_unchecked(0.75, 0.1, 0.3, 0.6), Color::from_rgbaf32_unchecked(0.25, 0.5, 1., 0.)];
|
||||
let Channels { red, green, blue, alpha } = into_channels((), image(&pixels));
|
||||
|
||||
// Each output is the image itself, still an image, with adjustments graying each pixel to one channel's gamma-encoded level, or the alpha's
|
||||
for (channel, output) in [red, green, blue, alpha].into_iter().enumerate() {
|
||||
assert_eq!(output.attributes().iter_any().count(), 0, "the envelope stays empty");
|
||||
let raster = lone_image(&output);
|
||||
assert_eq!(raster.element().data, pixels, "the pixels are left alone");
|
||||
let effects = raster.attribute::<Effects>(ATTR_EFFECTS).cloned().unwrap_or_default();
|
||||
|
||||
for pixel in pixels {
|
||||
let gray = effects.operations().fold(pixel, |color, operation| match operation {
|
||||
EffectOperation::Adjustment(adjustment) => adjust_color(&adjustment, color),
|
||||
operation => panic!("{operation:?} isn't an adjustment"),
|
||||
});
|
||||
|
||||
// The colors keep the pixel's alpha, and the alpha is opaque
|
||||
let (level, kept_alpha) = match channel {
|
||||
3 => (pixel.a(), 1.),
|
||||
_ => (pixel.to_gamma_srgb_channels()[channel], pixel.a()),
|
||||
};
|
||||
let [r, g, b, a] = gray.to_gamma_srgb_channels();
|
||||
assert!(
|
||||
[r, g, b].iter().all(|gray| (gray - level).abs() < 1e-5) && (a - kept_alpha).abs() < 1e-6,
|
||||
"channel {channel} of {pixel:?} grays to {gray:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_color_outputs_keep_the_sources_transparency() {
|
||||
// Half transparent white, then fully transparent red, then opaque white
|
||||
let Channels { red, .. } = into_channels((), image(&[Color::WHITE.with_alpha(0.5), Color::from_rgbaf32_unchecked(1., 0., 0., 0.), Color::WHITE]));
|
||||
|
||||
let Some(pixels) = rendered(&red, UVec2::new(3, 1)) else { return };
|
||||
assert!(pixels[0][..3] == [255; 3] && pixels[0][3].abs_diff(128) <= 1, "{:?}", pixels[0]);
|
||||
assert_eq!(pixels[1][3], 0, "the transparent pixel stays transparent");
|
||||
assert_eq!(pixels[2], [255; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_adjusts_a_graphic_by_its_envelope_where_its_fill_acts_first() {
|
||||
use graphic_types::EffectKind::{AlphaToGray, MakeOpaque};
|
||||
|
||||
let kinds = |effects: Option<&Effects>| effects.map_or(Vec::new(), |effects| effects.effects().map(|effect| effect.kind()).collect::<Vec<_>>());
|
||||
|
||||
// A placement alone leaves the image within to take the effects, so a placement left at its default acts as no placement
|
||||
let placed = image(&[Color::WHITE]).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(3., 0.)));
|
||||
let Channels { alpha, .. } = into_channels((), placed);
|
||||
assert_eq!(kinds(lone_image(&alpha).attribute(ATTR_EFFECTS)), [AlphaToGray, MakeOpaque]);
|
||||
|
||||
// The envelope's fill fades the image before the effects appended to the graphic, so they go on the envelope
|
||||
let faded = image(&[Color::WHITE]).with_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||
let Channels { alpha, .. } = into_channels((), faded);
|
||||
assert_eq!(kinds(alpha.attribute(ATTR_EFFECTS)), [AlphaToGray, MakeOpaque]);
|
||||
assert!(lone_image(&alpha).attribute::<Effects>(ATTR_EFFECTS).is_none(), "the image within is left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_renders_an_images_alpha_opaque_across_its_rectangle() {
|
||||
// A half transparent pixel, which shows middle gray, then a fully transparent one, which shows black rather than nothing
|
||||
let Channels { alpha, .. } = into_channels((), image(&[Color::WHITE.with_alpha(0.5), Color::TRANSPARENT]));
|
||||
|
||||
let Some(pixels) = rendered(&alpha, UVec2::new(3, 1)) else { return };
|
||||
assert!(pixels[0][..3].iter().all(|level| level.abs_diff(128) <= 1) && pixels[0][3] == 255, "{:?}", pixels[0]);
|
||||
assert_eq!(pixels[1], [0, 0, 0, 255]);
|
||||
assert_eq!(pixels[2][3], 0, "past the image");
|
||||
}
|
||||
|
||||
/// A square image of `size` pixels filled with one straight color, placed at `x` with one pixel per document unit, embedded in a graphic as a wire of images embeds it.
|
||||
fn filled(size: u32, color: Color, x: f64) -> Item<Graphic> {
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(size as f64), 0., DVec2::new(x, 0.));
|
||||
Item::new_from_element(Graphic::from(
|
||||
Item::new_from_element(Raster::new_cpu(Image::new(size, size, color))).with_attribute(ATTR_TRANSFORM, placement),
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_channels_groups_each_input_keeping_only_its_own_channel() {
|
||||
use core_types::ATTR_OPACITY;
|
||||
use graphic_types::EffectKind::{ChannelMixer, MakeOpaque, Mask};
|
||||
|
||||
let gray = |value: f32| filled(2, Color::from_rgbaf32_unchecked(value, value, value, 1.), 0.);
|
||||
let kinds = |effects: Option<&Effects>| effects.map_or(Vec::new(), |effects| effects.effects().map(|effect| effect.kind()).collect::<Vec<_>>());
|
||||
let members = |graphic: &Item<Graphic>| match graphic.element() {
|
||||
Graphic::GraphicList(group) => group.clone(),
|
||||
element => panic!("expected a group, found {element:?}"),
|
||||
};
|
||||
|
||||
// Each input in turn, made opaque with only its own channel, its opacity left out, and those after the first added on, all masked by the alpha
|
||||
let mut red = gray(0.25);
|
||||
red.set_attribute(ATTR_OPACITY, 0.5);
|
||||
let result = from_channels((), (), red, gray(0.5), gray(0.75), gray(1.));
|
||||
let group = members(&result);
|
||||
assert_eq!(group.len(), 4);
|
||||
for (index, member) in (0..group.len()).filter_map(|index| group.clone_item(index)).enumerate() {
|
||||
let blend_mode = member.attribute_cloned_or_default::<BlendMode>(ATTR_BLEND_MODE);
|
||||
assert_eq!(blend_mode, if index == 0 { BlendMode::Normal } else { BlendMode::LinearDodge });
|
||||
assert_eq!(member.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 1.);
|
||||
let Graphic::RasterCPU(raster) = member.element() else { panic!("expected an image") };
|
||||
assert_eq!(kinds(raster.attribute(ATTR_EFFECTS)), [MakeOpaque, ChannelMixer]);
|
||||
}
|
||||
assert_eq!(kinds(result.attribute(ATTR_EFFECTS)), [Mask]);
|
||||
|
||||
// Without the alpha, the group is made opaque, and the alpha alone gives black it masks
|
||||
let opaque = from_channels((), (), gray(0.25), Item::default(), Item::default(), Item::default());
|
||||
assert_eq!((members(&opaque).len(), kinds(opaque.attribute(ATTR_EFFECTS))), (1, vec![MakeOpaque]));
|
||||
let alpha = from_channels((), (), Item::default(), Item::default(), Item::default(), gray(0.5));
|
||||
assert_eq!((members(&alpha).len(), kinds(alpha.attribute(ATTR_EFFECTS))), (1, vec![Mask]));
|
||||
assert!(from_channels((), (), Item::default(), Item::default(), Item::default(), Item::default()).element().draws_nothing());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_and_back_from_channels_reproduces_the_image_with_its_partial_alpha() {
|
||||
// Colors across each channel, with every third pixel half transparent
|
||||
let data = (0..64)
|
||||
.map(|index| {
|
||||
let (x, y) = ((index % 8) as f32, (index / 8) as f32);
|
||||
let alpha = if index % 3 == 0 { 0.5 } else { 1. };
|
||||
Color::from_gamma_srgb_channels(x / 7., y / 7., (x + y) / 14., alpha)
|
||||
})
|
||||
.collect();
|
||||
let raster = Item::new_from_element(Raster::new_cpu(Image { width: 8, height: 8, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.)));
|
||||
let image = Item::new_from_element(Graphic::from(raster));
|
||||
|
||||
let Channels { red, green, blue, alpha } = into_channels((), image.clone());
|
||||
let recombined = from_channels((), (), red, green, blue, alpha);
|
||||
|
||||
let size = UVec2::splat(8);
|
||||
let (Some(original), Some(recombined)) = (rendered(&image, size), rendered(&recombined, size)) else {
|
||||
return;
|
||||
};
|
||||
for (index, (original, recombined)) in original.iter().zip(&recombined).enumerate() {
|
||||
let stray = original.iter().zip(recombined).map(|(original, recombined)| original.abs_diff(*recombined)).max().unwrap_or_default();
|
||||
assert!(stray <= 2, "pixel {index} renders as {recombined:?} rather than {original:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_channels_lines_up_its_inputs_where_they_lie_in_the_document() {
|
||||
// Red and green overlap by half, and a half gray alpha starts a pixel in from the red
|
||||
let half_gray = Color::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.);
|
||||
let result = from_channels((), (), filled(4, Color::WHITE, 0.), filled(4, Color::WHITE, 2.), Item::default(), filled(4, half_gray, 1.));
|
||||
|
||||
let size = UVec2::new(8, 4);
|
||||
let Some(pixels) = rendered(&result, size) else { return };
|
||||
let at = |x: u32| pixels[(size.x + x) as usize];
|
||||
let half_shown = |[red, green, blue, alpha]: [u8; 4], expected: [u8; 3]| [red, green, blue] == expected && alpha.abs_diff(128) <= 1;
|
||||
assert_eq!(at(0)[3], 0, "outside the alpha");
|
||||
assert!(half_shown(at(1), [255, 0, 0]), "red alone, half shown: {:?}", at(1));
|
||||
assert!(half_shown(at(3), [255, 255, 0]), "red and green: {:?}", at(3));
|
||||
assert_eq!(at(5)[3], 0, "outside the alpha");
|
||||
}
|
||||
|
||||
/// Red over the left four of a 12 by 4 render and green over the right four, past the red's rectangle, without an alpha.
|
||||
fn red_and_green_apart() -> Item<Graphic> {
|
||||
from_channels((), (), filled(4, Color::WHITE, 0.), filled(4, Color::WHITE, 8.), Item::default(), Item::default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_channels_covers_a_green_input_shifted_past_the_red() {
|
||||
// Over a gray beneath, which the channels don't add onto
|
||||
let beneath = filled(12, Color::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.), 0.);
|
||||
let group: List<Graphic> = [beneath, red_and_green_apart()].into_iter().collect();
|
||||
|
||||
let size = UVec2::new(12, 4);
|
||||
let Some(pixels) = rendered(&Item::new_from_element(Graphic::GraphicList(group)), size) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(pixels[(size.x + 1) as usize], [255, 0, 0, 255]);
|
||||
assert_eq!(pixels[(size.x + 10) as usize], [0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_channels_leaves_what_no_input_covers_transparent() {
|
||||
let size = UVec2::new(12, 4);
|
||||
let Some(pixels) = rendered(&red_and_green_apart(), size) else { return };
|
||||
assert_eq!(pixels[(size.x + 1) as usize], [255, 0, 0, 255]);
|
||||
assert_eq!(pixels[(size.x + 6) as usize][3], 0, "between the inputs");
|
||||
}
|
||||
}
|
||||
@@ -1,95 +1,27 @@
|
||||
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::{CPU, Raster};
|
||||
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Applies a median filter to reduce noise while preserving edges.
|
||||
#[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"), memoize)]
|
||||
fn median_filter(
|
||||
/// Applies a median filter to reduce noise while preserving edges, giving each pixel the middle value of each channel among the pixels in a square around it.
|
||||
///
|
||||
/// It works on an image's own pixels, or the document's pixels for other graphics, so it looks the same at any zoom.
|
||||
#[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"), version(2))]
|
||||
fn median_filter<T>(
|
||||
_: impl Ctx,
|
||||
/// The image to be filtered.
|
||||
image_frame: Item<Raster<CPU>>,
|
||||
/// The radius of the filter kernel. Larger values remove more noise but may blur fine details.
|
||||
/// The content to be filtered.
|
||||
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
|
||||
content: Item<T>,
|
||||
/// How far the square around each pixel reaches, in whole pixels. Larger values remove more noise but may blur fine details.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..50)]
|
||||
radius: Item<f64>,
|
||||
) -> Item<Raster<CPU>> {
|
||||
let radius = *radius.element();
|
||||
|
||||
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
|
||||
let filtered_image = if radius < 0.5 {
|
||||
// Minimum filter radius
|
||||
image
|
||||
} else {
|
||||
Raster::new_cpu(median_filter_algorithm(image.into_data(), radius as u32))
|
||||
};
|
||||
|
||||
Item::from_parts(filtered_image, attributes)
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
let window_span = |extent: u32| (radius as usize).saturating_mul(2).saturating_add(1).min(extent as usize);
|
||||
let window_capacity = window_span(width) * window_span(height);
|
||||
|
||||
fill_rows(&mut output.data, width as usize, |y, row| {
|
||||
let y = y as u32;
|
||||
|
||||
// Allocated once for the row and reused for each of its pixels
|
||||
let mut r_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut g_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut b_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
let mut a_vals: Vec<f32> = Vec::with_capacity(window_capacity);
|
||||
|
||||
for (x, output_pixel) in row.iter_mut().enumerate() {
|
||||
let x = x as u32;
|
||||
r_vals.clear();
|
||||
g_vals.clear();
|
||||
b_vals.clear();
|
||||
a_vals.clear();
|
||||
|
||||
// Use saturating_add to avoid potential overflow in extreme cases
|
||||
let y_max = y.saturating_add(radius).min(height - 1);
|
||||
let x_max = x.saturating_add(radius).min(width - 1);
|
||||
|
||||
for ny in y.saturating_sub(radius)..=y_max {
|
||||
for nx in x.saturating_sub(radius)..=x_max {
|
||||
if let Some(px) = original_buffer.get_pixel(nx, ny) {
|
||||
r_vals.push(px.r());
|
||||
g_vals.push(px.g());
|
||||
b_vals.push(px.b());
|
||||
a_vals.push(px.a());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let r = median_quickselect(&mut r_vals);
|
||||
let g = median_quickselect(&mut g_vals);
|
||||
let b = median_quickselect(&mut b_vals);
|
||||
let a = median_quickselect(&mut a_vals);
|
||||
|
||||
*output_pixel = Color::from_rgbaf32_unchecked(r, g, b, a);
|
||||
}
|
||||
});
|
||||
|
||||
output
|
||||
}
|
||||
/// Finds the median of a slice using quickselect for O(n) average case performance.
|
||||
/// This is more efficient than sorting the entire slice which would be O(n log n).
|
||||
fn median_quickselect(values: &mut [f32]) -> f32 {
|
||||
let mid: usize = values.len() / 2;
|
||||
// nth_unstable is like quickselect: average O(n)
|
||||
// Use total_cmp for safe NaN handling instead of partial_cmp().unwrap()
|
||||
*values.select_nth_unstable_by(mid, |a, b| a.total_cmp(b)).1
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(&mut content, Effect::new(&EffectOperation::Median { radius: *radius.element() }));
|
||||
content
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod adjustments;
|
||||
pub mod blending_nodes;
|
||||
pub mod channels;
|
||||
pub use raster_kernels::color_lookup_table;
|
||||
pub mod dehaze;
|
||||
pub mod filter;
|
||||
|
||||
@@ -1,17 +1,10 @@
|
||||
use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::color::Color;
|
||||
use core_types::color::{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 glam::DVec2;
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::generator::{Generator, MandelbrotSettings, NoiseSettings};
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
use raster_types::{Bitmap, BitmapMut};
|
||||
use raster_types::{CPU, Raster};
|
||||
use raster_types::{Image, ImageError};
|
||||
use std::fmt::Debug;
|
||||
@@ -29,156 +22,6 @@ impl From<std::io::Error> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two rasters that must line up pixel for pixel but differ in size.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("{first} and {second} must be the same size, but {first} is {}×{} pixels and {second} is {}×{}", .first_size.x, .first_size.y, .second_size.x, .second_size.y)]
|
||||
pub struct SizeMismatchError {
|
||||
pub first: &'static str,
|
||||
pub first_size: UVec2,
|
||||
pub second: &'static str,
|
||||
pub second_size: UVec2,
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), name("Channels to Image"), memoize)]
|
||||
fn channels_to_image(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[expose] red: Item<Raster<CPU>>,
|
||||
#[expose] green: Item<Raster<CPU>>,
|
||||
#[expose] blue: Item<Raster<CPU>>,
|
||||
#[expose] alpha: Item<Raster<CPU>>,
|
||||
) -> 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 channels = [red, green, blue, alpha].map(present);
|
||||
|
||||
// All present channels must share the same dimensions
|
||||
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());
|
||||
};
|
||||
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: 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 [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();
|
||||
|
||||
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.));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Item::from_parts(Raster::new_cpu(image), attributes))
|
||||
}
|
||||
|
||||
#[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);
|
||||
let image_aabb = Bbox::unit().affine_transform(image_transform).to_axis_aligned_bbox();
|
||||
let bounds_aabb = Bbox::unit().affine_transform(bounds.transform()).to_axis_aligned_bbox();
|
||||
if image_aabb.contains(bounds_aabb.start) && image_aabb.contains(bounds_aabb.end) {
|
||||
return Ok(image);
|
||||
}
|
||||
|
||||
let (image_width, image_height) = (image.element().width, image.element().height);
|
||||
if image_width == 0 || image_height == 0 {
|
||||
return empty_image(bounds, Color::TRANSPARENT).map_err(|error| (image, error));
|
||||
}
|
||||
if image_transform.matrix2.determinant() == 0. {
|
||||
return Ok(image);
|
||||
}
|
||||
|
||||
let orig_image_scale = DVec2::new(image_width as f64, image_height as f64);
|
||||
let layer_to_image_space = DAffine2::from_scale(orig_image_scale) * image_transform.inverse();
|
||||
let bounds_in_image_space = Bbox::unit().affine_transform(layer_to_image_space * bounds).to_axis_aligned_bbox();
|
||||
|
||||
let new_start = bounds_in_image_space.start.floor().min(DVec2::ZERO);
|
||||
let new_end = bounds_in_image_space.end.ceil().max(orig_image_scale);
|
||||
let new_scale = new_end - new_start;
|
||||
|
||||
// Copy over original image into enlarged image.
|
||||
let mut new_image = match Image::try_new(new_scale.x as u32, new_scale.y as u32, Color::TRANSPARENT) {
|
||||
Ok(new_image) => new_image,
|
||||
Err(error) => return Err((image, error)),
|
||||
};
|
||||
let (image, mut attributes) = image.into_parts();
|
||||
let offset_in_new_image = (-new_start).as_uvec2();
|
||||
for y in 0..image_height {
|
||||
let old_start = y * image_width;
|
||||
let new_start = (y + offset_in_new_image.y) * new_image.width + offset_in_new_image.x;
|
||||
let old_row = &image.data[old_start as usize..(old_start + image_width) as usize];
|
||||
let new_row = &mut new_image.data[new_start as usize..(new_start + image_width) as usize];
|
||||
new_row.copy_from_slice(old_row);
|
||||
}
|
||||
|
||||
// Compute new transform.
|
||||
// let layer_to_new_texture_space = (DAffine2::from_scale(1. / new_scale) * DAffine2::from_translation(new_start) * layer_to_image_space).inverse();
|
||||
let new_texture_to_layer_space = image_transform * DAffine2::from_scale(1. / orig_image_scale) * DAffine2::from_translation(new_start) * DAffine2::from_scale(new_scale);
|
||||
|
||||
attributes.insert(ATTR_TRANSFORM, new_texture_to_layer_space);
|
||||
Ok(Item::from_parts(Raster::new_cpu(new_image), attributes))
|
||||
}
|
||||
|
||||
/// Creates an image filled with one color, sized in pixels by the transform's scale and placed by the transform.
|
||||
fn empty_image(transform: DAffine2, color: Color) -> Result<Item<Raster<CPU>>, ImageError> {
|
||||
let width = transform.transform_vector2(DVec2::new(1., 0.)).length() as u32;
|
||||
let height = transform.transform_vector2(DVec2::new(0., 1.)).length() as u32;
|
||||
|
||||
let image = Image::try_new(width, height, color)?;
|
||||
|
||||
Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform))
|
||||
}
|
||||
|
||||
/// Displays an image from a file.
|
||||
///
|
||||
/// Reads PNG, JPG, GIF, WEBP, TIFF, BMP, TGA, ICO, HDR, and EXR files. Light brighter than white, as HDR and EXR files can hold, is clipped to white.
|
||||
@@ -318,40 +161,3 @@ fn mandelbrot(
|
||||
settings.stamp(&mut generator);
|
||||
generator
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn channels_stay_aligned_when_effects_grow_only_one() {
|
||||
use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect};
|
||||
|
||||
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.)))
|
||||
};
|
||||
|
||||
// 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_mask: Graphic::default(),
|
||||
radius: 1.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
}),
|
||||
);
|
||||
let image = channels_to_image((), (), red, gray(0.5), gray(0.25), gray(1.)).unwrap();
|
||||
|
||||
// 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:?}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user