Compare commits

..
26 changed files with 2122 additions and 1409 deletions

No files matched your search

+14
View File
@@ -148,10 +148,24 @@ pub const CURVATURE_COMB_MAX_TEETH_PER_SEGMENT: f64 = 128.;
pub const CURVATURE_COMB_MAX_TOOTH_LENGTH: f64 = 2000.;
// GRADIENT TOOL
pub const GRADIENT_LINE_WIDTH: f64 = 2.;
// Half the height of a midpoint diamond across the gradient line
pub const GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT: f64 = 5.;
// Half the width of a midpoint diamond along the gradient line
pub const GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH: f64 = 3.;
// The radius of the circle approximating a midpoint diamond, which a press is measured against
pub const GRADIENT_MIDPOINT_DIAMOND_RADIUS: f64 = 4.;
// The radius of a color stop dot at its regular size, which a press is measured against
pub const GRADIENT_STOP_RADIUS: f64 = MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1.;
pub const GRADIENT_MIDPOINT_MIN: f64 = 0.01;
pub const GRADIENT_MIDPOINT_MAX: f64 = 0.99;
pub const GRADIENT_STOP_MIN_VIEWPORT_GAP: f64 = 10.;
// In viewport pixels from a contour's dashed rim, within which a press takes hold of it
pub const GRADIENT_CONTOUR_RIM_GRAB_DISTANCE: f64 = 5.;
// In viewport pixels, within which a dragged contour handle snaps onto making its contour a line or a point
pub const GRADIENT_CONTOUR_SNAP_DISTANCE: f64 = 4.;
// In viewport pixels, the shortest an end circle's semi-minor axis lines are drawn, below which they have no aspect handles at their tips
pub const GRADIENT_SEMI_MINOR_AXIS_MIN_LENGTH: f64 = 20.;
// PEN TOOL
pub const CREATE_CURVE_THRESHOLD: f64 = 5.;
@@ -57,6 +57,11 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier,
gradient_form: GradientForm,
},
GradientCurvatureSet {
layer: LayerNodeIdentifier,
/// The start and end curvatures.
curvatures: [f64; 2],
},
GradientSpreadSet {
layer: LayerNodeIdentifier,
gradient_spread: GradientSpread,
@@ -86,6 +86,11 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.gradient_form_set(gradient_form);
}
}
GraphOperationMessage::GradientCurvatureSet { layer, curvatures } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_curvature_set(curvatures);
}
}
GraphOperationMessage::GradientSpreadSet { layer, gradient_spread } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_spread_set(gradient_spread);
@@ -6,7 +6,8 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{
ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, gradient_curvature_values, replaceable_paint_chain,
ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_fill_node_id_with_direct_fill_input, get_upstream_gradient_value_node_id, gradient_chain_target_input,
gradient_curvature_values, replaceable_paint_chain,
};
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::ResourceId;
@@ -492,19 +493,8 @@ impl<'a> ModifyInputsContext<'a> {
}
// Only a chosen form sets the curvatures, leaving any the graph feeds or that already make it
let curvatures = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
if let Some(gradient_form) = gradient_form
&& curvatures.is_some_and(|curvatures| GradientForm::from_curvatures(curvatures) != Some(gradient_form))
{
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let [start_curvature, end_curvature] = gradient_form.curvatures();
self.set_input_with_refresh(
InputConnector::node(fill_node_id, StartCurvatureInput),
NodeInput::value(TaggedValue::Number(start_curvature), false),
true,
);
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end_curvature), false), true);
if let Some(gradient_form) = gradient_form {
self.write_fill_curvatures(fill_node_id, gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form));
}
self.responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -513,6 +503,20 @@ impl<'a> ModifyInputsContext<'a> {
}
}
/// Write both curvatures to a Fill node's hidden curvature inputs unless the graph feeds them or its current ones are `already_written`, for the caller to then run the graph.
fn write_fill_curvatures(&mut self, fill_node_id: NodeId, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) {
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let current = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
if current.is_none_or(already_written) {
return;
}
let [start, end] = curvatures;
self.set_input_with_refresh(InputConnector::node(fill_node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), true);
}
/// A freshly created Fill node lands at the chain start, downstream of any Stroke node, where it would
/// paint over the stroke. This hops the stroke back downstream so it keeps painting above by default.
fn restore_default_stroke_order(&mut self) {
@@ -776,23 +780,42 @@ impl<'a> ModifyInputsContext<'a> {
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
/// from the default (`Linear`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched.
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
self.write_gradient_curvatures(gradient_form.curvatures(), |current| GradientForm::from_curvatures(current) == Some(gradient_form));
}
/// Write both curvatures to the layer's gradient: a Fill node holding it, or else the last 'Gradient Curvature' node in its chain, inserting
/// one only when they differ from the default form's (`Linear`). Curvatures fed from the graph (procedural authorship) are left untouched.
pub fn gradient_curvature_set(&mut self, curvatures: [f64; 2]) {
if let Some(output_layer) = self.get_output_layer()
&& let Some(fill_node_id) = get_fill_node_id_with_direct_fill_input(output_layer, self.network_interface)
{
self.write_fill_curvatures(fill_node_id, curvatures, |current| current == curvatures);
self.responses.add(NodeGraphMessage::RunDocumentGraph);
return;
}
self.write_gradient_curvatures(curvatures, |current| current == curvatures);
}
/// Write these curvatures to the last 'Gradient Curvature' node in the chain unless its current ones are `already_written`.
fn write_gradient_curvatures(&mut self, curvatures: [f64; 2], already_written: impl Fn([f64; 2]) -> bool) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let create_if_nonexistent = gradient_form != GradientForm::default();
let create_if_nonexistent = curvatures != GradientForm::default().curvatures();
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
return;
};
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return };
let Some(curvatures) = gradient_curvature_values(node) else { return };
if GradientForm::from_curvatures(curvatures) == Some(gradient_form) {
let Some(current) = gradient_curvature_values(node) else { return };
if already_written(current) {
return;
}
let [start, end] = gradient_form.curvatures();
let [start, end] = curvatures;
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
}
@@ -1,8 +1,8 @@
use crate::consts::{
ARC_SWEEP_GIZMO_RADIUS, COLOR_OVERLAY_BLACK, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_50, COLOR_OVERLAY_GREEN, COLOR_OVERLAY_RED, COLOR_OVERLAY_WHITE, COLOR_OVERLAY_WHITE_05, COLOR_OVERLAY_YELLOW,
COLOR_OVERLAY_YELLOW_DULL, COMPASS_ROSE_ARROW_SIZE, COMPASS_ROSE_HOVER_RING_DIAMETER, COMPASS_ROSE_MAIN_RING_DIAMETER, COMPASS_ROSE_RING_INNER_DIAMETER, CURVATURE_COMB_DEFAULT_SCALE,
DOWEL_PIN_RADIUS, GRADIENT_MIDPOINT_DIAMOND_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH, PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET,
SKEW_TRIANGLE_SIZE,
DOWEL_PIN_RADIUS, GRADIENT_LINE_WIDTH, GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT, GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH, GRADIENT_STOP_RADIUS, MANIPULATOR_GROUP_MARKER_SIZE, PIVOT_CROSSHAIR_LENGTH,
PIVOT_CROSSHAIR_THICKNESS, PIVOT_DIAMETER, RESIZE_HANDLE_SIZE, SKEW_TRIANGLE_OFFSET, SKEW_TRIANGLE_SIZE,
};
use crate::messages::portfolio::document::overlays::utility_functions::hex_to_rgba_u8;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -24,7 +24,7 @@ use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::misc::point_to_dvec2;
use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, NodeParameter};
use graphene_std::{ATTR_TRANSFORM, Color, NodeParameter};
use kurbo::{self, BezPath, ParamCurve};
use kurbo::{Affine, PathSeg};
use std::borrow::Cow;
@@ -404,6 +404,12 @@ impl OverlayContext {
self.record(move |overlays| overlays.dashed_polygon(&polygon, stroke_color.as_deref(), color_fill.as_deref(), dash_width, dash_gap_width, dash_offset));
}
/// Strokes the open path through these points, unlike [`Self::dashed_polygon`], which closes it.
pub fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
let (points, color) = (points.to_vec(), owned(color));
self.record(move |overlays| overlays.dashed_polyline(&points, color.as_deref(), dash_width, dash_gap_width, dash_offset));
}
pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
let color = owned(color);
self.record(move |overlays| overlays.line(start, end, color.as_deref(), thickness));
@@ -428,6 +434,12 @@ impl OverlayContext {
self.record(move |overlays| overlays.manipulator_handle(position, selected, color.as_deref()));
}
/// Draws a handle like [`Self::manipulator_handle`] outlined in `color`, and filled with it too where `selected`.
pub fn colored_manipulator_handle(&mut self, position: DVec2, selected: bool, color: &str) {
let color = color.to_owned();
self.record(move |overlays| overlays.filled_manipulator_handle(position, if selected { &color } else { COLOR_OVERLAY_WHITE }, &color));
}
pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
let color = owned(color);
self.record(move |overlays| overlays.manipulator_anchor(position, selected, color.as_deref()));
@@ -438,8 +450,15 @@ impl OverlayContext {
self.record(move |overlays| overlays.gradient_color_stop(position, emphasis, &color, small));
}
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, angle));
/// Draws a gradient midpoint's diamond filled with `color`, taller across the gradient line at `angle` than it is wide, bordered like a color stop's dot.
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
let color = color.to_owned();
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, &color, angle));
}
/// Draws a line in a gradient's own colors, from its color `stops` at fractions of the way from `start` to `end`, outlined in white and then black like its color stops.
pub fn gradient_line(&mut self, start: DVec2, end: DVec2, stops: Vec<(f64, Color)>) {
self.record(move |overlays| overlays.gradient_line(start, end, &stops));
}
pub fn resize_handle(&mut self, position: DVec2, rotation: f64) {
@@ -785,6 +804,24 @@ impl OverlayContextInternal {
self.stroke_in_view(&stroke, Self::parse_color(stroke_color), &path);
}
fn dashed_polyline(&mut self, points: &[DVec2], color: Option<&str>, dash_width: Option<f64>, dash_gap_width: Option<f64>, dash_offset: Option<f64>) {
let mut points = points.iter().map(|&point| self.snap_to_physical_pixel_center(point));
let Some(first) = points.next() else { return };
let mut path = BezPath::new();
path.move_to(kurbo::Point::new(first.x, first.y));
for point in points {
path.line_to(kurbo::Point::new(point.x, point.y));
}
let mut stroke = kurbo::Stroke::new(1.);
if let Some(dash_width) = dash_width {
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap_width.unwrap_or(1.)]);
}
self.stroke_in_view(&stroke, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), &path);
}
fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
self.dashed_line(start, end, color, thickness, None, None, None)
}
@@ -809,16 +846,17 @@ impl OverlayContextInternal {
}
fn manipulator_handle(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.filled_manipulator_handle(position, fill, color.unwrap_or(COLOR_OVERLAY_BLUE));
}
fn filled_manipulator_handle(&mut self, position: DVec2, fill: &str, stroke: &str) {
let transform = self.get_transform();
let position = self.snap_to_physical_pixel_center(position);
let circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.);
let fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &circle);
self.scene
.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &circle);
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(stroke), None, &circle);
}
fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
@@ -860,7 +898,7 @@ impl OverlayContextInternal {
GizmoEmphasis::Active => 1.,
};
let stroke_width = radius_offset * 2. + 1.;
let radius = (MANIPULATOR_GROUP_MARKER_SIZE / 1.5 + 1. + radius_offset) * if small { 0.5 } else { 1. };
let radius = (GRADIENT_STOP_RADIUS + radius_offset) * if small { 0.5 } else { 1. };
let mut draw_circle = |radius: f64, width: Option<f64>, color: &str| {
let circle = kurbo::Circle::new((position.x, position.y), radius);
@@ -878,33 +916,59 @@ impl OverlayContextInternal {
draw_circle(radius, Some(stroke_width), COLOR_OVERLAY_WHITE);
}
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) {
let transform = self.get_transform();
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
let position = position.round() - DVec2::splat(0.5);
let transform = self.get_transform() * kurbo::Affine::translate((position.x, position.y)) * kurbo::Affine::rotate(angle);
// Rotate diamond points by the gradient line angle
let (sin, cos) = angle.sin_cos();
let rotate = |dx: f64, dy: f64| DVec2::new(dx * cos - dy * sin, dx * sin + dy * cos);
let top = rotate(0., -GRADIENT_MIDPOINT_DIAMOND_RADIUS);
let right = rotate(GRADIENT_MIDPOINT_DIAMOND_RADIUS, 0.);
let bottom = rotate(0., GRADIENT_MIDPOINT_DIAMOND_RADIUS);
let left = rotate(-GRADIENT_MIDPOINT_DIAMOND_RADIUS, 0.);
let mut path = BezPath::new();
path.move_to(kurbo::Point::new(position.x + top.x, position.y + top.y));
path.line_to(kurbo::Point::new(position.x + right.x, position.y + right.y));
path.line_to(kurbo::Point::new(position.x + bottom.x, position.y + bottom.y));
path.line_to(kurbo::Point::new(position.x + left.x, position.y + left.y));
path.close_path();
let (fill, stroke_width) = match emphasis {
GizmoEmphasis::Regular => (COLOR_OVERLAY_WHITE, 1.),
GizmoEmphasis::Hovered => (COLOR_OVERLAY_WHITE, 2.),
GizmoEmphasis::Active => (COLOR_OVERLAY_BLUE, 1.),
// Grown for emphasis with a thicker white border, as a color stop's dot is
let radius_offset = match emphasis {
GizmoEmphasis::Regular => 0.,
GizmoEmphasis::Hovered => 0.5,
GizmoEmphasis::Active => 1.,
};
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &path);
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
let stroke_width = radius_offset * 2. + 1.;
// Taller across the gradient line than it is wide along it
let (half_width, half_height) = (GRADIENT_MIDPOINT_DIAMOND_HALF_WIDTH + radius_offset, GRADIENT_MIDPOINT_DIAMOND_HALF_HEIGHT + radius_offset);
let mut diamond = BezPath::new();
diamond.move_to((half_width, 0.));
diamond.line_to((0., half_height));
diamond.line_to((-half_width, 0.));
diamond.line_to((0., -half_height));
diamond.close_path();
// The black border shows half a pixel past the white one, as around a color stop's dot
self.scene
.stroke(&kurbo::Stroke::new(stroke_width + 1.), transform, Self::parse_color(COLOR_OVERLAY_BLACK), None, &diamond);
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color), None, &diamond);
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &diamond);
}
fn gradient_line(&mut self, start: DVec2, end: DVec2, stops: &[(f64, Color)]) {
let transform = self.get_transform();
// Centered on whole pixels, the even widths have crisp edges
let [start, end] = [start, end].map(|point| self.snap_to_physical_pixel(point));
let line = kurbo::Line::new((start.x, start.y), (end.x, end.y));
// Bordered like a color stop's dot, by a pixel of white and then half a pixel of black
self.scene
.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH + 3.), transform, Self::parse_color(COLOR_OVERLAY_BLACK), None, &line);
self.scene
.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH + 2.), transform, Self::parse_color(COLOR_OVERLAY_WHITE), None, &line);
// Opaque like the stops' dots
let stops = stops.iter().map(|&(offset, color)| {
let [red, green, blue, _] = color.to_gamma_srgb_channels();
peniko::ColorStop {
offset: offset as f32,
color: peniko::color::DynamicColor::from_alpha_color(peniko::Color::new([red, green, blue, 1.])),
}
});
let mut gradient = peniko::Gradient::new_linear((start.x, start.y), (end.x, end.y));
gradient.stops = peniko::ColorStops(stops.collect());
self.scene.stroke(&kurbo::Stroke::new(GRADIENT_LINE_WIDTH), transform, &gradient, None, &line);
}
fn resize_handle(&mut self, position: DVec2, rotation: f64) {
@@ -0,0 +1,454 @@
//! Geometry of the Gradient tool's gizmos, in gradient space, where the gradient line runs from the start point at the origin to the end
//! point at (1, 0). Each end's contour passes through its endpoint with its center on the line, set by its curvature, as described
//! in [`graphene_std::vector::gradient_standard`].
use glam::{DAffine2, DVec2};
use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature};
use std::f64::consts::{FRAC_PI_2, PI};
/// The farthest a drawn contour bows from its chords between the points it's drawn through, in viewport pixels.
const CONTOUR_SAG_TOLERANCE: f64 = 0.25;
/// The most chords a contour is drawn with.
const CONTOUR_MAX_CHORDS: usize = 1024;
/// One of the gradient line's two ends, each with its own contour.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GradientEnd {
Start,
End,
}
impl GradientEnd {
/// Its index in a `[start, end]` pair of curvatures.
pub fn index(self) -> usize {
match self {
Self::Start => 0,
Self::End => 1,
}
}
/// Its endpoint in gradient space.
pub fn endpoint(self) -> DVec2 {
match self {
Self::Start => DVec2::ZERO,
Self::End => DVec2::X,
}
}
/// Which way along the gradient line points toward the other end, which a positive curvature bows this end's contour toward.
fn inward(self) -> f64 {
match self {
Self::Start => 1.,
Self::End => -1.,
}
}
}
/// The center of this end's contour in gradient space for its `curvature`, or `None` for a line.
pub fn contour_center(end: GradientEnd, curvature: f64) -> Option<DVec2> {
let radius = curvature_radius(curvature);
radius.is_finite().then(|| end.endpoint() + DVec2::new(end.inward() * radius, 0.))
}
/// The curvature that centers this end's contour at `axis_position` along the gradient line, as dragging its center dot there does.
pub fn center_curvature(end: GradientEnd, axis_position: f64) -> f64 {
radius_curvature((axis_position - end.endpoint().x) * end.inward())
}
/// The curvature of this end's contour through `point`, the circle through it and the endpoint with its center on the gradient line,
/// which is the line across the gradient line where `point` lies across from the endpoint. `None` at the endpoint itself.
pub fn rim_curvature(end: GradientEnd, point: DVec2) -> Option<f64> {
let offset = point - end.endpoint();
let distance_squared = offset.length_squared();
// The inverse of the radius `|offset|² / 2 offset.x`, which stays finite where the radius doesn't
(distance_squared > 0.).then(|| (2. * offset.x * end.inward() / distance_squared).atan() / FRAC_PI_2)
}
/// The signed radius that resizes this end's contour (from its `curvature`) to bring the place on its rim nearest `grabbed` as near `pointer` as it gets,
/// both in the space `unit_to_viewport` maps to, and where that place lands there. `None` for a line or a point, which no resizing moves a place on.
pub fn rim_resized_toward(end: GradientEnd, curvature: f64, grabbed: DVec2, pointer: DVec2, unit_to_viewport: DAffine2) -> Option<(f64, DVec2)> {
let radius = curvature_radius(curvature);
if !radius.is_finite() || radius == 0. {
return None;
}
let inward = DVec2::new(end.inward(), 0.);
// Each circle through the endpoint is the others scaled about it, so the place keeps its angle around them from the endpoint, measured at the center
let to_endpoint = -radius * inward;
let to_grabbed = unit_to_viewport.inverse().transform_point2(grabbed) - end.endpoint() - radius * inward;
let angle = to_endpoint.perp_dot(to_grabbed).atan2(to_endpoint.dot(to_grabbed));
// At that angle, the place lies the radius times this from the endpoint, a line the pointer projects onto
let direction = unit_to_viewport.transform_vector2(inward - DVec2::from_angle(angle).rotate(inward));
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
let resized = (pointer - endpoint).dot(direction) / direction.length_squared();
resized.is_finite().then(|| (resized, endpoint + resized * direction))
}
/// Whether a gradient with these curvatures has a focus to move: a point for its start contour and a circle for its end contour.
pub fn has_focus(curvatures: [f64; 2]) -> bool {
let end_radius = curvature_radius(curvatures[1]);
curvature_radius(curvatures[0]) == 0. && end_radius.is_finite() && end_radius != 0.
}
/// A gradient line in the gradient space of the line it replaces, with the curvature it gives the end contour.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RefocusedLine {
pub start: DVec2,
pub end: DVec2,
pub end_curvature: f64,
}
/// The line of a gradient whose start point (its focus) moves to `focus` while its end circle from `end_curvature` stays put: from the focus through the
/// circle's center to its far side, with the end curvature keeping that circle. A focus on the center keeps `direction`. `None` unless the end is a circle.
pub fn refocused_line(focus: DVec2, end_curvature: f64, direction: DVec2) -> Option<RefocusedLine> {
let radius = curvature_radius(end_curvature);
if !radius.is_finite() || radius == 0. {
return None;
}
let (center, size) = (DVec2::new(1. - radius, 0.), radius.abs());
let to_center = center - focus;
let distance = to_center.length();
let direction = if distance > 0. { to_center / distance } else { direction.try_normalize()? };
Some(RefocusedLine {
start: focus,
end: center + direction * size,
end_curvature: radius_curvature(size / (distance + size)),
})
}
/// The transform placing a gradient along `line`, given in the gradient space of the `old` transform. Its frame turns and scales uniformly within
/// that space, so a contour that's a circle there keeps its shape, even where `old` stretches it into an ellipse.
pub fn transform_along(old: DAffine2, line: RefocusedLine) -> DAffine2 {
let x_axis = line.end - line.start;
old * DAffine2::from_cols(x_axis, x_axis.perp(), line.start)
}
/// One side of the gradient line, across which its perpendicular axis points one way or the other.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineSide {
Positive,
Negative,
}
impl LineSide {
/// Which way across the gradient line its perpendicular axis points to reach this side.
pub fn sign(self) -> f64 {
match self {
Self::Positive => 1.,
Self::Negative => -1.,
}
}
}
/// The semi-minor axis to this side of this end's circle from its `curvature`, from the circle's center a radius across the gradient line to where
/// a handle stretching the gradient across its line sits, in gradient space. `None` for a line or a point.
pub fn aspect_axis(end: GradientEnd, curvature: f64, side: LineSide) -> Option<[DVec2; 2]> {
let radius = curvature_radius(curvature).abs();
let center = contour_center(end, curvature).filter(|_| radius > 0.)?;
Some([center, center + DVec2::new(0., side.sign() * radius)])
}
/// The transform stretched across its line so the point `handle` in its gradient space lies as far across the line as `pointer` does
/// (in the transform's output space), keeping the line and how far its perpendicular axis leans along it. `None` where it would collapse.
pub fn stretched_transform(transform: DAffine2, handle: DVec2, pointer: DVec2) -> Option<DAffine2> {
let x_axis = transform.matrix2.x_axis;
let along = x_axis.try_normalize()?;
let across = along.perp();
// The handle lies `handle.y` times the perpendicular axis's span across the line
let span_across = (pointer - transform.translation).dot(across) / handle.y;
if !(span_across.abs() > 1e-9 * x_axis.length()) {
return None;
}
let y_axis = along * transform.matrix2.y_axis.dot(along) + across * span_across;
Some(DAffine2::from_cols(x_axis, y_axis, transform.translation))
}
/// The smallest factor `transform` scales any length by, the least singular value of its linear part.
fn least_scale(transform: DAffine2) -> f64 {
let [x_axis, y_axis] = [transform.matrix2.x_axis, transform.matrix2.y_axis];
let determinant = transform.matrix2.determinant().abs();
// Of the singular values `√(mean ± √(mean² - determinant²))`, the least is the determinant over the greatest, which avoids cancellation
let mean = (x_axis.length_squared() + y_axis.length_squared()) / 2.;
let greatest = (mean + (mean * mean - determinant * determinant).max(0.).sqrt()).sqrt();
if greatest > 0. { determinant / greatest } else { 0. }
}
/// Points through which this end's contour is drawn in the viewport, from `unit_to_viewport`, as far as `reach` viewport pixels from
/// its endpoint along it (or around the whole circle if that's shorter). Empty for a point, or where the transform collapses.
pub fn contour_polyline(end: GradientEnd, curvature: f64, unit_to_viewport: DAffine2, reach: f64) -> Vec<DVec2> {
let radius = curvature_radius(curvature);
let endpoint = end.endpoint();
let least_scale = least_scale(unit_to_viewport);
if radius == 0. || least_scale <= 0. {
return Vec::new();
}
// A line runs straight across the gradient line through the endpoint
if radius.is_infinite() {
let Some(direction) = unit_to_viewport.transform_vector2(DVec2::Y).try_normalize() else {
return Vec::new();
};
let viewport_endpoint = unit_to_viewport.transform_point2(endpoint);
return vec![viewport_endpoint - direction * reach, viewport_endpoint + direction * reach];
}
// Sweep from the endpoint both ways around the circle, by the angle reaching `reach` pixels at the least scale
let size = radius.abs();
let sweep = (reach / (size * least_scale)).min(PI);
// Uniform steps small enough that each chord stays within the sag tolerance, even at twice the longest axis's scale (which bounds the greatest)
let viewport_radius_bound = size * unit_to_viewport.matrix2.x_axis.length().max(unit_to_viewport.matrix2.y_axis.length()) * 2.;
let step = (8. * CONTOUR_SAG_TOLERANCE / viewport_radius_bound).sqrt();
let chords_each_way = ((sweep / step).ceil() as usize).clamp(4, CONTOUR_MAX_CHORDS / 2);
let chords = 2 * chords_each_way;
// Measured from the endpoint rather than the center, the points stay precise on huge circles
(0..=chords)
.map(|index| {
let angle = sweep * (2. * index as f64 / chords as f64 - 1.);
let half_sine = (angle / 2.).sin();
let offset = DVec2::new(2. * end.inward() * radius * half_sine * half_sine, size * angle.sin());
unit_to_viewport.transform_point2(endpoint + offset)
})
.collect()
}
/// The distance from `point` to the nearest place on the polyline through `points`, or `None` if it has none.
pub fn distance_to_polyline(points: &[DVec2], point: DVec2) -> Option<f64> {
if let [only] = points {
return Some(only.distance(point));
}
points
.windows(2)
.map(|pair| {
let (start, end) = (pair[0], pair[1]);
let along = (point - start).dot(end - start) / (end - start).length_squared();
let nearest = if along.is_finite() { start.lerp(end, along.clamp(0., 1.)) } else { start };
nearest.distance(point)
})
.min_by(f64::total_cmp)
}
#[cfg(test)]
mod tests {
use super::*;
/// Curvatures through circles of each size and bend, both lines, and the points.
fn curvatures() -> impl Iterator<Item = f64> {
(-20..=20).map(|step| step as f64 * 0.05)
}
#[test]
fn a_rim_dragged_to_a_point_takes_the_curvature_of_the_circle_through_it() {
for end in [GradientEnd::Start, GradientEnd::End] {
for point in [DVec2::new(0.3, 0.4), DVec2::new(-0.7, 1.2), DVec2::new(2.5, -0.25), DVec2::new(0.5, 3.)] {
let curvature = rim_curvature(end, point).unwrap();
// The contour of that curvature passes through the point, centered on the gradient line
let center = contour_center(end, curvature).unwrap();
assert!(center.y == 0.);
let radius = center.distance(end.endpoint());
assert!((center.distance(point) - radius).abs() < 1e-9 * radius.max(1.), "{end:?} through {point}: curvature {curvature}");
}
// Straight across from the endpoint is the line, and either side of it bends toward that side
let across = end.endpoint() + DVec2::Y;
assert_eq!(rim_curvature(end, across), Some(0.));
let inward = DVec2::new(end.inward() * 0.1, 0.);
assert!(rim_curvature(end, across + inward).unwrap() > 0.);
assert!(rim_curvature(end, across - inward).unwrap() < 0.);
// The endpoint is on every contour, so it sets none
assert_eq!(rim_curvature(end, end.endpoint()), None);
}
}
#[test]
fn a_rim_dragged_along_its_own_contour_keeps_its_curvature() {
for end in [GradientEnd::Start, GradientEnd::End] {
for curvature in curvatures().filter(|curvature| curvature.abs() != 1.) {
for point in contour_polyline(end, curvature, DAffine2::IDENTITY, 3.) {
// Every point but the endpoint sets the curvature back, as a line's points beside the endpoint do
if point.distance(end.endpoint()) < 1e-6 {
continue;
}
let found = rim_curvature(end, point).unwrap();
assert!((found - curvature).abs() < 1e-9, "{end:?} curvature {curvature} at {point}: {found}");
}
}
}
}
#[test]
fn a_center_dragged_along_the_line_takes_the_curvature_centered_there() {
for end in [GradientEnd::Start, GradientEnd::End] {
for curvature in curvatures().filter(|&curvature| curvature != 0.) {
let center = contour_center(end, curvature).unwrap();
let found = center_curvature(end, center.x);
// A point is both -1 and 1, which the drag settles at -1
let expected = if curvature.abs() == 1. { -1. } else { curvature };
assert!((found - expected).abs() < 1e-9, "{end:?} curvature {curvature}: {found}");
}
// Toward the other end bows toward it, and onto the endpoint is a point
assert!(center_curvature(end, 0.5) > 0.);
assert!(center_curvature(end, end.endpoint().x - end.inward()) < 0.);
assert_eq!(center_curvature(end, end.endpoint().x), -1.);
}
// The start contour centered at the end point, and the end contour at the start point, are each the circle of radius 1 between them
assert!((center_curvature(GradientEnd::Start, 1.) - 0.5).abs() < 1e-12);
assert!((center_curvature(GradientEnd::End, 0.) - 0.5).abs() < 1e-12);
}
/// The center and radius of the end circle of a gradient along `line`, in the gradient space `line` is given in.
fn end_circle(line: RefocusedLine) -> (DVec2, f64) {
let radius = curvature_radius(line.end_curvature);
(line.start.lerp(line.end, 1. - radius), radius.abs() * line.start.distance(line.end))
}
#[test]
fn a_moved_focus_keeps_the_end_circle_in_place() {
// The end circle of radius 0.75 centered at 0.25, with foci inside it, outside it, and behind its center
let end_curvature = radius_curvature(0.75);
let (center, radius) = (DVec2::new(0.25, 0.), 0.75);
for focus in [DVec2::new(0.1, 0.3), DVec2::new(-0.2, -0.4), DVec2::new(3., 2.), DVec2::new(0.9, 0.), DVec2::new(-5., 0.)] {
let line = refocused_line(focus, end_curvature, DVec2::X).unwrap();
assert_eq!(line.start, focus);
let (new_center, new_radius) = end_circle(line);
assert!(new_center.distance(center) < 1e-12 && (new_radius - radius).abs() < 1e-12, "focus {focus}: {line:?}");
// The line runs on through the center to the circle's far side
assert!((line.end.distance(focus) - (focus.distance(center) + radius)).abs() < 1e-12, "focus {focus}: {line:?}");
}
// A focus off the circle's line still aims the line through its center
let line = refocused_line(DVec2::new(0.25, 2.), end_curvature, DVec2::X).unwrap();
assert!(line.end.abs_diff_eq(DVec2::new(0.25, -0.75), 1e-12));
}
#[test]
fn a_focus_on_the_center_keeps_the_direction_and_makes_the_radial_form() {
let end_curvature = radius_curvature(0.75);
let line = refocused_line(contour_center(GradientEnd::End, end_curvature).unwrap(), end_curvature, DVec2::new(0., 2.)).unwrap();
assert_eq!(line.end_curvature, 0.5);
assert!(line.end.abs_diff_eq(DVec2::new(0.25, 0.75), 1e-12));
assert_eq!(
graphene_std::vector::style::GradientForm::from_curvatures([-1., line.end_curvature]),
Some(graphene_std::vector::style::GradientForm::Radial)
);
// Only an end circle has a focus to move around
assert!(has_focus([-1., 0.5]) && has_focus([1., -0.3]));
assert!(!has_focus([0., 0.5]) && !has_focus([-1., 0.]) && !has_focus([-1., 1.]));
assert_eq!(refocused_line(DVec2::ZERO, 0., DVec2::X), None);
}
#[test]
fn a_refocused_transform_keeps_an_elliptical_end_contour_in_place() {
// A radial gradient squashed to half its height and skewed, whose focus moves off its line
let old = DAffine2::from_cols(DVec2::new(100., 20.), DVec2::new(-5., 50.), DVec2::new(30., 40.));
let line = refocused_line(DVec2::new(0.3, 0.4), 0.5, DVec2::X).unwrap();
let new = transform_along(old, line);
// The end contour's points land on the same ellipse before and after (within its chords' sag), though spread differently around it
let before = contour_polyline(GradientEnd::End, 0.5, old, 1e6);
let after = contour_polyline(GradientEnd::End, line.end_curvature, new, 1e6);
for point in after {
assert!(distance_to_polyline(&before, point).unwrap() <= CONTOUR_SAG_TOLERANCE, "{point} left the ellipse");
}
assert!(new.transform_point2(DVec2::ZERO).abs_diff_eq(old.transform_point2(DVec2::new(0.3, 0.4)), 1e-9));
}
#[test]
fn each_end_circle_has_an_aspect_handle_a_radius_to_either_side_of_its_center() {
use LineSide::{Negative, Positive};
// The radial form's end circle around the start point, but not its start point
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Positive), Some([DVec2::ZERO, DVec2::Y]));
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Negative), Some([DVec2::ZERO, -DVec2::Y]));
assert_eq!(aspect_axis(GradientEnd::Start, -1., Positive), None);
// Each of two crossing circles, and a huge nearly flat one
let radius = curvature_radius(0.6);
assert_eq!(aspect_axis(GradientEnd::Start, 0.6, Positive), Some([DVec2::new(radius, 0.), DVec2::new(radius, radius)]));
assert_eq!(aspect_axis(GradientEnd::End, 0.6, Negative), Some([DVec2::new(1. - radius, 0.), DVec2::new(1. - radius, -radius)]));
assert!(aspect_axis(GradientEnd::End, 1e-3, Positive).is_some_and(|[_, handle]| handle.y > 100.));
// Lines and points have none
for end in [GradientEnd::Start, GradientEnd::End] {
for curvature in [0., 1., -1.] {
for side in [Positive, Negative] {
assert_eq!(aspect_axis(end, curvature, side), None, "{end:?} curvature {curvature} {side:?}");
}
}
}
}
#[test]
fn stretching_moves_each_aspect_handle_across_the_line_and_keeps_the_line() {
// A skewed gradient, its perpendicular axis leaning along the line
let transform = DAffine2::from_cols(DVec2::new(80., 60.), DVec2::new(-50., 70.), DVec2::new(10., 20.));
let along = transform.matrix2.x_axis.normalize();
// The radial form's handles and those of two crossing circles of different sizes, each pulled to its own side of the line
let axes = [(GradientEnd::End, 0.5), (GradientEnd::Start, 0.6), (GradientEnd::End, 0.3)];
let handles = axes
.into_iter()
.flat_map(|(end, curvature)| [LineSide::Positive, LineSide::Negative].map(|side| (aspect_axis(end, curvature, side).unwrap()[1], side)));
for (handle, side) in handles {
let pointer = transform.transform_point2(DVec2::new(0.4, side.sign() * 0.7));
let stretched = stretched_transform(transform, handle, pointer).unwrap();
assert!(stretched.matrix2.determinant() * transform.matrix2.determinant() > 0., "the gradient shouldn't mirror");
for point in [DVec2::ZERO, DVec2::X] {
assert!(stretched.transform_point2(point).abs_diff_eq(transform.transform_point2(point), 1e-9));
}
// The handle lands as far across the line as the pointer, sliding only across it, and the lean along the line stays
let (old_handle, new_handle) = (transform.transform_point2(handle), stretched.transform_point2(handle));
assert!(((new_handle - transform.translation).dot(along.perp()) - (pointer - transform.translation).dot(along.perp())).abs() < 1e-9);
assert!((new_handle - old_handle).dot(along).abs() < 1e-9);
assert!((stretched.matrix2.y_axis.dot(along) - transform.matrix2.y_axis.dot(along)).abs() < 1e-9);
// Onto the line, it would collapse
assert_eq!(stretched_transform(transform, handle, transform.transform_point2(DVec2::new(0.5, 0.))), None);
}
}
#[test]
fn contours_are_drawn_through_their_endpoints_out_to_their_reach() {
let unit_to_viewport = DAffine2::from_scale_angle_translation(DVec2::new(200., 100.), 0.3, DVec2::new(40., 60.));
for end in [GradientEnd::Start, GradientEnd::End] {
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
// A point draws nothing, and a line is one long chord through the endpoint
assert!(contour_polyline(end, 1., unit_to_viewport, 500.).is_empty());
let line = contour_polyline(end, 0., unit_to_viewport, 500.);
assert_eq!(line.len(), 2);
assert!(distance_to_polyline(&line, endpoint).unwrap() < 1e-9);
// A small circle is drawn whole, closing on itself, and a huge one only as far as its reach, nearly straight
let small = contour_polyline(end, 0.5, unit_to_viewport, 500.);
assert!(small.first().unwrap().distance(*small.last().unwrap()) < 1e-6);
let huge = contour_polyline(end, 1e-6, unit_to_viewport, 500.);
let farthest = huge.iter().map(|point| point.distance(endpoint)).fold(0., f64::max);
assert!((400. ..=1000.).contains(&farthest), "a huge circle should reach about 500 pixels, not {farthest}");
for polyline in [small, huge] {
assert!(distance_to_polyline(&polyline, endpoint).unwrap() < 1e-6);
}
}
}
}
@@ -3,6 +3,7 @@ pub mod color_selector;
pub mod compass_rose;
pub mod edit_target;
pub mod gizmos;
pub mod gradient_gizmos;
pub mod graph_modification_utils;
pub mod layer_origin_cross;
pub mod measure;
@@ -92,6 +92,8 @@ pub struct PointOptions {
pub box_features: Option<BoxFeatures>,
/// Whether the grid is left out, as for a turn, which the grid would otherwise step at odd angles.
pub ignores_grid: bool,
/// Whether the tool marks where a press would land in its own way, so nothing marks it there unless a snap is named.
pub marked_by_tool: bool,
}
/// Which features of a gesture make up a box.
@@ -122,6 +124,8 @@ pub struct Shown {
pub features: Vec<DVec2>,
/// The index of the feature the pointer carries.
pub lead: usize,
/// Whether the tool marks where a press would land, as [`PointOptions::marked_by_tool`] tells.
pub marked_by_tool: bool,
}
/// What a kept set of constructions was found for, which it stays good for.
@@ -321,6 +325,7 @@ impl SnapSession {
features: features.iter().map(|feature| feature.position(parameters)).collect(),
lead,
outcome,
marked_by_tool: options.marked_by_tool,
});
// A crossing, or the grid, can hold the box anywhere along the track that evens out its gaps, so they are measured again where it landed
@@ -399,6 +404,7 @@ impl SnapSession {
features: vec![position_of(snapped)],
lead: 0,
outcome,
marked_by_tool: false,
});
snapped
@@ -19,14 +19,24 @@ impl SnapSession {
self.draw_awake(target, to_viewport, overlay_context);
}
let Some(Shown { outcome, features, lead, .. }) = &self.shown else { return };
let Some(Shown {
outcome,
features,
lead,
marked_by_tool,
}) = &self.shown
else {
return;
};
// Before a press, the point is marked where the press would place it, even with no snap to name
if matches!(outcome.snap, Snap::Grid | Snap::Free)
&& self.gesture.is_none()
&& let Some(&position) = features.get(*lead)
{
overlay_context.square(to_viewport.transform_point2(position), Some(4.), Some(COLOR_OVERLAY_BLUE), Some(COLOR_OVERLAY_BLUE));
if !marked_by_tool {
overlay_context.square(to_viewport.transform_point2(position), Some(4.), Some(COLOR_OVERLAY_BLUE), Some(COLOR_OVERLAY_BLUE));
}
return;
}
File diff suppressed because it is too large. Load diff
@@ -115,16 +115,6 @@ impl Adjustment {
}
}
/// Whether the adjustment might change a color's alpha, which only Make Opaque and the alpha records of Levels and Curves do.
pub fn may_change_alpha(&self) -> bool {
match self {
Self::MakeOpaque { .. } => true,
Self::Levels(settings) => !settings.alpha.is_identity(),
Self::Curves(settings) => settings.alpha != TransferCurve::default(),
_ => false,
}
}
/// Whether each channel of the result depends only on the same channel of the color, making the adjustment four curves.
pub fn is_per_channel(&self) -> bool {
matches!(
@@ -496,20 +486,6 @@ fn grouped_key(group: &str, parameter: &str) -> String {
}
impl LevelsRecord {
/// The record leaving every value as it is, as its node's defaults do.
pub const IDENTITY: Self = Self {
shadows: 0.,
midtones: 1.,
highlights: 100.,
output_minimums: 0.,
output_maximums: 100.,
};
/// Whether the record leaves every value as it is.
pub fn is_identity(&self) -> bool {
*self == Self::IDENTITY
}
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
@@ -454,17 +454,6 @@ impl Effects {
self.operations().all(|operation| operation.changes_nothing())
}
/// Whether the effects might change the content's alpha, as any but an adjustment keeping it (see [`Adjustment::may_change_alpha`]) can unless it changes nothing.
pub fn may_change_alpha(&self) -> bool {
self.operations().any(|operation| {
!operation.changes_nothing()
&& match &operation {
EffectOperation::Adjustment(adjustment) => adjustment.may_change_alpha(),
_ => true,
}
})
}
/// The effects of the given range of rows decoded into operations, in order.
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
@@ -1,6 +1,6 @@
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the CPU, GPU, and SVG each carry out.
use crate::effects::EffectOperation;
use crate::effects::{EffectOperation, Effects};
use core_types::graphene_hash::CacheHash;
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
@@ -181,6 +181,12 @@ pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
}
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
/// The random field filters change endless content without its neighbors (see [`is_random_field_filter`]).
pub fn has_filters(effects: &Effects) -> bool {
effects.operations().any(|operation| reads_neighbors(&operation) && !operation.changes_nothing())
}
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
pub const SOBEL_TAPS: [(DVec2, [f64; 2]); 8] = [
(DVec2::new(-1., -1.), [-1., -1.]),
+35 -129
View File
@@ -630,17 +630,16 @@ impl Graphic {
}
}
/// Whether this graphic clips as its outline would, with `inherited_appearance` cascading from an ancestor to vectors lacking their own.
pub fn can_reduce_to_clip_path(&self, inherited_appearance: Option<&Appearance>) -> bool {
pub fn can_reduce_to_clip_path(&self) -> bool {
// Effects (like a mask, which shapes a clip) are more than an outline can express
match self {
Graphic::Vector(item) => {
let appearance = Appearance::cascade(item.attribute(ATTR_APPEARANCE), inherited_appearance);
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), appearance)
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing)
&& vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
}
Graphic::VectorList(list) => (0..list.len()).all(|index| {
let appearance = Appearance::cascade(list.attribute(ATTR_APPEARANCE, index), inherited_appearance);
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), appearance)
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing)
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
}),
_ => false,
}
@@ -649,22 +648,16 @@ impl Graphic {
pub fn is_guaranteed_fully_opaque(&self) -> bool {
match self {
Graphic::None(_) | Graphic::NoneList(_) => false,
// The group's own opacity and effects act on whatever it wraps, so they must keep it at full alpha
Graphic::Graphic(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_opaque(),
Graphic::GraphicList(list) => {
!list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque)
}
Graphic::Vector(item) => {
!item_effects_may_change_alpha(item)
&& vector_is_guaranteed_fully_opaque(
item.attribute_cloned_or(ATTR_OPACITY, 1.),
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
item.attribute::<Appearance>(ATTR_APPEARANCE),
)
}
// The group's own opacity scales whatever it wraps, so full alpha there is a precondition
Graphic::Graphic(item) => item_opacity_is_full(item) && item.element().is_guaranteed_fully_opaque(),
Graphic::GraphicList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque),
Graphic::Vector(item) => vector_is_guaranteed_fully_opaque(
item.attribute_cloned_or(ATTR_OPACITY, 1.),
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
item.attribute::<Appearance>(ATTR_APPEARANCE),
),
Graphic::VectorList(list) => {
!list.is_empty()
&& !list_effects_may_change_alpha(list)
&& (0..list.len()).all(|index| {
vector_is_guaranteed_fully_opaque(
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
@@ -676,12 +669,11 @@ impl Graphic {
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
Graphic::Color(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_opaque(),
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.is_opaque()),
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
// A `Clear` spread cuts off to transparency past the ends, and curved contours may leave gaps, leaving the rest of the region unpainted
Graphic::Gradient(item) => {
item_opacity_is_full(item)
&& !item_effects_may_change_alpha(item)
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
&& gradient_paints_everywhere(&|key| item.attributes().get_any(key))
&& item.element().iter().all(|stop| stop.color.is_opaque())
@@ -689,7 +681,6 @@ impl Graphic {
Graphic::GradientList(list) => {
!list.is_empty()
&& every_item_has_full_opacity(list)
&& !list_effects_may_change_alpha(list)
&& (0..list.len()).all(|index| {
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
&& gradient_paints_everywhere(&|key| list.attribute_any(key, index))
@@ -702,41 +693,27 @@ impl Graphic {
}
pub fn is_guaranteed_fully_transparent(&self) -> bool {
// An effect that might change alpha, like Make Opaque or a shadow, can show content its paints leave transparent, so only its opacity can hide it
match self {
Graphic::None(_) | Graphic::NoneList(_) => true,
Graphic::Graphic(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_transparent()),
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent)),
Graphic::Vector(item) => {
item_opacity_is_zero(item)
|| (!item_effects_may_change_alpha(item)
&& vector_is_guaranteed_fully_transparent(
item.attribute_cloned_or(ATTR_OPACITY, 1.),
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
item.attribute::<Appearance>(ATTR_APPEARANCE),
item.attribute::<Effects>(ATTR_EFFECTS),
))
}
Graphic::VectorList(list) => {
every_item_has_zero_opacity(list)
|| (!list_effects_may_change_alpha(list)
&& (0..list.len()).all(|index| {
vector_is_guaranteed_fully_transparent(
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
list.attribute::<Effects>(ATTR_EFFECTS, index),
)
}))
}
Graphic::Color(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().a() == 0.),
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.a() == 0.)),
Graphic::Graphic(item) => item_opacity_is_zero(item) || item.element().is_guaranteed_fully_transparent(),
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent),
Graphic::Vector(item) => vector_is_guaranteed_fully_transparent(
item.attribute_cloned_or(ATTR_OPACITY, 1.),
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
item.attribute::<Appearance>(ATTR_APPEARANCE),
),
Graphic::VectorList(list) => (0..list.len()).all(|index| {
vector_is_guaranteed_fully_transparent(
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
)
}),
Graphic::Color(item) => item_opacity_is_zero(item) || item.element().a() == 0.,
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|color| color.a() == 0.),
// A stopless ramp paints as solid black, matching `Gradient::evaluate`, so it counts as transparent only once it has stops
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && !item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
Graphic::GradientList(list) => {
every_item_has_zero_opacity(list)
|| (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)))
}
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
Graphic::GradientList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)),
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
@@ -829,13 +806,12 @@ fn vector_is_guaranteed_fully_opaque(opacity: f64, opacity_fill: f64, appearance
}
/// Whether a vector object draws nothing visible, either through its opacity or through its paint.
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>, effects: Option<&Effects>) -> bool {
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>) -> bool {
if opacity <= f64::EPSILON {
return true;
}
// Fill opacity fades the paints but not what effects paint at full strength, like overlays and shadows
let fills_invisible = (opacity_fill <= f64::EPSILON && effects.is_none_or(Effects::change_nothing))
let fills_invisible = opacity_fill <= f64::EPSILON
|| appearance.is_none_or(|appearance| {
appearance
.covers_with_paints()
@@ -853,16 +829,6 @@ fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appea
fills_invisible && strokes_invisible
}
/// Whether a lone item's effects might change its alpha, so its element's own alpha can't vouch for it being opaque or transparent.
fn item_effects_may_change_alpha<T>(item: &Item<T>) -> bool {
item.attribute::<Effects>(ATTR_EFFECTS).is_some_and(Effects::may_change_alpha)
}
/// Whether the effects of any item of a list might change its alpha (see [`item_effects_may_change_alpha`]).
fn list_effects_may_change_alpha<T>(list: &List<T>) -> bool {
(0..list.len()).any(|index| list.attribute::<Effects>(ATTR_EFFECTS, index).is_some_and(Effects::may_change_alpha))
}
/// Whether a lone item's opacity zeroes it out, independent of what its element holds.
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) <= f64::EPSILON
@@ -1342,64 +1308,4 @@ mod graphic_is_opaque_tests {
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
assert!(!Graphic::Graphic(Box::new(reduced)).is_guaranteed_fully_opaque());
}
#[test]
fn effects_that_might_change_alpha_leave_content_neither_known_opaque_nor_known_transparent() {
use crate::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
use crate::effects::EffectOperation;
use crate::vector_types::vector::style::Stroke;
let effected = |graphic: Graphic, operation: EffectOperation| Item::new_from_element(graphic).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]));
let colors = |alpha: f64, operation: EffectOperation| {
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
Graphic::ColorList(List::new_from_item(Item::new_from_element(color).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]))))
};
let make_opaque = || EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
let dissolve = || EffectOperation::Dissolve { opacity: 50., seed: 0 };
let levels = |record: LevelsRecord, alpha: LevelsRecord| {
EffectOperation::Adjustment(Adjustment::Levels(Box::new(LevelsSettings {
composite: record,
red: LevelsRecord::IDENTITY,
green: LevelsRecord::IDENTITY,
blue: LevelsRecord::IDENTITY,
alpha,
})))
};
let identity = LevelsRecord::IDENTITY;
let darkened = LevelsRecord { output_maximums: 50., ..identity };
// Adjustments keeping alpha leave paints as opaque or transparent as their colors
assert!(colors(1., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_opaque());
assert!(colors(0., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_transparent());
assert!(colors(1., levels(darkened, identity)).is_guaranteed_fully_opaque());
// Effects that might fade a paint, or show a transparent one, leave it unknown
assert!(!colors(1., dissolve()).is_guaranteed_fully_opaque());
assert!(!colors(1., levels(identity, darkened)).is_guaranteed_fully_opaque());
assert!(!colors(0., make_opaque()).is_guaranteed_fully_transparent());
assert!(!colors(0., make_opaque()).is_guaranteed_to_cover_opaquely());
// A group's own effects act on all it wraps, though its zero opacity still hides it
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(1.), dissolve()))).is_guaranteed_fully_opaque());
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()))).is_guaranteed_fully_transparent());
assert!(Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()).with_attribute(ATTR_OPACITY, 0.))).is_guaranteed_fully_transparent());
// A vector's own effects, like a shadow cast by a shape with no visible paint, do too
let mut shape = Item::new_from_element(Vector::default());
shape.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_stroke(&Stroke::new(4.)), color_graphic(0.)));
assert!(Graphic::Vector(Box::new(shape.clone())).is_guaranteed_fully_transparent());
let shadowed = shape
.clone()
.with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::default_for(crate::effects::EffectKind::DropShadow)]));
assert!(!Graphic::Vector(Box::new(shadowed)).is_guaranteed_fully_transparent());
// Zero fill opacity hides a vector's paints but not an overlay its effects paint over them, though that keeps alpha
let mut filled = Item::new_from_element(Vector::default()).with_attribute(ATTR_OPACITY_FILL, 0.);
filled.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), color_graphic(1.)));
assert!(Graphic::Vector(Box::new(filled.clone())).is_guaranteed_fully_transparent());
let overlay = EffectOperation::default_for(crate::effects::EffectKind::PaintOverlay);
assert!(matches!(overlay, EffectOperation::Adjustment(Adjustment::ColorOverlay { .. })), "{overlay:?}");
let overlaid = filled.with_attribute(ATTR_EFFECTS, Effects::from_operations([overlay]));
assert!(!Graphic::Vector(Box::new(overlaid)).is_guaranteed_fully_transparent());
}
}
@@ -2007,69 +2007,4 @@ mod tests {
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
}
}
#[test]
fn adjustments_changing_alpha_are_known_to_without_running_their_kernels() {
use core_types::transfer_curve::TransferCurve;
use glam::DVec2;
use graphic_types::effects::{EffectKind, EffectOperation};
let kinds = [
EffectKind::Desaturate,
EffectKind::GammaCorrection,
EffectKind::MakeOpaque,
EffectKind::BrightnessContrast,
EffectKind::Levels,
EffectKind::Curves,
EffectKind::BlackAndWhite,
EffectKind::HueSaturation,
EffectKind::Invert,
EffectKind::Threshold,
EffectKind::GradientMap,
EffectKind::Vibrance,
EffectKind::ChannelMixer,
EffectKind::SelectiveColor,
EffectKind::Posterize,
EffectKind::Exposure,
EffectKind::ColorBalance,
EffectKind::PhotoFilter,
EffectKind::ColorLookup,
EffectKind::Solarize,
];
let defaults = kinds.map(|kind| match EffectOperation::default_for(kind) {
EffectOperation::Adjustment(adjustment) => adjustment,
operation => panic!("{kind} isn't an adjustment: {operation:?}"),
});
// Levels and Curves change alpha by their alpha records and curves, and nothing else of theirs
let identity = settings::LevelsRecord::IDENTITY;
let darkened = settings::LevelsRecord { output_maximums: 50., ..identity };
let levels = |composite, alpha| {
Adjustment::Levels(Box::new(settings::LevelsSettings {
composite,
red: identity,
green: identity,
blue: identity,
alpha,
}))
};
let curve = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(1., 0.5)]);
let curves = |composite: TransferCurve, alpha: TransferCurve| {
Adjustment::Curves(Box::new(settings::CurvesSettings {
composite,
alpha,
..Default::default()
}))
};
let settings = [
levels(darkened, identity),
levels(identity, darkened),
curves(curve.clone(), TransferCurve::default()),
curves(TransferCurve::default(), curve),
];
for adjustment in defaults.iter().chain(&settings) {
assert_eq!(adjustment.may_change_alpha(), !preserves_alpha(adjustment), "{adjustment:?}");
}
}
}
@@ -18,4 +18,4 @@ pub mod warp_kernels;
pub use kernel::*;
pub use raster_effects::evaluate_raster_effects;
pub use value_effects::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
pub use value_effects::{evaluate_color_effects, evaluate_gradient_effects};
@@ -5,7 +5,7 @@ use crate::adjustments::{PreparedAdjustment, adjust_color};
use crate::blending::overlay_paint;
use core_types::Color;
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_OPACITY, ATTR_OPACITY_FILL, Item};
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
use graphic_types::adjustment::Adjustment;
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
use graphic_types::effects::{EffectOperation, Effects};
@@ -258,24 +258,9 @@ pub fn adjusted_gradient_with_blend_ifs(
Some((resampled, resampled_settings))
}
/// Whether [`color_after_effects`] and [`gradient_after_effects`] carry out every one of the effects, since each changes every color on its own:
/// an adjustment, a Blend If reading only the value's own colors, or an effect that changes nothing.
pub fn carries_out_every_effect(effects: &Effects) -> bool {
effects.operations().all(|operation| match operation {
EffectOperation::Adjustment(_) => true,
EffectOperation::BlendIf(ranges) => ranges.underlying.show_everything(),
_ => operation.changes_nothing(),
})
}
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
filled_color_after_effects(color, effects, 1.)
}
/// Like [`color_after_effects`], carried out over the color faded by a `fill`, which leaves the paint overlays among them at full strength, as the renderers fade content.
pub fn filled_color_after_effects(color: Color, effects: &Effects, fill: f32) -> Color {
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), fill)
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), 1.)
}
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
@@ -285,15 +270,10 @@ pub fn prepared_color_after_effects(effects: &Effects) -> Box<dyn Fn(Color) -> C
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
filled_gradient_after_effects(gradient, settings, effects, 1.)
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), 1.)
}
/// Like [`gradient_after_effects`], carried out along the ramp faded by a `fill` as [`filled_color_after_effects`] carries them out on a color.
pub fn filled_gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects, fill: f32) -> Option<(Gradient, GradientSettings)> {
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), fill)
}
/// The color with its effects carried out as [`color_after_effects`] does and consumed, though not its opacity (see [`evaluate_color_parameter`]).
/// The color with its effects carried out as [`color_after_effects`] does and consumed, for nodes that read the color.
/// A color without the effects attribute is returned as it is.
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
@@ -306,27 +286,6 @@ pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
item
}
/// The color as the renderers show it, for a node reading it as a parameter: its effects carried out over it faded by its fill, then its opacity fading it all, each consumed.
/// Every node reading one color goes through this, so those attributes mean the same to all of them.
pub fn evaluate_color_parameter(item: Item<Color>) -> Item<Color> {
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
let (adjustments, blend_ifs) = item
.attribute::<Effects>(ATTR_EFFECTS)
.map(|effects| (adjustments(effects), content_blend_ifs(effects)))
.unwrap_or_default();
let shown = filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill);
let mut item = item;
*item.element_mut() = shown.with_alpha(shown.a() * opacity);
// Consumed so a node passing the item on doesn't get them carried out twice where it's drawn
item.remove_attribute::<Effects>(ATTR_EFFECTS);
item.remove_attribute::<f64>(ATTR_OPACITY);
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
item
}
/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors.
/// A gradient without the effects attribute is returned as it is.
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
@@ -392,21 +351,6 @@ mod tests {
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
}
#[test]
fn a_color_parameters_fill_fades_it_beneath_its_paint_overlays_and_its_opacity_over_them() {
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::RED,
blend_mode: BlendMode::Normal,
opacity: 100.,
});
let unfilled = Item::new_from_element(Color::BLACK)
.with_attribute(ATTR_EFFECTS, Effects::from_operations([red]))
.with_attribute(ATTR_OPACITY_FILL, 0_f64);
assert!(close(gamma(*evaluate_color_parameter(unfilled.clone()).element()), [1., 0., 0., 1.]));
assert!(close(gamma(*evaluate_color_parameter(unfilled.with_attribute(ATTR_OPACITY, 0.5_f64)).element()), [1., 0., 0., 0.5]));
}
#[test]
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
use graphic_types::blend_if::BlendIfRanges;
@@ -1,6 +1,6 @@
use crate::renderer::{
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, paint_draws_by_its_colors, painted_gradient,
spread_adjusted_samples, svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, painted_gradient, spread_adjusted_samples,
svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
};
use crate::{Render, RenderSvgSegmentList, SvgRender};
use core_types::color::SRGBA8;
@@ -88,7 +88,7 @@ impl RenderExt for List<Color> {
/// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing.
/// One painted through a mask fills a pattern spanning `bounds`, which `stroke_transform` places in the painted element's space.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_fill_and_opacity`] explains.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
fn render_gradient_paint(
item: Option<ItemRef<'_, Gradient>>,
svg_defs: &mut String,
@@ -101,13 +101,14 @@ fn render_gradient_paint(
let mut stop = String::new();
let item = item?;
let (stops, settings, paint_opacity) = painted_gradient(item, for_mask)?;
let (stops, settings) = painted_gradient(item)?;
let shape = gradient_shape(item);
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
with_two_stops_at_least(shape, &mut samples);
let paint_opacity = item.paint_opacity(for_mask);
if paint_opacity < 1. {
for (_, color, _) in &mut samples {
*color = color.with_alpha(color.a() * paint_opacity);
@@ -302,11 +303,10 @@ impl RenderExt for Graphic {
target: PaintTarget,
) -> Self::Output {
let paint_attr = target.paint_attr();
let by_colors = paint_draws_by_its_colors(self);
match self {
Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
Graphic::ColorList(color_list) if by_colors => color_list.render(
Graphic::Color(item) => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
Graphic::ColorList(color_list) => color_list.render(
svg_defs,
user_to_document,
paint_reach,
@@ -317,11 +317,11 @@ impl RenderExt for Graphic {
render_params,
target,
),
Graphic::Gradient(item) if by_colors => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
Graphic::GradientList(gradient_list) if by_colors => gradient_list
Graphic::GradientList(gradient_list) if gradient_list.len() <= 1 => gradient_list
.render(
svg_defs,
user_to_document,
@@ -336,10 +336,7 @@ impl RenderExt for Graphic {
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
Graphic::Color(_)
| Graphic::ColorList(_)
| Graphic::Gradient(_)
| Graphic::Graphic(_)
Graphic::Graphic(_)
| Graphic::Vector(_)
| Graphic::RasterCPU(_)
| Graphic::RasterGPU(_)
+57 -520
View File
@@ -51,8 +51,7 @@ use num_traits::Zero;
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
use raster_kernels::raster_effects::adjusted_raster;
use raster_kernels::value_effects::{
BlendIfStep, adjusted_color, adjusted_gradient, adjusted_gradient_with_blend_ifs, blend_ifs_span_runs, carries_out_every_effect, filled_color_after_effects, filled_color_with_blend_ifs,
filled_gradient_after_effects,
BlendIfStep, adjusted_color, adjusted_gradient, adjusted_gradient_with_blend_ifs, blend_ifs_span_runs, color_after_effects, filled_color_with_blend_ifs, gradient_after_effects,
};
use skrifa::instance::{LocationRef, NormalizedCoord, Size};
use skrifa::outline::{DrawSettings, OutlinePen};
@@ -121,12 +120,12 @@ impl<'a, T> ItemRef<'a, T> {
}
}
/// The fill and opacity this item's opacity attributes fade it by when it serves as a paint, the fill before its effects and the opacity after them, as for any content.
/// A masker drops the fill so it cannot reach the content clipped to it.
pub(crate) fn paint_fill_and_opacity(self, for_mask: bool) -> (f32, f32) {
let fill = if for_mask { 1. } else { self.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) };
/// The alpha multiplier this item's opacity attributes apply when it serves as a paint.
/// Fill opacity fades a paint just as opacity does, but a masker drops it so it cannot reach the content clipped to it.
pub(crate) fn paint_opacity(self, for_mask: bool) -> f32 {
let opacity_fill = if for_mask { 1. } else { self.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) };
(fill as f32, self.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32)
(self.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) * opacity_fill) as f32
}
/// How the item's opacity attributes and effects apply as it renders, with `content_transform` placing its content in the space it's drawn in.
@@ -540,7 +539,6 @@ impl ItemCompositing<'_> {
// The color a solid paint draws, which is `None` for no paint, or no color at all for a paint that isn't solid
let solid_color = |paint: Option<&Graphic>| match paint {
None | Some(Graphic::None(_) | Graphic::NoneList(_)) => Some(None),
Some(paint) if !paint_draws_by_its_colors(paint) => None,
Some(Graphic::Color(item)) => Some(faded_paint_color(ItemRef::Item(item), for_mask)),
Some(Graphic::ColorList(list)) => Some(composite_paint_colors(list, for_mask)),
Some(_) => None,
@@ -2632,60 +2630,25 @@ fn rect_bounds(rect: kurbo::Rect) -> RenderBoundingBox {
RenderBoundingBox::Rectangle([DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)])
}
/// Whether a solid or gradient paint draws by its colors, with each item's effects carried out on them (see [`faded_paint_color`] and [`painted_gradient`]), which is exact
/// only where every effect changes each color on its own. Any other paint renders as content with its whole effect stack, clipped to the shape.
pub(crate) fn paint_draws_by_its_colors(paint: &Graphic) -> bool {
match paint {
// Stacked gradients can't composite into one brush
Graphic::GradientList(list) if list.len() > 1 => false,
Graphic::Color(_) | Graphic::ColorList(_) | Graphic::Gradient(_) | Graphic::GradientList(_) => !paint_has_effects_beyond_its_colors(paint),
_ => false,
}
}
/// Whether an item of a solid or gradient paint has an effect that doesn't change each color on its own (see [`carries_out_every_effect`]).
fn paint_has_effects_beyond_its_colors(paint: &Graphic) -> bool {
fn beyond_colors(effects: Option<&Effects>) -> bool {
effects.is_some_and(|effects| !carries_out_every_effect(effects))
}
fn list_beyond_colors<T>(list: &List<T>) -> bool {
(0..list.len()).any(|index| beyond_colors(list.attribute(ATTR_EFFECTS, index)))
}
match paint {
Graphic::Color(item) => beyond_colors(item.attribute(ATTR_EFFECTS)),
Graphic::Gradient(item) => beyond_colors(item.attribute(ATTR_EFFECTS)),
Graphic::ColorList(list) => list_beyond_colors(list),
Graphic::GradientList(list) => list_beyond_colors(list),
_ => false,
}
}
/// The color one paint item contributes, faded by its fill with its effects carried out over that (see [`filled_color_after_effects`]), then faded by its opacity.
/// The color one paint item contributes, with its effects carried out (see [`color_after_effects`]) and faded by its opacity attributes.
pub(crate) fn faded_paint_color(item: ItemRef<'_, Color>, for_mask: bool) -> Option<Color> {
let color = *item.element()?;
let (fill, opacity) = item.paint_fill_and_opacity(for_mask);
let mut color = *item.element()?;
if let Some(effects) = item.attribute::<Effects>(ATTR_EFFECTS) {
color = color_after_effects(color, effects);
}
let filled = match item.attribute::<Effects>(ATTR_EFFECTS) {
Some(effects) => filled_color_after_effects(color, effects, fill),
None => color.with_alpha(color.a() * fill),
};
Some(filled.with_alpha(filled.a() * opacity))
Some(color.with_alpha(color.a() * item.paint_opacity(for_mask)))
}
/// The ramp one gradient paint item contributes, faded by its fill with its effects carried out along it (see [`filled_gradient_after_effects`]), the settings to read it with,
/// and the opacity left to fade it by, which takes the fill too where there was nothing to carry out along the ramp.
pub(crate) fn painted_gradient(item: ItemRef<'_, Gradient>, for_mask: bool) -> Option<(Cow<'_, Gradient>, GradientSettings, f32)> {
/// The ramp one gradient paint item contributes, with its effects carried out along it (see [`gradient_after_effects`]), and the settings to read it with.
pub(crate) fn painted_gradient(item: ItemRef<'_, Gradient>) -> Option<(Cow<'_, Gradient>, GradientSettings)> {
let gradient = item.element()?;
let settings = gradient_settings_from_item(item);
let (fill, opacity) = item.paint_fill_and_opacity(for_mask);
let adjusted = item
.attribute::<Effects>(ATTR_EFFECTS)
.and_then(|effects| filled_gradient_after_effects(gradient, settings, effects, fill));
let adjusted = item.attribute::<Effects>(ATTR_EFFECTS).and_then(|effects| gradient_after_effects(gradient, settings, effects));
Some(match adjusted {
Some((gradient, settings)) => (Cow::Owned(gradient), settings, opacity),
None => (Cow::Borrowed(gradient), settings, opacity * fill),
Some((gradient, settings)) => (Cow::Owned(gradient), settings),
None => (Cow::Borrowed(gradient), settings),
})
}
@@ -2954,8 +2917,6 @@ pub struct RenderParams {
pub canvas_image_scale: f64,
/// The nearest ancestor's appearance, cascading to items that lack their own.
pub inherited_appearance: Option<Appearance>,
/// The frame in the document of the shape a paint fills, within which endless content painting it is seen and has its effects carried out.
pub paint_frame: Option<DAffine2>,
}
impl RenderParams {
@@ -3167,24 +3128,6 @@ fn svg_only_approximates(paint: &Graphic) -> bool {
}
}
/// Whether a solid or gradient paint rendering as content (see [`paint_draws_by_its_colors`]) takes maps or images from the GPU for its effects, which can't reach the pattern it paints through.
/// Found by rendering it as content in the document, placed by `content_transform` in the current user space.
fn svg_paint_needs_the_gpu(paint: &Graphic, render: &SvgRender, content_transform: DAffine2, render_params: &RenderParams) -> bool {
if !paint_has_effects_beyond_its_colors(paint) || !render.images_replace_markup(render_params) {
return false;
}
let mut content = SvgRender::new();
content.transform = render.transform * content_transform;
content.ancestors_reach = render.ancestors_reach;
let paint_render_params = RenderParams {
inherited_appearance: None,
..render_params.clone()
};
paint.render_svg(&mut content, &paint_render_params);
!content.effect_maps.is_empty() || !content.deferred_images.is_empty()
}
/// Maps a gradient's `transform` into the frame handed to the renderer: most shapes keep the full matrix (so a
/// non-uniform transform makes an ellipse), while linear is reduced to the equivalent non-sheared gradient line (the
/// axis projected onto the band normal) so the iso-color bands keep following a sheared transform, which Vello can
@@ -3632,9 +3575,9 @@ fn apollonian_geometry(parameters: &GradientApollonian) -> vello_gpu::PencilGeom
}
/// How Vello draws one gradient paint item, in the space `multiplied_transform` places it in.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_fill_and_opacity`] explains.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
fn create_gradient_paint(gradient_item: ItemRef<'_, Gradient>, multiplied_transform: &DAffine2, for_mask: bool) -> Option<VelloGradientPaint> {
let (stops, settings, paint_opacity) = painted_gradient(gradient_item, for_mask)?;
let (stops, settings) = painted_gradient(gradient_item)?;
let shape = gradient_shape(gradient_item);
let gradient_transform: DAffine2 = gradient_item.attribute_cloned_or_default(ATTR_TRANSFORM);
@@ -3642,6 +3585,7 @@ fn create_gradient_paint(gradient_item: ItemRef<'_, Gradient>, multiplied_transf
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
with_two_stops_at_least(shape, &mut samples);
let paint_opacity = gradient_item.paint_opacity(for_mask);
if paint_opacity < 1. {
// A stopless ramp gets its black stop downstream, too late to be faded, so it needs one here instead
if samples.is_empty() {
@@ -3920,11 +3864,7 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st
if next_clips && mask_state.is_none() {
let uuid = generate_uuid();
let (base, nested) = clipping_base(element, transform, item.attribute::<Effects>(ATTR_EFFECTS));
let mask_type = if base.can_reduce_to_clip_path(render_params.inherited_appearance.as_ref()) {
MaskType::Clip
} else {
MaskType::Mask
};
let mask_type = if base.can_reduce_to_clip_path() { MaskType::Clip } else { MaskType::Mask };
// A base nested to take the item's effects carries the item's transform itself
let base_transform = if nested { DAffine2::IDENTITY } else { transform };
@@ -4841,22 +4781,6 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, opacity:
let override_paint_order = can_draw_aligned_stroke && can_use_paint_order;
let use_face_fill = item.fills_faces();
// Fills drawn as paths of their own composite with the stroke's path as one shape, through a group taking its opacity and blend mode
if (needs_separate_alignment_fill || use_face_fill) && (opacity < 1. || blend_mode != BlendMode::default()) {
let group_attributes = |attributes: &mut SvgRenderAttrs| {
if opacity < 1. {
attributes.push("opacity", opacity.to_string());
}
if blend_mode != BlendMode::default() {
attributes.push("style", blend_mode.render());
}
};
render.parent_tag("g", group_attributes, |render| {
render_vector_shape_svg(item, vector, 1., BlendMode::default(), folded, render, render_params)
});
return;
}
if needs_separate_alignment_fill && !wants_stroke_below {
emit_svg_fill_path(
render,
@@ -4965,7 +4889,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, opacity:
let paint_bounds = match paint {
Graphic::Gradient(item) if gradient_draws_masked(ItemRef::Item(item)) => stroke_bounds_matrix,
Graphic::GradientList(list) if list.len() == 1 && gradient_draws_masked(ItemRef::ListItem(list, 0)) => stroke_bounds_matrix,
Graphic::Color(_) | Graphic::Gradient(_) | Graphic::ColorList(_) | Graphic::GradientList(_) if paint_draws_by_its_colors(paint) => bounds_matrix,
Graphic::Color(_) | Graphic::Gradient(_) | Graphic::ColorList(_) | Graphic::GradientList(_) => bounds_matrix,
_ => stroke_bounds_matrix,
};
paint.render(
@@ -5046,11 +4970,7 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask
if next_clips && clip_mask_state.is_none() {
let masker = Graphic::VectorList(vector_clipping_base(vector, item));
let mask_type = if masker.can_reduce_to_clip_path(render_params.inherited_appearance.as_ref()) {
MaskType::Clip
} else {
MaskType::Mask
};
let mask_type = if masker.can_reduce_to_clip_path() { MaskType::Clip } else { MaskType::Mask };
let uuid = generate_uuid();
let mut masker_svg = SvgRender::new();
@@ -5092,14 +5012,12 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask
None => compositing,
};
// A fill or drawn stroke SVG only approximates, like a gradient of Apollonian circles or a paint with effects needing the GPU, takes the GPU's image of the item
let item_transform = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let approximates = |paint: &Graphic| svg_only_approximates(paint) || svg_paint_needs_the_gpu(paint, render, item_transform, render_params);
// A fill or drawn stroke SVG only approximates, like a gradient of Apollonian circles, takes the GPU's image of the item
let svg_approximates_paint = render_params.render_mode != RenderMode::Outline
&& appearance().is_some_and(|appearance| {
let FillAndStroke { fill_paint, stroke_paint, stroke, .. } = appearance.fill_and_stroke();
let strokes = stroke.is_some_and(|stroke| stroke.weight() > 0.);
fill_paint.is_some_and(approximates) || (strokes && stroke_paint.is_some_and(approximates))
fill_paint.is_some_and(svg_only_approximates) || (strokes && stroke_paint.is_some_and(svg_only_approximates))
});
let compositing = ItemCompositing {
svg_approximates_paint,
@@ -5339,13 +5257,6 @@ fn render_vector_item_to_vello(
let use_layer = can_draw_aligned_stroke;
// A paint is seen within the shape it fills, or the stroke's outline for the stroke
let painting_within = |bounds: [DVec2; 2]| RenderParams {
paint_frame: Some(frame_of_bounds(bounds, multiplied_transform)),
..paint_render_params.clone()
};
let stroke_bounds = || element.stroke_inclusive_bounding_box_with_transform(element_paths, DAffine2::IDENTITY, stroke).unwrap_or(layer_bounds);
let do_fill_path = |scene: &mut VelloSceneBuilder, path: &kurbo::BezPath, fill_rule: peniko::Fill| {
let Some(paint) = fill_paint else { return };
@@ -5371,18 +5282,15 @@ fn render_vector_item_to_vello(
});
};
let by_colors = paint_draws_by_its_colors(paint);
match paint {
Graphic::None(_) | Graphic::NoneList(_) => (),
Graphic::Color(item) if by_colors => solid_fill(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
Graphic::ColorList(list) if by_colors => solid_fill(scene, composite_paint_colors(list, render_params.for_mask)),
Graphic::Gradient(item) if by_colors => gradient_fill(scene, ItemRef::Item(item)),
Graphic::GradientList(list) if by_colors => gradient_fill(scene, ItemRef::ListItem(list, 0)),
Graphic::Color(item) => solid_fill(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
Graphic::ColorList(list) => solid_fill(scene, composite_paint_colors(list, render_params.for_mask)),
Graphic::Gradient(item) => gradient_fill(scene, ItemRef::Item(item)),
// Stacked gradients cannot be composited into one brush, so they fall through to the clipped texture path
Graphic::GradientList(list) if list.len() <= 1 => gradient_fill(scene, ItemRef::ListItem(list, 0)),
// Any other graphic content paints as a texture clipped to the path
Graphic::Color(_)
| Graphic::ColorList(_)
| Graphic::Gradient(_)
| Graphic::GradientList(_)
Graphic::GradientList(_)
| Graphic::Graphic(_)
| Graphic::Vector(_)
| Graphic::RasterCPU(_)
@@ -5396,9 +5304,8 @@ fn render_vector_item_to_vello(
| Graphic::GraphicList(_)
| Graphic::TextList(_)
| Graphic::StrokeList(_) => {
// The paint composites within its own layer, as in its SVG pattern, so its blend modes act on nothing beneath the shape
scene.push_layer(fill_rule, peniko::Mix::Normal, 1., kurbo::Affine::new(element_transform.to_cols_array()), path);
paint.render_to_vello(scene, multiplied_transform, &painting_within(layer_bounds));
scene.push_clip_layer(fill_rule, kurbo::Affine::new(element_transform.to_cols_array()), path);
paint.render_to_vello(scene, multiplied_transform, paint_render_params);
scene.pop_layer();
}
};
@@ -5469,18 +5376,15 @@ fn render_vector_item_to_vello(
});
};
let by_colors = paint_draws_by_its_colors(paint);
match paint {
Graphic::None(_) | Graphic::NoneList(_) => (),
Graphic::Color(item) if by_colors => solid_stroke(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
Graphic::ColorList(list) if by_colors => solid_stroke(scene, composite_paint_colors(list, render_params.for_mask)),
Graphic::Gradient(item) if by_colors => gradient_stroke(scene, ItemRef::Item(item)),
Graphic::GradientList(list) if by_colors => gradient_stroke(scene, ItemRef::ListItem(list, 0)),
Graphic::Color(item) => solid_stroke(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
Graphic::ColorList(list) => solid_stroke(scene, composite_paint_colors(list, render_params.for_mask)),
Graphic::Gradient(item) => gradient_stroke(scene, ItemRef::Item(item)),
// Stacked gradients cannot be composited into one brush, so they fall through to the clipped texture path
Graphic::GradientList(list) if list.len() <= 1 => gradient_stroke(scene, ItemRef::ListItem(list, 0)),
// Any other graphic content paints as a texture clipped to the stroked region
Graphic::Color(_)
| Graphic::ColorList(_)
| Graphic::Gradient(_)
| Graphic::GradientList(_)
Graphic::GradientList(_)
| Graphic::Graphic(_)
| Graphic::Vector(_)
| Graphic::RasterCPU(_)
@@ -5496,9 +5400,8 @@ fn render_vector_item_to_vello(
| Graphic::StrokeList(_) => {
let stroked = placed.stroke_outline(&stroke, 0.01);
// The paint composites within its own layer, as for the fill
scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., element_affine, &*stroked);
paint.render_to_vello(scene, multiplied_transform, &painting_within(stroke_bounds()));
scene.push_clip_layer(peniko::Fill::NonZero, element_affine, &*stroked);
paint.render_to_vello(scene, multiplied_transform, paint_render_params);
scene.pop_layer();
}
};
@@ -6422,10 +6325,10 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende
render_edgeless_color_svg(item, render, &compositing, color, render_params);
}
/// Whether endless content carries out its `effects` over the area in view rather than on its paint: for those reading the pixels around each one (like filters, warps, blurs, and Pixelate),
/// which change a ramp and some even a flat color, and for Blend Ifs spanning effect runs, which the paint's layers can't carry from one run to the next.
/// Whether endless content carries out its `effects` over the area in view rather than on its paint: for filters and warps, which change even a flat color,
/// and for Blend Ifs spanning effect runs, which the paint's layers can't carry from one run to the next.
fn carried_out_in_view(effects: &Effects) -> bool {
effects.operations().any(|operation| operation.reads_pixels_around() && !operation.changes_nothing()) || blend_ifs_span_runs(effects)
graphic_types::filters::has_filters(effects) || warps_change_endless_content(effects) || blend_ifs_span_runs(effects)
}
/// Whether any of the effects is a warp that changes something, which it does within its frame even to endless content.
@@ -6647,15 +6550,7 @@ fn draw_endless_item_with_effects(
if layer {
scene.push_viewport_layer(peniko::BlendMode::new(blend_mode.to_peniko(), peniko::Compose::SrcOver), compositing.opacity);
}
// Effects relative to the content's extent, like Pixelate, take the region it's seen in, being the shape it paints or else the view
let view = scene.view().inverse().transform_rect_bbox(kurbo::Rect::new(0., 0., scene.width() as f64, scene.height() as f64));
let frame = (render_params.paint_frame).unwrap_or_else(|| frame_of_bounds([DVec2::new(view.x0, view.y0), DVec2::new(view.x1, view.y1)], DAffine2::IDENTITY));
let bounds = match render_params.paint_frame {
Some(frame) => RenderBoundingBox::Rectangle((frame * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()),
None => RenderBoundingBox::Infinite,
};
compositing.draw_with_effects(scene, parent_transform, render_params, || bounds, || Some(frame), 0., draw);
compositing.draw_with_effects(scene, parent_transform, render_params, || RenderBoundingBox::Infinite, || None, 0., draw);
if layer {
scene.pop_layer();
}
@@ -6727,33 +6622,26 @@ fn gradient_control_interior_is_clickable(gradient_form: GradientForm) -> bool {
gradient_form == GradientForm::Radial
}
/// For thumbnails the gradient fills a finite rect around the footprint's document area in the user space, with a 1-unit margin for the `as u32` truncation of `Footprint::resolution`.
/// For thumbnails the gradient fills a finite rect at the footprint's document space bounds, with a 1-unit margin to cover the `as u32` truncation of `Footprint::resolution`.
/// The viewBox crops the overshoot. Canvas rendering keeps the polyline path since Chrome rejects rects larger than ~20 million.
fn gradient_thumbnail_rect(render: &SvgRender, render_params: &RenderParams) -> Option<(DVec2, DVec2)> {
if !render_params.thumbnail {
return None;
fn gradient_thumbnail_rect(render_params: &RenderParams) -> Option<(DVec2, DVec2)> {
if render_params.thumbnail {
let truncated_size = render_params.footprint.resolution.as_dvec2();
let margin = DVec2::ONE;
Some((render_params.footprint.transform.translation - margin / 2., truncated_size + margin))
} else {
None
}
let truncated_size = render_params.footprint.resolution.as_dvec2();
let margin = DVec2::ONE;
let (min, size) = (render_params.footprint.transform.translation - margin / 2., truncated_size + margin);
if !render.transform.matrix2.determinant().is_normal() {
return Some((min, size));
}
// Content drawn in a space of its own, like a paint's pattern, takes the area mapped into that space
let [min, max] = (render.transform.inverse() * Quad::from_box([min, min + size])).bounding_box();
Some((min, max - min))
}
/// Emits one item of gradient content as SVG.
fn render_gradient_item_svg(item: ItemRef<'_, Gradient>, render: &mut SvgRender, render_params: &RenderParams) {
render_gradient_item_svg_with_thumbnail_rect(item, gradient_thumbnail_rect(render, render_params), render, render_params);
render_gradient_item_svg_with_thumbnail_rect(item, gradient_thumbnail_rect(render_params), render, render_params);
}
impl Render for List<Gradient> {
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
let thumbnail_rect = gradient_thumbnail_rect(render, render_params);
let thumbnail_rect = gradient_thumbnail_rect(render_params);
render_list_items_svg(self, render, render_params, |index, render| {
render_gradient_item_svg_with_thumbnail_rect(ItemRef::ListItem(self, index), thumbnail_rect, render, render_params)
@@ -12227,7 +12115,7 @@ mod tests {
// A gradient's dark start is hidden and its light end shown
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]));
stamp_effect(&mut gradient, blend_if());
let (ramp, settings, _) = painted_gradient(ItemRef::Item(&gradient), false).expect("the Blend If fades the ramp");
let (ramp, settings) = painted_gradient(ItemRef::Item(&gradient)).expect("the Blend If fades the ramp");
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
assert!(ramp.evaluate(0., settings).a() < 1e-6, "the start is hidden");
assert!(close(ramp.evaluate(1., settings), Color::WHITE), "the end shows");
@@ -12253,363 +12141,12 @@ mod tests {
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]));
stamp_effect(&mut gradient, invert());
let (ramp, settings, _) = painted_gradient(ItemRef::Item(&gradient), false).unwrap();
let (ramp, settings) = painted_gradient(ItemRef::Item(&gradient)).unwrap();
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
assert!(close(ramp.evaluate(0., settings), Color::WHITE), "the start turns white");
assert!(close(ramp.evaluate(1., settings), Color::BLACK), "the end turns black");
}
#[test]
fn paints_fade_by_their_fill_before_their_adjustments_and_by_their_opacity_after() {
use graphic_types::{Effect, EffectOperation, stamp_effect};
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
let make_opaque = || Effect::new(&EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. }));
let half_filled = |opacity: f64| Item::new_from_element(Color::RED).with_attribute(ATTR_OPACITY_FILL, 0.5).with_attribute(ATTR_OPACITY, opacity);
// Making a half-filled red opaque restores what the fill faded, though not what the opacity fades after it
let mut red = half_filled(1.);
stamp_effect(&mut red, make_opaque());
assert!(close(faded_paint_color(ItemRef::Item(&red), false).unwrap(), Color::RED));
let mut faded_red = half_filled(0.5);
stamp_effect(&mut faded_red, make_opaque());
assert!(close(faded_paint_color(ItemRef::Item(&faded_red), false).unwrap(), Color::RED.with_alpha(0.5)));
// Without effects, both fade it, though a masker drops the fill
assert!(close(faded_paint_color(ItemRef::Item(&half_filled(0.5)), false).unwrap(), Color::RED.with_alpha(0.25)));
assert!(close(faded_paint_color(ItemRef::Item(&half_filled(0.5)), true).unwrap(), Color::RED.with_alpha(0.5)));
// A gradient's ramp takes the fill where its effects are carried out along it, leaving only the opacity to fade it by, and otherwise leaves both
let half_filled_ramp = || Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_OPACITY_FILL, 0.5);
let mut opaque_ramp = half_filled_ramp();
stamp_effect(&mut opaque_ramp, make_opaque());
let (ramp, settings, opacity) = painted_gradient(ItemRef::Item(&opaque_ramp), false).unwrap();
assert!(ramp.evaluate(0.5, settings).a() > 1. - 1e-6 && opacity == 1., "{opacity}");
let plain_ramp = half_filled_ramp();
let (ramp, settings, opacity) = painted_gradient(ItemRef::Item(&plain_ramp), false).unwrap();
assert!(ramp.evaluate(0.5, settings).a() > 1. - 1e-6 && opacity == 0.5, "{opacity}");
}
/// A square 100 across covered by a `paint`.
fn square_covered_by(coverage: Coverage, paint: Graphic) -> List<Vector> {
use kurbo::Shape;
let mut square = Vector::item_from_bezpath(&kurbo::Rect::new(0., 0., 100., 100.).to_path(0.1));
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
List::new_from_item(square)
}
/// A paint of `element` with the effect `operations` stamped on it.
fn effected_paint<T>(element: T, operations: impl IntoIterator<Item = graphic_types::EffectOperation>) -> Item<T> {
Item::new_from_element(element).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations))
}
fn speckle(amount: f64) -> graphic_types::EffectOperation {
graphic_types::EffectOperation::Speckle {
amount,
distribution: graphic_types::NoiseDistribution::Uniform,
monochromatic: false,
seed: 0,
}
}
#[test]
fn paints_draw_by_their_colors_only_where_every_effect_changes_each_color_alone() {
use graphic_types::EffectOperation;
let invert = EffectOperation::Adjustment(Adjustment::Invert);
let mut darks_hidden = BlendIfRanges::default();
darks_hidden.content.gray.falloff_start = 50.;
darks_hidden.content.gray.range_start = 50.;
let mut underlying_darks_hidden = BlendIfRanges::default();
underlying_darks_hidden.underlying.gray.falloff_start = 50.;
underlying_darks_hidden.underlying.gray.range_start = 50.;
let twirl = EffectOperation::Twirl {
angle: 90.,
transform: DAffine2::from_scale(DVec2::splat(100.)),
};
let pixelate = EffectOperation::Pixelate { cell_size: 10., offset: DVec2::ZERO };
// Adjustments, Blend Ifs reading the paint's own colors, and effects changing nothing keep to the fast path
for operations in [vec![], vec![invert.clone()], vec![EffectOperation::BlendIf(Box::new(darks_hidden)), invert.clone()], vec![speckle(0.)]] {
assert!(paint_draws_by_its_colors(&Graphic::Color(effected_paint(Color::BLACK, operations.clone()))), "{operations:?}");
assert!(paint_draws_by_its_colors(&Graphic::Gradient(effected_paint(Gradient::default(), operations))));
}
// Effects reading neighbors, positions, or what lies beneath don't, nor do lists holding a paint with one
for operation in [speckle(50.), twirl, pixelate, EffectOperation::BlendIf(Box::new(underlying_darks_hidden))] {
assert!(!paint_draws_by_its_colors(&Graphic::Color(effected_paint(Color::BLACK, [operation.clone()]))), "{operation:?}");
assert!(!paint_draws_by_its_colors(&Graphic::Gradient(effected_paint(Gradient::default(), [operation.clone()]))));
let colors: List<Color> = [Item::new_from_element(Color::WHITE), effected_paint(Color::BLACK, [operation])].into_iter().collect();
assert!(!paint_draws_by_its_colors(&Graphic::ColorList(colors)));
}
// So an inverted fill stays a plain color in SVG, without a pattern
let mut render = SvgRender::new();
square_covered_by(Coverage::new_fill(), Graphic::Color(effected_paint(Color::BLACK, [invert]))).render_svg(&mut render, &RenderParams::default());
let svg = render.svg.to_svg_string();
assert!(svg.contains(r##"fill="#ffffff""##) && !render.svg_defs.contains("<pattern"), "{svg}");
}
#[test]
fn svg_paints_with_effects_beyond_their_colors_render_as_content_clipped_to_the_shape() {
use glam::UVec2;
use graphic_types::EffectOperation;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
let in_view = RenderParams {
view: Some(Footprint {
resolution: UVec2::new(160, 160),
..Default::default()
}),
..Default::default()
};
let stroke = |align: StrokeAlign| Coverage::new_stroke(&Stroke { align, ..Stroke::new(10.) });
let coverages = || [Coverage::new_fill(), stroke(StrokeAlign::Center), stroke(StrokeAlign::Inside), stroke(StrokeAlign::Outside)];
// A grained color or a twirled gradient, which SVG's filters can't draw in a pattern, takes the GPU's image of the vector
let twirl = EffectOperation::Twirl {
angle: 180.,
transform: DAffine2::from_scale_angle_translation(DVec2::splat(100.), 0., DVec2::splat(50.)),
};
let gradient = || Gradient::from(vec![Color::BLACK, Color::WHITE]);
for paint in [Graphic::Color(effected_paint(Color::RED, [speckle(50.)])), Graphic::Gradient(effected_paint(gradient(), [twirl]))] {
for coverage in coverages() {
let images = deferred_images_of(Graphic::VectorList(square_covered_by(coverage, paint.clone())), &in_view);
assert!(
matches!(
&images[..],
[DeferredImage {
content: DeferredContent::Item(Graphic::Vector(_)),
..
}]
),
"{} images",
images.len()
);
}
}
// A masked gradient, which SVG draws, paints natively through a pattern holding the mask
let mut left_half = Vector::item_from_bezpath(&kurbo::Shape::to_path(&kurbo::Rect::new(0., 0., 50., 100.), 0.1));
left_half.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE))));
let mask = EffectOperation::Mask {
mask: Graphic::VectorList(List::new_from_item(left_half)),
mode: graphic_types::MaskMode::Luminance,
density: 100.,
feather: 0.,
invert: false,
};
for coverage in coverages() {
let mut render = SvgRender::new();
square_covered_by(coverage, Graphic::Gradient(effected_paint(gradient(), [mask.clone()]))).render_svg(&mut render, &in_view);
let (svg, defs) = (render.svg.to_svg_string(), render.svg_defs);
assert!(render.deferred_images.is_empty() && render.effect_maps.is_empty(), "{svg}");
assert!(svg.contains(r##"="url(#pattern-"##) && defs.contains("<pattern") && defs.contains("<mask"), "{svg}\n{defs}");
}
// Where no image can replace markup, the grained color paints through a pattern spanning the stroke as well as the fill
let thumbnail = RenderParams { thumbnail: true, ..in_view };
let pattern_width = |coverage: Coverage| {
let mut render = SvgRender::new();
square_covered_by(coverage, Graphic::Color(effected_paint(Color::RED, [speckle(50.)]))).render_svg(&mut render, &thumbnail);
assert!(render.deferred_images.is_empty(), "{}", render.svg.to_svg_string());
let defs = render.svg_defs;
let pattern = &defs[defs.find("<pattern").expect("the paint draws through a pattern")..];
let width = pattern.split(r#"width=""#).nth(1).and_then(|rest| rest.split('"').next()).expect("the pattern has a width");
width.parse::<f64>().unwrap()
};
assert_eq!(pattern_width(Coverage::new_fill()), 100.);
for (align, stroked_width) in [(StrokeAlign::Center, 110.), (StrokeAlign::Inside, 100.), (StrokeAlign::Outside, 120.)] {
let width = pattern_width(stroke(align));
assert!(width >= stroked_width, "{align:?}: {width}");
}
}
#[test]
fn svg_endless_gradients_and_their_paints_blur_natively_and_pixelate_through_the_gpu() {
use glam::UVec2;
use graphic_types::EffectOperation;
let in_view = RenderParams {
view: Some(Footprint {
resolution: UVec2::new(160, 160),
..Default::default()
}),
..Default::default()
};
let blur = EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 4.,
box_blur: false,
gamma: false,
};
let pixelate = EffectOperation::Pixelate { cell_size: 10., offset: DVec2::ZERO };
let gradient = |operation: &EffectOperation| Graphic::Gradient(effected_paint(Gradient::from(vec![Color::BLACK, Color::WHITE]), [operation.clone()]));
let render_of = |graphic: Graphic| {
let mut render = SvgRender::new();
List::new_from_element(graphic).render_svg(&mut render, &in_view);
render
};
// A gradient layer and a square it fills blur by SVG's own filter
for graphic in [gradient(&blur), Graphic::VectorList(square_covered_by(Coverage::new_fill(), gradient(&blur)))] {
let render = render_of(graphic);
assert!(render.deferred_images.is_empty() && render.svg_defs.contains("feGaussianBlur"), "{}", render.svg_defs);
}
// SVG can't pixelate, so each takes the GPU's image of it
for graphic in [gradient(&pixelate), Graphic::VectorList(square_covered_by(Coverage::new_fill(), gradient(&pixelate)))] {
let images = render_of(graphic).deferred_images;
assert_eq!(images.len(), 1);
}
}
#[test]
fn svg_thumbnails_fill_the_patterns_of_moved_shapes_with_their_gradient_paints() {
use core_types::transform::RenderQuality;
// A square moved 500 across, filled by a blurred gradient through a pattern in the square's own space
let blur = graphic_types::EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 4.,
box_blur: false,
gamma: false,
};
let mut square = square_covered_by(Coverage::new_fill(), Graphic::Gradient(effected_paint(Gradient::from(vec![Color::BLACK, Color::WHITE]), [blur])));
square.set_attribute(ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(500., 0.)));
let thumbnail = RenderParams {
footprint: Footprint::from_bounds([DVec2::new(500., 0.), DVec2::new(600., 100.)], RenderQuality::Full),
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
square.render_svg(&mut render, &thumbnail);
let defs = render.svg_defs;
// The gradient's rectangle covers the pattern's tile, from 0 to 100 in the square's space
let pattern = &defs[defs.find("<pattern").expect("the paint draws through a pattern")..];
let rect = &pattern[pattern.find("<rect").expect("the gradient fills a rectangle")..];
let attribute = |name: &str| -> f64 { rect.split(&format!(r#" {name}=""#)).nth(1).and_then(|rest| rest.split('"').next()).unwrap().parse().unwrap() };
let (x, width) = (attribute("x"), attribute("width"));
assert!(x <= 0. && x + width >= 100., "{rect}");
}
#[test]
fn svg_shortcuts_for_opaque_or_transparent_paints_look_past_effects_that_might_change_alpha() {
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
use graphic_types::{CoverPlacement, EffectOperation};
let svg_of = |list: List<Vector>| {
let mut render = SvgRender::new();
list.render_svg(&mut render, &RenderParams::default());
(render.svg.to_svg_string(), render.svg_defs)
};
// Black faded away by a Blend If hiding the darks
let mut darks_hidden = BlendIfRanges::default();
darks_hidden.content.gray.falloff_start = 50.;
darks_hidden.content.gray.range_start = 50.;
let faded_black = || Graphic::Color(effected_paint(Color::BLACK, [EffectOperation::BlendIf(Box::new(darks_hidden))]));
// A clipping base filled with it masks what clips to it by its alpha, rather than clipping to its outline as if it were opaque
for (base_paint, clips) in [(Graphic::Color(Item::new_from_element(Color::BLACK)), true), (faded_black(), false)] {
let mut list = square_covered_by(Coverage::new_fill(), base_paint);
let clipped = square_covered_by(Coverage::new_fill(), Graphic::Color(Item::new_from_element(Color::RED)));
list.push(clipped.into_iter().next().unwrap().with_attribute(ATTR_CLIPPING_MASK, true));
let (svg, defs) = svg_of(list);
assert_eq!(defs.contains("<clipPath"), clips, "{svg}\n{defs}");
assert_eq!(defs.contains("<mask"), !clips, "{svg}\n{defs}");
}
// An outside stroke beneath it isn't hidden within the shape by drawing the fill over it, which would leave its inner half showing through
for (fill_paint, paint_order) in [(Graphic::Color(Item::new_from_element(Color::BLACK)), true), (faded_black(), false)] {
let mut list = square_covered_by(Coverage::new_fill(), fill_paint);
let red = Graphic::Color(Item::new_from_element(Color::RED));
let outside = Stroke {
align: StrokeAlign::Outside,
..Stroke::new(10.)
};
let mut appearance = list.attribute::<Appearance>(ATTR_APPEARANCE, 0).unwrap().clone();
appearance.replace_or_insert(Coverage::new_stroke(&outside), red, DAffine2::IDENTITY, CoverPlacement::Above);
list.set_attribute(ATTR_APPEARANCE, 0, appearance);
let (svg, defs) = svg_of(list);
assert_eq!(svg.contains("paint-order"), paint_order, "{svg}");
assert_eq!(defs.contains("alignment-"), !paint_order, "{svg}\n{defs}");
}
// A transparent stroke made opaque is drawn
let transparent_red = Color::from_rgbaf32_unchecked(1., 0., 0., 0.);
let made_opaque = Graphic::Color(effected_paint(transparent_red, [EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. })]));
let (svg, _) = svg_of(square_covered_by(Coverage::new_stroke(&Stroke::new(4.)), made_opaque));
assert!(svg.contains(r##"stroke="#ff0000""##), "{svg}");
}
#[test]
fn svg_fills_drawn_apart_from_an_aligned_stroke_share_the_shapes_opacity_and_blend_mode() {
use graphic_types::CoverPlacement;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
// A translucent fill can't hide an outside stroke's inner half, so it's drawn as a path of its own
let mut list = square_covered_by(Coverage::new_fill(), Graphic::Color(Item::new_from_element(Color::RED.with_alpha(0.5))));
let outside = Stroke {
align: StrokeAlign::Outside,
..Stroke::new(10.)
};
let mut appearance = list.attribute::<Appearance>(ATTR_APPEARANCE, 0).unwrap().clone();
appearance.replace_or_insert(
Coverage::new_stroke(&outside),
Graphic::Color(Item::new_from_element(Color::BLUE)),
DAffine2::IDENTITY,
CoverPlacement::Above,
);
list.set_attribute(ATTR_APPEARANCE, 0, appearance);
list.set_attribute(ATTR_OPACITY, 0, 0.5);
list.set_attribute(ATTR_BLEND_MODE, 0, BlendMode::Multiply);
let mut render = SvgRender::new();
list.render_svg(&mut render, &RenderParams::default());
let svg = render.svg.to_svg_string();
// Both paths lie in one group taking the opacity and blend mode, which neither takes again
let group = &svg[svg.find("<g").expect("the paths are grouped")..];
assert!(group.matches("<path").count() == 2, "{svg}");
assert!(svg.matches(r#" opacity="0.5""#).count() == 1 && group.starts_with(r#"<g opacity="0.5""#), "{svg}");
assert!(svg.matches("multiply").count() == 1, "{svg}");
}
#[test]
fn svg_clipping_bases_filled_by_an_inherited_paint_clip_by_its_alpha() {
use graphic_types::EffectOperation;
// Black faded away by a Blend If hiding the darks, or plain opaque black
let mut darks_hidden = BlendIfRanges::default();
darks_hidden.content.gray.falloff_start = 50.;
darks_hidden.content.gray.range_start = 50.;
let faded_black = Graphic::Color(effected_paint(Color::BLACK, [EffectOperation::BlendIf(Box::new(darks_hidden))]));
let opaque_black = Graphic::Color(Item::new_from_element(Color::BLACK));
// A group's fill cascades to a square without its own, which a red square clips to
for (inherited_fill, clips) in [(opaque_black, true), (faded_black, false)] {
let mut squares = square_covered_by(Coverage::new_fill(), Graphic::default());
squares.set_attribute(ATTR_APPEARANCE, 0, Appearance::default());
let clipped = square_covered_by(Coverage::new_fill(), Graphic::Color(Item::new_from_element(Color::RED)));
squares.push(clipped.into_iter().next().unwrap().with_attribute(ATTR_CLIPPING_MASK, true));
let group = Item::new_from_element(Graphic::VectorList(squares)).with_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), inherited_fill));
let mut render = SvgRender::new();
List::new_from_item(group).render_svg(&mut render, &RenderParams::default());
let (svg, defs) = (render.svg.to_svg_string(), render.svg_defs);
assert_eq!(defs.contains("<clipPath"), clips, "{svg}\n{defs}");
assert_eq!(defs.contains("<mask"), !clips, "{svg}\n{defs}");
}
}
#[test]
fn svg_endless_colors_carry_out_filters_over_the_area_in_view_in_nested_groups() {
use glam::UVec2;
@@ -211,7 +211,7 @@ fn a_clip_path_becomes_a_hidden_clipper_beneath_the_content_it_clips() -> Result
let content = converted(r#"<clipPath id="clip"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)"><rect width="8" height="8"/></g>"#)?;
let clipped = group(&content, 0);
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
assert_eq!(clipped.and_then(|clipped| clipped.attribute::<f64>(ATTR_OPACITY_FILL, 0)), Some(&0.));
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
Ok(())
@@ -314,7 +314,7 @@ fn a_mask_region_that_cuts_its_content_clips_the_masked_content() -> Result<(),
let within_region = group(&content, 0).and_then(|masked| masked.element(1));
assert!(within_region.is_some_and(Graphic::had_clip_enabled));
let clipped = within_region.and_then(Graphic::as_graphic_list);
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
Ok(())
}
@@ -1715,250 +1715,6 @@ fn endless_layers_clip_to_the_shape_beneath_them() {
}
}
/// Black on the left half of a render 140 across and white on the right, with nothing between, its effects measured in its own space spanning the render.
fn hard_edged_gradient() -> core_types::list::Item<graphic_types::vector_types::gradient::Gradient> {
use core_types::list::{ATTR_GRADIENT_INTERPOLATION, Item};
use core_types::{ATTR_TRANSFORM, Color};
use graphic_types::vector_types::gradient::{Gradient, GradientInterpolation};
Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE, Color::WHITE]))
.with_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Stepped)
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::splat(140.)))
}
/// Pixelate with cells 10 across in a gradient's space spanning a render 140 across.
fn pixelated_by_tens() -> graphic_types::EffectOperation {
graphic_types::EffectOperation::Pixelate {
cell_size: 10. / 140.,
offset: glam::DVec2::ZERO,
}
}
/// A Gaussian blur of radius 4 in a gradient's space spanning a render 140 across.
fn blurred_by_four() -> graphic_types::EffectOperation {
graphic_types::EffectOperation::Blur {
radius_mask: graphic_types::Graphic::default(),
radius: 4. / 140.,
box_blur: false,
gamma: false,
}
}
#[test]
fn endless_gradients_pixelate_and_blur_over_the_view() {
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_INTERPOLATION};
use core_types::{ATTR_TRANSFORM, Color};
use graphic_types::vector_types::gradient::{Gradient, GradientInterpolation};
use graphic_types::{Effects, Graphic};
use rendering::{Render, RenderParams};
let size = UVec2::new(140, 140);
let draw = |graphic: &Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
// A smooth black-to-white ramp across the render bands into cells 10 across, each one color
let ramp = core_types::list::Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
.with_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Linear)
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::splat(140.)))
.with_attribute(ATTR_EFFECTS, Effects::from_operations([pixelated_by_tens()]));
let Some(pixelated) = draw(&Graphic::Gradient(ramp)) else { return };
for cell in 1..13 {
let first = pixel(&pixelated, size, cell * 10 + 1, 70);
assert!((cell * 10 + 2..cell * 10 + 9).all(|x| pixel(&pixelated, size, x, 70) == first), "cell {cell} is one color");
assert_ne!(first, pixel(&pixelated, size, cell * 10 + 11, 70), "cell {cell} differs from the next");
}
// The hard edge halfway across softens, from gray just beside it to black and white farther away
let blurred = draw(&Graphic::Gradient(hard_edged_gradient().with_attribute(ATTR_EFFECTS, Effects::from_operations([blurred_by_four()])))).unwrap();
let gray = |x: u32| pixel(&blurred, size, x, 70)[0];
assert!(gray(66) > 10 && gray(66) < 128 && gray(73) > 128 && gray(73) < 245, "{} and {}", gray(66), gray(73));
assert!(gray(50) < 3 && gray(90) > 252, "{} and {}", gray(50), gray(90));
}
#[test]
fn paints_with_effects_beyond_their_colors_show_them_within_the_shape() {
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
use glam::DVec2;
use graphic_types::vector_types::gradient::Gradient;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, MaskMode, NoiseDistribution, Vector};
use rendering::{Render, RenderParams};
use vello_gpu::kurbo::Shape;
let size = UVec2::new(140, 140);
let draw = |graphic: &Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
let square_covered_by = |coverage: Coverage, paint: Graphic| {
let mut square = Vector::item_from_bezpath(&Rect::new(20., 20., 120., 120.).to_path(0.1));
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
Graphic::VectorList(List::new_from_item(square))
};
let close = |a: [u8; 4], b: [u8; 4]| a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 2);
// A color and a gradient across the render, grained, twirled, and masked to its left half, with the gradient's effects measured in its own space that spans the render
let color = || Item::new_from_element(GraphicColor::from_gamma_srgb_channels(0.8, 0.2, 0.4, 1.));
let gradient = || Item::new_from_element(Gradient::from(vec![GraphicColor::BLACK, GraphicColor::WHITE])).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(140.)));
let speckle = EffectOperation::Speckle {
amount: 50.,
distribution: NoiseDistribution::Uniform,
monochromatic: false,
seed: 0,
};
let twirl = EffectOperation::Twirl {
angle: 180.,
transform: DAffine2::from_scale_angle_translation(DVec2::splat(100. / 140.), 0., DVec2::splat(0.5)),
};
let mut left_half = Vector::item_from_bezpath(&Rect::new(0., 0., 0.5, 1.).to_path(0.001));
left_half.set_attribute(
ATTR_APPEARANCE,
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))),
);
let mask = EffectOperation::Mask {
mask: Graphic::VectorList(List::new_from_item(left_half)),
mode: MaskMode::Luminance,
density: 100.,
feather: 0.,
invert: false,
};
let effected = |operation: &EffectOperation| Effects::from_operations([operation.clone()]);
let paints = [
("speckled color", Graphic::Color(color().with_attribute(ATTR_EFFECTS, effected(&speckle))), Graphic::Color(color())),
(
"speckled gradient",
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&speckle))),
Graphic::Gradient(gradient()),
),
(
"twirled gradient",
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&twirl))),
Graphic::Gradient(gradient()),
),
(
"masked gradient",
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&mask))),
Graphic::Gradient(gradient()),
),
(
"pixelated gradient",
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&pixelated_by_tens()))),
Graphic::Gradient(gradient()),
),
(
"blurred hard-edged gradient",
Graphic::Gradient(hard_edged_gradient().with_attribute(ATTR_EFFECTS, effected(&blurred_by_four()))),
Graphic::Gradient(hard_edged_gradient()),
),
];
for (name, paint, plain) in paints {
// The paint drawn as a layer filling everything, which the shape's paint matches where it covers it
let Some(layer) = draw(&paint) else { return };
// A fill shows the effect within the square and nothing past it
let filled = draw(&square_covered_by(Coverage::new_fill(), paint.clone())).unwrap();
let plain_filled = draw(&square_covered_by(Coverage::new_fill(), plain.clone())).unwrap();
for (x, y) in (22..118).flat_map(|x| (22..118).map(move |y| (x, y))) {
assert!(close(pixel(&filled, size, x, y), pixel(&layer, size, x, y)), "{name}: the fill matches the layer at ({x}, {y})");
}
for (x, y) in [(10, 70), (130, 70), (70, 10), (70, 130)] {
assert_eq!(pixel(&filled, size, x, y)[3], 0, "{name}: nothing is filled at ({x}, {y}), past the square");
}
let changed = (0..filled.len()).filter(|&index| !close(filled[index], plain_filled[index])).count();
assert!(changed > 500, "{name}: the effect changes the fill at {changed} pixels");
// A stroke shows it within its band, wherever its alignment places it along the square's left edge
for (align, band) in [(StrokeAlign::Center, 16..24), (StrokeAlign::Inside, 21..29), (StrokeAlign::Outside, 11..19)] {
let stroked = draw(&square_covered_by(Coverage::new_stroke(&Stroke { align, ..Stroke::new(10.) }), paint.clone())).unwrap();
for (x, y) in band.clone().flat_map(|x| (40..100).map(move |y| (x, y))) {
assert!(
close(pixel(&stroked, size, x, y), pixel(&layer, size, x, y)),
"{name}, {align:?}: the stroke matches the layer at ({x}, {y})"
);
}
for x in [band.start - 4, band.end + 3] {
assert_eq!(pixel(&stroked, size, x, 70)[3], 0, "{name}, {align:?}: nothing is stroked at ({x}, 70), past the band");
}
}
}
}
#[test]
fn a_half_filled_paint_made_opaque_looks_the_same_whether_drawn_by_its_color_or_as_content() {
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
use core_types::{ATTR_OPACITY_FILL, Color as GraphicColor};
use graphic_types::adjustment::Adjustment;
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector};
use rendering::{Render, RenderParams};
use vello_gpu::kurbo::Shape;
let size = UVec2::new(140, 140);
let filled_square = |operations: Vec<EffectOperation>| {
let paint = Item::new_from_element(GraphicColor::RED)
.with_attribute(ATTR_OPACITY_FILL, 0.5)
.with_attribute(ATTR_EFFECTS, Effects::from_operations(operations));
let mut square = Vector::item_from_bezpath(&Rect::new(20., 20., 120., 120.).to_path(0.1));
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::Color(paint)));
Graphic::VectorList(List::new_from_item(square))
};
// The fill fades the red before Make Opaque restores it, alike when a blur of the flat color draws it as content
let make_opaque = EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
let blur = EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 4.,
box_blur: false,
gamma: false,
};
for operations in [vec![make_opaque.clone()], vec![make_opaque, blur]] {
let count = operations.len();
let Some(pixels) = render(size, |scene| filled_square(operations.clone()).render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
for (x, y) in [(70, 70), (25, 70), (115, 115)] {
assert_eq!(pixel(&pixels, size, x, y), [255, 0, 0, 255], "{count} effects at ({x}, {y})");
}
}
}
#[test]
fn a_paints_own_blend_mode_composites_within_the_paint_rather_than_onto_what_lies_beneath_the_shape() {
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
use core_types::{ATTR_BLEND_MODE, Color as GraphicColor};
use graphic_types::vector_types::vector::style::Stroke;
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector};
use rendering::{Render, RenderParams};
use vello_gpu::kurbo::Shape;
let size = UVec2::new(140, 140);
let shape = |rect: Rect, coverage: Coverage, paint: Graphic| {
let mut vector = Vector::item_from_bezpath(&rect.to_path(0.1));
vector.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
Graphic::VectorList(List::new_from_item(vector))
};
let background = shape(Rect::new(0., 0., 140., 140.), Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::RED)));
// Green multiplied with nothing beneath it in its paint stays green, whatever lies beneath the shape, as in SVG's pattern, though a blur of it draws it as content
let blur = EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 4.,
box_blur: false,
gamma: false,
};
let green = Item::new_from_element(GraphicColor::GREEN)
.with_attribute(ATTR_BLEND_MODE, BlendMode::Multiply)
.with_attribute(ATTR_EFFECTS, Effects::from_operations([blur]));
for (coverage, inside) in [(Coverage::new_fill(), (70, 70)), (Coverage::new_stroke(&Stroke::new(10.)), (20, 70))] {
let square = shape(Rect::new(20., 20., 120., 120.), coverage, Graphic::Color(green.clone()));
let Some(pixels) = render(size, |scene| {
background.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
square.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
}) else {
return;
};
let (x, y) = inside;
assert_eq!(pixel(&pixels, size, x, y), [0, 255, 0, 255], "green at ({x}, {y})");
}
}
#[test]
fn feathers_fade_the_content_to_nothing_at_its_edges() {
use graphic_types::EffectOperation;
+12 -35
View File
@@ -3,13 +3,13 @@ use core_types::blending::BlendMode;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{Item, List};
use core_types::transfer_curve::TransferCurve;
use core_types::{ATTR_TRANSFORM, Color, Ctx};
use core_types::{ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color, Ctx};
use glam::{DAffine2, DVec2};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectOperation, Generator, GlowSource, GlowTechnique, Graphic, Vector, linked_to_content, paint_with_envelope_effects, stamp_effect,
};
use raster_kernels::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
use raster_kernels::{evaluate_color_effects, evaluate_gradient_effects};
use vector_types::Gradient;
use vector_types::vector::style::{StrokeAlign, initial_gradient_transform_for_bounding_box};
@@ -99,7 +99,7 @@ fn drop_shadow<T>(
stamp_effect(
&mut content,
Effect::new(&EffectOperation::DropShadow {
color: evaluate_color_parameter(color).into_element(),
color: evaluate_color_effects(color).into_element(),
blend_mode: *blend_mode.element(),
angle: *angle.element(),
distance: *distance.element(),
@@ -155,7 +155,7 @@ fn inner_shadow<T>(
stamp_effect(
&mut content,
Effect::new(&EffectOperation::InnerShadow {
color: evaluate_color_parameter(color).into_element(),
color: evaluate_color_effects(color).into_element(),
blend_mode: *blend_mode.element(),
angle: *angle.element(),
distance: *distance.element(),
@@ -468,7 +468,7 @@ fn satin<T>(
stamp_effect(
&mut content,
Effect::new(&EffectOperation::Satin {
color: evaluate_color_parameter(color).into_element(),
color: evaluate_color_effects(color).into_element(),
blend_mode: *blend_mode.element(),
angle: *angle.element(),
distance: *distance.element(),
@@ -620,9 +620,9 @@ fn bevel_and_emboss<T: PaintFitBounds>(
soften: *soften.element(),
angle: *angle.element(),
altitude: *altitude.element(),
highlight_color: evaluate_color_parameter(highlight_color).into_element(),
highlight_color: evaluate_color_effects(highlight_color).into_element(),
highlight_blend_mode: *highlight_blend_mode.element(),
shadow_color: evaluate_color_parameter(shadow_color).into_element(),
shadow_color: evaluate_color_effects(shadow_color).into_element(),
shadow_blend_mode: *shadow_blend_mode.element(),
texture,
texture_depth: *texture_depth.element(),
@@ -661,7 +661,11 @@ fn paint_overlay<T: PaintFitBounds>(
let paint = match paint_with_envelope_effects(paint) {
Graphic::None(_) | Graphic::NoneList(_) => return content,
// A solid paint becomes a bare color, so its own opacity fades the color's alpha
Graphic::Color(color) => Graphic::from(evaluate_color_parameter(color).into_element()),
Graphic::Color(color) => {
let opacity = color.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) * color.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.);
let color = evaluate_color_effects(color).into_element();
Graphic::from(color.with_alpha(color.a() * opacity as f32))
}
paint => paint_with_placement(&content, paint, _has_transform, _transform),
};
@@ -771,33 +775,6 @@ mod test {
assert!(color.r() > 0.05 && color.r() < 0.95, "half the black paint leaves {color:?}");
}
#[test]
fn drop_shadow_fades_its_color_by_the_colors_own_opacity() {
use core_types::ATTR_OPACITY;
use core_types::transfer_curve::TransferCurve;
use graphic_types::EffectOperation;
let number = |value: f64| Item::new_from_element(value);
let shadowed = super::drop_shadow(
(),
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::WHITE))),
Item::new_from_element(Color::BLACK).with_attribute(ATTR_OPACITY, 0.5_f64),
BlendMode::Normal.into(),
number(120.),
number(5.),
number(0.),
number(5.),
Item::new_from_element(TransferCurve::default()),
true.into(),
);
let operation = shadowed.attribute::<Effects>(ATTR_EFFECTS).and_then(|effects| effects.operations().next());
let Some(EffectOperation::DropShadow { color, .. }) = operation else {
panic!("expected a drop shadow, got {operation:?}")
};
assert_eq!(color, Color::BLACK.with_alpha(0.5));
}
type PaintEffectNode<T> = fn(Item<T>, Graphic, bool, DAffine2) -> Item<T>;
fn paint_effect_nodes<T: super::PaintFitBounds>() -> [(&'static str, PaintEffectNode<T>); 3] {
+1 -1
View File
@@ -53,7 +53,7 @@ fn create_artboard<T: IntoGraphicList>(
let normalized_location = location.min(location + dimensions);
let normalized_dimensions = dimensions.abs().max(DVec2::ONE);
let background = raster_kernels::evaluate_color_parameter(background).into_element();
let background = raster_kernels::evaluate_color_effects(background).into_element();
// Name is not stored here, it's resolved live from the parent layer's display name
Ok(Item::new_from_element(Artboard::new(content))
+1 -17
View File
@@ -1142,9 +1142,7 @@ fn flatten_gradient(_: impl Ctx, content: List<Graphic>) -> List<Gradient> {
/// Constructs a gradient from a `Color[]`, where each color becomes a gradient stop. A `position` attribute on the colors places their stops along the ramp and a `midpoint` attribute skews each transition, while colors carrying neither are distributed evenly across the 0 to 1 range.
#[node_macro::node(category("Gradient"), icon("NodeColorsToGradient"), name("Colors to Gradient"))]
fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Item<Gradient> {
// Each color's own effects and opacity go into it before it becomes a stop
let colors: List<Color> = colors.into_flattened_list::<Color>().into_iter().map(value_effects::evaluate_color_parameter).collect();
Item::new_from_element(Gradient::from(colors))
Item::new_from_element(Gradient::from(colors.into_flattened_list::<Color>()))
}
/// Unwraps a gradient into a `Color[]` of its stops, keeping any `position` and `midpoint` attributes that place them along the ramp. Attributes belonging to the gradient as a whole (like spread and interpolation), rather than its individual color stops, are not preserved.
@@ -1425,18 +1423,4 @@ mod test {
expected.set_positions(&[0.25, 0.75]);
assert_eq!(colors_to_gradient((), embed_colors(colors)).element(), &expected, "each stop should keep its place");
}
#[test]
fn colors_to_gradient_carries_out_each_colors_effects_and_opacity() {
use core_types::ATTR_OPACITY;
use graphic_types::{Adjustment, EffectOperation};
let inverted = Item::new_from_element(Color::BLACK).with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::Adjustment(Adjustment::Invert)]));
let half_opacity = Item::new_from_element(Color::RED).with_attribute(ATTR_OPACITY, 0.5_f64);
let colors: List<Color> = [inverted, half_opacity].into_iter().collect();
let gradient = colors_to_gradient((), embed_colors(colors));
let expected = Gradient::from(vec![Color::WHITE, Color::RED.with_alpha(0.5)]);
assert_eq!(gradient.element(), &expected, "the inverted black should become a white stop, and the half-opaque red a half-alpha one");
}
}
+3 -4
View File
@@ -14,7 +14,7 @@ use graphic_types::adjustment::{
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_kernels::{evaluate_color_effects, evaluate_gradient_effects};
use raster_types::{CPU, GPU, Image, Raster};
use vector_types::Gradient;
@@ -414,7 +414,7 @@ fn black_and_white<T>(
) -> Item<T> {
let settings = BlackAndWhiteSettings {
use_tint: use_tint.into_element(),
tint: evaluate_color_parameter(tint).into_element(),
tint: evaluate_color_effects(tint).into_element(),
reds: reds.into_element(),
yellows: yellows.into_element(),
greens: greens.into_element(),
@@ -1417,7 +1417,7 @@ fn photo_filter<T>(
adjust(
image,
Adjustment::PhotoFilter {
color: evaluate_color_parameter(color).into_element(),
color: evaluate_color_effects(color).into_element(),
density: density.into_element(),
preserve_luminosity: preserve_luminosity.into_element(),
},
@@ -1460,7 +1460,6 @@ mod _graphene_hash_impls {
#[cfg(test)]
mod tests {
use super::*;
use raster_kernels::evaluate_color_effects;
/// Matched to within one 8-bit level.
fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
+2 -18
View File
@@ -18,8 +18,8 @@ fn mix_colors(
#[default(100.)]
opacity: Item<f64>,
) -> Item<Color> {
let mut under = raster_kernels::evaluate_color_parameter(under);
let over = raster_kernels::evaluate_color_parameter(over);
let mut under = raster_kernels::evaluate_color_effects(under);
let over = raster_kernels::evaluate_color_effects(over);
let blend_mode = blend_mode.into_element();
let opacity = (opacity.into_element() / 100.) as f32;
@@ -41,20 +41,4 @@ mod test {
assert_eq!(mixed, Color::from_rgbaf32_unchecked(0.25, 0., 0.75, 1.));
}
#[test]
fn mix_colors_fades_each_color_by_its_opacity() {
use core_types::ATTR_OPACITY;
use core_types::list::Item;
let half_opacity = |color: Color| Item::new_from_element(color).with_attribute(ATTR_OPACITY, 0.5_f64);
let mix = |under: Item<Color>, over: Item<Color>| super::mix_colors((), under, over, BlendMode::Normal.into(), 100_f64.into());
assert_eq!(*mix(Color::TRANSPARENT.into(), half_opacity(Color::RED)).element(), Color::RED.with_alpha(0.5));
// The under color's opacity goes into its alpha, so the result carries none to fade it twice
let mixed = mix(half_opacity(Color::BLUE), Color::TRANSPARENT.into());
assert_eq!(*mixed.element(), Color::BLUE.with_alpha(0.5));
assert_eq!(mixed.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 1.);
}
}