Compare commits

...
36 changed files with 3652 additions and 430 deletions

No files matched your search

Generated
+3 -3
View File
@@ -8084,7 +8084,7 @@ dependencies = [
[[package]] [[package]]
name = "vello_common" name = "vello_common"
version = "0.3.0" version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"fearless_simd", "fearless_simd",
@@ -8099,7 +8099,7 @@ dependencies = [
[[package]] [[package]]
name = "vello_gpu" name = "vello_gpu"
version = "0.3.0" version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"hashbrown 0.17.1", "hashbrown 0.17.1",
@@ -8113,7 +8113,7 @@ dependencies = [
[[package]] [[package]]
name = "vello_gpu_shaders" name = "vello_gpu_shaders"
version = "0.3.0" version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
dependencies = [ dependencies = [
"naga", "naga",
"wesl", "wesl",
+3 -3
View File
@@ -315,6 +315,6 @@ debug = true
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2 fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2
# TODO: Remove these once the fork's fixes are upstreamed and released # TODO: Remove these once the fork's fixes are upstreamed and released
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" } vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" } vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" } vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
@@ -0,0 +1,63 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
GradientModel(GradientModel),
GradientDirection(GradientDirection),
}
#[derive(Serialize, Deserialize)]
enum GradientModel {
Standard,
}
#[derive(Serialize, Deserialize)]
enum GradientDirection {
Along,
}
/// 'Fill' gained the model and direction it gives the gradient it paints, set to the Standard model and the Along direction a gradient without them already has.
#[migration("graphene_core::vector::FillNode"@2 => @3)]
pub fn fill_v2(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// The model and the direction.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::GradientModel(GradientModel::Standard)), literal(Tagged::GradientDirection(GradientDirection::Along))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&FillV2, &contract());
check_undo(&FillV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_the_default_model_and_direction() {
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&FillV2);
let fill = fixture.add(decl!("graphene_core::vector::FillNode"@2), inputs.clone());
let migrated = fixture.migrate(&FillV2).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, fill), Some(decl!("graphene_core::vector::FillNode"@3)));
assert_eq!(fixture.inputs(&migrated, fill), expected);
}
}
@@ -1,6 +1,7 @@
//! Migrations of the nodes in `graphene_core`. //! Migrations of the nodes in `graphene_core`.
mod fill_v1; mod fill_v1;
mod fill_v2;
mod passthrough_from_read_attribute_gradient_form_node; mod passthrough_from_read_attribute_gradient_form_node;
mod passthrough_from_upload_texture_node; mod passthrough_from_upload_texture_node;
mod renames; mod renames;
+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.; pub const CURVATURE_COMB_MAX_TOOTH_LENGTH: f64 = 2000.;
// GRADIENT TOOL // 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.; 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_MIN: f64 = 0.01;
pub const GRADIENT_MIDPOINT_MAX: f64 = 0.99; pub const GRADIENT_MIDPOINT_MAX: f64 = 0.99;
pub const GRADIENT_STOP_MIN_VIEWPORT_GAP: f64 = 10.; 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 // PEN TOOL
pub const CREATE_CURVE_THRESHOLD: f64 = 5.; pub const CREATE_CURVE_THRESHOLD: f64 = 5.;
@@ -31,8 +31,8 @@ use graphene_std::vector::misc::{
WeldMethod, WeldMethod,
}; };
use graphene_std::vector::style::{ use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, DashPattern, FillChoice, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign,
StrokeJoin, StrokeCap, StrokeJoin,
}; };
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector}; use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{ use graphene_std::{
@@ -470,6 +470,7 @@ macro_rules! inspectable_types {
Item<BlendMode>, Item<BlendMode>,
Item<GradientForm>, Item<GradientForm>,
Item<GradientModel>, Item<GradientModel>,
Item<GradientDirection>,
Item<GradientSpread>, Item<GradientSpread>,
Item<GradientSpace>, Item<GradientSpace>,
Item<GradientHueDirection>, Item<GradientHueDirection>,
@@ -1286,6 +1287,7 @@ impl_table_item_layout_for_choice_enum!(
MinimumMaximumMode, MinimumMaximumMode,
GradientForm, GradientForm,
GradientModel, GradientModel,
GradientDirection,
GradientSpread, GradientSpread,
GradientSpace, GradientSpace,
GradientHueDirection, GradientHueDirection,
@@ -1482,6 +1484,7 @@ macro_rules! known_item_types {
BlendMode, BlendMode,
GradientForm, GradientForm,
GradientModel, GradientModel,
GradientDirection,
GradientSpread, GradientSpread,
GradientSpace, GradientSpace,
GradientHueDirection, GradientHueDirection,
@@ -7,7 +7,7 @@ use graph_craft::document::NodeId;
use graphene_std::Color; use graphene_std::Color;
use graphene_std::raster::BlendMode; use graphene_std::raster::BlendMode;
use graphene_std::text::{Font, TypesettingConfig}; use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke}; use graphene_std::vector::style::{GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::{Gradient, VectorModificationType}; use graphene_std::vector::{Gradient, VectorModificationType};
use std::sync::Arc; use std::sync::Arc;
@@ -57,6 +57,19 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier, layer: LayerNodeIdentifier,
gradient_form: GradientForm, gradient_form: GradientForm,
}, },
GradientCurvatureSet {
layer: LayerNodeIdentifier,
/// The start and end curvatures.
curvatures: [f64; 2],
},
GradientModelSet {
layer: LayerNodeIdentifier,
model: GradientModel,
},
GradientDirectionSet {
layer: LayerNodeIdentifier,
direction: GradientDirection,
},
GradientSpreadSet { GradientSpreadSet {
layer: LayerNodeIdentifier, layer: LayerNodeIdentifier,
gradient_spread: GradientSpread, gradient_spread: GradientSpread,
@@ -86,6 +86,21 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.gradient_form_set(gradient_form); modify_inputs.gradient_form_set(gradient_form);
} }
} }
GraphOperationMessage::GradientCurvatureSet { layer, curvatures } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_curvature_set(curvatures);
}
}
GraphOperationMessage::GradientModelSet { layer, model } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_model_set(model);
}
}
GraphOperationMessage::GradientDirectionSet { layer, direction } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_direction_set(direction);
}
}
GraphOperationMessage::GradientSpreadSet { layer, gradient_spread } => { GraphOperationMessage::GradientSpreadSet { layer, gradient_spread } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) { if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_spread_set(gradient_spread); 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::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*; use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{ 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 glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::ResourceId; use graph_craft::application_io::resource::ResourceId;
@@ -15,7 +16,7 @@ use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, list}; use graph_craft::{ProtoNodeIdentifier, list};
use graphene_std::raster::BlendMode; use graphene_std::raster::BlendMode;
use graphene_std::text::{Font, TypesettingConfig}; use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke}; use graphene_std::vector::style::{GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType}; use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
use graphene_std::{Artboard, Color, Graphic}; use graphene_std::{Artboard, Color, Graphic};
use kurbo::BezPath; use kurbo::BezPath;
@@ -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 // 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 {
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));
&& curvatures.is_some_and(|curvatures| GradientForm::from_curvatures(curvatures) != Some(gradient_form))
{
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let [start_curvature, end_curvature] = gradient_form.curvatures();
self.set_input_with_refresh(
InputConnector::node(fill_node_id, StartCurvatureInput),
NodeInput::value(TaggedValue::Number(start_curvature), false),
true,
);
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end_curvature), false), true);
} }
self.responses.add(NodeGraphMessage::RunDocumentGraph); 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 /// 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. /// paint over the stroke. This hops the stroke back downstream so it keeps painting above by default.
fn restore_default_stroke_order(&mut self) { fn restore_default_stroke_order(&mut self) {
@@ -776,27 +780,95 @@ 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 /// 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. /// 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) { 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}; use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
let Some(output_layer) = self.get_output_layer() else { return }; let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface); 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 { let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
return; return;
}; };
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) 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 }; let Some(current) = gradient_curvature_values(node) else { return };
if GradientForm::from_curvatures(curvatures) == Some(gradient_form) { if already_written(current) {
return; 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, 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); self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
} }
/// Set the model of the layer's gradient, as [`Self::gradient_choice_set`] sets a choice.
pub fn gradient_model_set(&mut self, model: GradientModel) {
use graphene_std::NodeParameter;
use graphene_std::math_nodes::gradient_model;
let value = TaggedValue::GradientModel(model);
let fill_input = graphene_std::vector::fill::ModelInput::INDEX;
self.gradient_choice_set(fill_input, gradient_model::IDENTIFIER, gradient_model::ModelInput::INDEX, value, model == GradientModel::default());
}
/// Set the direction of the layer's gradient, as [`Self::gradient_choice_set`] sets a choice.
pub fn gradient_direction_set(&mut self, direction: GradientDirection) {
use graphene_std::NodeParameter;
use graphene_std::math_nodes::gradient_direction;
let value = TaggedValue::GradientDirection(direction);
let fill_input = graphene_std::vector::fill::DirectionInput::INDEX;
self.gradient_choice_set(
fill_input,
gradient_direction::IDENTIFIER,
gradient_direction::DirectionInput::INDEX,
value,
direction == GradientDirection::default(),
);
}
/// Set a choice of how the layer's gradient is drawn: in the Fill node's input at `fill_input` where the Fill holds the gradient as a value, or else in the input at
/// `node_input` of the last node of this `identifier` in the chain, inserting one only for a value other than the default. A choice the graph feeds is left as it is.
fn gradient_choice_set(&mut self, fill_input: usize, identifier: ProtoNodeIdentifier, node_input: usize, value: TaggedValue, is_default: bool) {
let Some(output_layer) = self.get_output_layer() else { return };
let (node_id, input_index) = match get_fill_node_id_with_direct_fill_input(output_layer, self.network_interface) {
Some(fill_node_id) => (fill_node_id, fill_input),
None => {
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, !is_default) else {
return;
};
(node_id, node_input)
}
};
let node = self.network_interface.document_network().nodes.get(&node_id);
let current = node.and_then(|node| node.inputs.get(input_index)).and_then(NodeInput::as_non_exposed_value);
if current.is_some_and(|current| *current != value) {
self.set_input_with_refresh(InputConnector::node_at_index(node_id, input_index), NodeInput::value(value, false), false);
}
}
/// Set the spread on the chain's gradient value, which is where the ramp carries it. /// Set the spread on the chain's gradient value, which is where the ramp carries it.
pub fn gradient_spread_set(&mut self, gradient_spread: GradientSpread) { pub fn gradient_spread_set(&mut self, gradient_spread: GradientSpread) {
let Some(output_layer) = self.get_output_layer() else { return }; let Some(output_layer) = self.get_output_layer() else { return };
@@ -37,8 +37,8 @@ use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod, ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
}; };
use graphene_std::vector::style::{ use graphene_std::vector::style::{
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, FillChoice, Gradient, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops,
StrokeCap, StrokeJoin, build_transform_with_y_preservation, StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
}; };
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification}; use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector}; use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
@@ -435,6 +435,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
// ========================= // =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientModel>(x) => enum_choice::<GradientModel>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GradientModel>(x) => enum_choice::<GradientModel>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientDirection>(x) => enum_choice::<GradientDirection>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
@@ -1,8 +1,8 @@
use crate::consts::{ 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, 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, 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, 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,
SKEW_TRIANGLE_SIZE, 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::overlays::utility_functions::hex_to_rgba_u8;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; 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::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::misc::point_to_dvec2; 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::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::{self, BezPath, ParamCurve};
use kurbo::{Affine, PathSeg}; use kurbo::{Affine, PathSeg};
use std::borrow::Cow; 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)); 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>) { pub fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
let color = owned(color); let color = owned(color);
self.record(move |overlays| overlays.line(start, end, color.as_deref(), thickness)); 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())); 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>) { pub fn manipulator_anchor(&mut self, position: DVec2, selected: bool, color: Option<&str>) {
let color = owned(color); let color = owned(color);
self.record(move |overlays| overlays.manipulator_anchor(position, selected, color.as_deref())); 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)); self.record(move |overlays| overlays.gradient_color_stop(position, emphasis, &color, small));
} }
pub fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) { /// 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.
self.record(move |overlays| overlays.gradient_midpoint(position, emphasis, angle)); 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) { 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); 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>) { fn line(&mut self, start: DVec2, end: DVec2, color: Option<&str>, thickness: Option<f64>) {
self.dashed_line(start, end, color, thickness, None, None, None) 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>) { 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 transform = self.get_transform();
let position = self.snap_to_physical_pixel_center(position); let position = self.snap_to_physical_pixel_center(position);
let circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.); 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.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &circle);
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(stroke), None, &circle);
self.scene
.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(color.unwrap_or(COLOR_OVERLAY_BLUE)), None, &circle);
} }
fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) { fn hover_manipulator_handle(&mut self, position: DVec2, selected: bool) {
@@ -860,7 +898,7 @@ impl OverlayContextInternal {
GizmoEmphasis::Active => 1., GizmoEmphasis::Active => 1.,
}; };
let stroke_width = radius_offset * 2. + 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 mut draw_circle = |radius: f64, width: Option<f64>, color: &str| {
let circle = kurbo::Circle::new((position.x, position.y), radius); 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); draw_circle(radius, Some(stroke_width), COLOR_OVERLAY_WHITE);
} }
fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, angle: f64) { fn gradient_midpoint(&mut self, position: DVec2, emphasis: GizmoEmphasis, color: &str, angle: f64) {
let transform = self.get_transform();
let position = position.round() - DVec2::splat(0.5); 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 // Grown for emphasis with a thicker white border, as a color stop's dot is
let (sin, cos) = angle.sin_cos(); let radius_offset = match emphasis {
let rotate = |dx: f64, dy: f64| DVec2::new(dx * cos - dy * sin, dx * sin + dy * cos); GizmoEmphasis::Regular => 0.,
GizmoEmphasis::Hovered => 0.5,
let top = rotate(0., -GRADIENT_MIDPOINT_DIAMOND_RADIUS); GizmoEmphasis::Active => 1.,
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.),
}; };
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(fill), None, &path); let stroke_width = radius_offset * 2. + 1.;
self.scene.stroke(&kurbo::Stroke::new(stroke_width), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &path);
// 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) { fn resize_handle(&mut self, position: DVec2, rotation: f64) {
@@ -975,7 +975,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve"); let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let fill_node = &network.nodes[&node_id]; let fill_node = &network.nodes[&node_id];
assert_eq!(fill_node.inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape"); assert_eq!(fill_node.inputs.len(), 10, "the legacy Fill should upgrade to the 10-input shape");
let paint = fill_node.input(graphene_std::vector::fill::PaintInput); let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
assert!( assert!(
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })), matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
@@ -1033,7 +1033,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve"); let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let fill_node = &network.nodes[&node_id]; let fill_node = &network.nodes[&node_id];
assert_eq!(fill_node.inputs.len(), 8, "the eight-input Fill should come out in the modern shape, which also has eight inputs"); assert_eq!(fill_node.inputs.len(), 10, "the eight-input Fill should come out in the modern 10-input shape");
let curvatures = [graphene_std::vector::fill::StartCurvatureInput::INDEX, graphene_std::vector::fill::EndCurvatureInput::INDEX].map(|index| fill_node.inputs[index].as_value().cloned()); let curvatures = [graphene_std::vector::fill::StartCurvatureInput::INDEX, graphene_std::vector::fill::EndCurvatureInput::INDEX].map(|index| fill_node.inputs[index].as_value().cloned());
assert_eq!( assert_eq!(
curvatures, curvatures,
@@ -5663,8 +5663,19 @@ mod tests {
let node = &document.network_interface.document_network().nodes[&fill_id]; let node = &document.network_interface.document_network().nodes[&fill_id];
let values: Vec<_> = node.inputs[4..].iter().map(|input| input.as_value().cloned()).collect(); let values: Vec<_> = node.inputs[4..].iter().map(|input| input.as_value().cloned()).collect();
let expected = [TaggedValue::Number(-1.), TaggedValue::Number(0.5), TaggedValue::Bool(true), TaggedValue::DAffine2(placement)].map(Some); let expected = [
assert_eq!(values, expected, "the form should become its curvatures before the placement"); TaggedValue::Number(-1.),
TaggedValue::Number(0.5),
TaggedValue::Bool(true),
TaggedValue::DAffine2(placement),
TaggedValue::GradientModel(Default::default()),
TaggedValue::GradientDirection(Default::default()),
]
.map(Some);
assert_eq!(
values, expected,
"the form should become its curvatures before the placement, followed by the default model and direction"
);
} }
// A Fill that held the radial form in its input before the transform ones opens with that form's curvatures, painting as a Fill given the form now does // A Fill that held the radial form in its input before the transform ones opens with that form's curvatures, painting as a Fill given the form now does
@@ -5709,6 +5720,7 @@ mod tests {
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_START_CURVATURE), gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_START_CURVATURE),
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_END_CURVATURE), gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_END_CURVATURE),
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_MODEL), gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_MODEL),
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_DIRECTION),
gradient.attribute_cloned_or_default(graphene_std::ATTR_TRANSFORM), gradient.attribute_cloned_or_default(graphene_std::ATTR_TRANSFORM),
)), )),
_ => None, _ => None,
@@ -5749,7 +5761,7 @@ mod tests {
let form = NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false); let form = NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false);
let mut old_inputs = NodeTemplate { let mut old_inputs = NodeTemplate {
inputs: [&inputs[..4], &[form], &inputs[6..]].concat(), inputs: [&inputs[..4], &[form], &inputs[6..8]].concat(),
..Default::default() ..Default::default()
}; };
document.network_interface.replace_inputs(&fill_id, &[], &mut old_inputs); document.network_interface.replace_inputs(&fill_id, &[], &mut old_inputs);
@@ -0,0 +1,454 @@
//! Geometry of the Gradient tool's gizmos, in gradient space, where the gradient line runs from the start point at the origin to the end
//! point at (1, 0). Each end's contour passes through its endpoint with its center on the line, set by its curvature, as described
//! in [`graphene_std::vector::gradient_standard`].
use glam::{DAffine2, DVec2};
use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature};
use std::f64::consts::{FRAC_PI_2, PI};
/// The farthest a drawn contour bows from its chords between the points it's drawn through, in viewport pixels.
const CONTOUR_SAG_TOLERANCE: f64 = 0.25;
/// The most chords a contour is drawn with.
const CONTOUR_MAX_CHORDS: usize = 1024;
/// One of the gradient line's two ends, each with its own contour.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GradientEnd {
Start,
End,
}
impl GradientEnd {
/// Its index in a `[start, end]` pair of curvatures.
pub fn index(self) -> usize {
match self {
Self::Start => 0,
Self::End => 1,
}
}
/// Its endpoint in gradient space.
pub fn endpoint(self) -> DVec2 {
match self {
Self::Start => DVec2::ZERO,
Self::End => DVec2::X,
}
}
/// Which way along the gradient line points toward the other end, which a positive curvature bows this end's contour toward.
fn inward(self) -> f64 {
match self {
Self::Start => 1.,
Self::End => -1.,
}
}
}
/// The center of this end's contour in gradient space for its `curvature`, or `None` for a line.
pub fn contour_center(end: GradientEnd, curvature: f64) -> Option<DVec2> {
let radius = curvature_radius(curvature);
radius.is_finite().then(|| end.endpoint() + DVec2::new(end.inward() * radius, 0.))
}
/// The curvature that centers this end's contour at `axis_position` along the gradient line, as dragging its center dot there does.
pub fn center_curvature(end: GradientEnd, axis_position: f64) -> f64 {
radius_curvature((axis_position - end.endpoint().x) * end.inward())
}
/// The curvature of this end's contour through `point`, the circle through it and the endpoint with its center on the gradient line,
/// which is the line across the gradient line where `point` lies across from the endpoint. `None` at the endpoint itself.
pub fn rim_curvature(end: GradientEnd, point: DVec2) -> Option<f64> {
let offset = point - end.endpoint();
let distance_squared = offset.length_squared();
// The inverse of the radius `|offset|² / 2 offset.x`, which stays finite where the radius doesn't
(distance_squared > 0.).then(|| (2. * offset.x * end.inward() / distance_squared).atan() / FRAC_PI_2)
}
/// The signed radius that resizes this end's contour (from its `curvature`) to bring the place on its rim nearest `grabbed` as near `pointer` as it gets,
/// both in the space `unit_to_viewport` maps to, and where that place lands there. `None` for a line or a point, which no resizing moves a place on.
pub fn rim_resized_toward(end: GradientEnd, curvature: f64, grabbed: DVec2, pointer: DVec2, unit_to_viewport: DAffine2) -> Option<(f64, DVec2)> {
let radius = curvature_radius(curvature);
if !radius.is_finite() || radius == 0. {
return None;
}
let inward = DVec2::new(end.inward(), 0.);
// Each circle through the endpoint is the others scaled about it, so the place keeps its angle around them from the endpoint, measured at the center
let to_endpoint = -radius * inward;
let to_grabbed = unit_to_viewport.inverse().transform_point2(grabbed) - end.endpoint() - radius * inward;
let angle = to_endpoint.perp_dot(to_grabbed).atan2(to_endpoint.dot(to_grabbed));
// At that angle, the place lies the radius times this from the endpoint, a line the pointer projects onto
let direction = unit_to_viewport.transform_vector2(inward - DVec2::from_angle(angle).rotate(inward));
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
let resized = (pointer - endpoint).dot(direction) / direction.length_squared();
resized.is_finite().then(|| (resized, endpoint + resized * direction))
}
/// Whether a gradient with these curvatures has a focus to move: a point for its start contour and a circle for its end contour.
pub fn has_focus(curvatures: [f64; 2]) -> bool {
let end_radius = curvature_radius(curvatures[1]);
curvature_radius(curvatures[0]) == 0. && end_radius.is_finite() && end_radius != 0.
}
/// A gradient line in the gradient space of the line it replaces, with the curvature it gives the end contour.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RefocusedLine {
pub start: DVec2,
pub end: DVec2,
pub end_curvature: f64,
}
/// The line of a gradient whose start point (its focus) moves to `focus` while its end circle from `end_curvature` stays put: from the focus through the
/// circle's center to its far side, with the end curvature keeping that circle. A focus on the center keeps `direction`. `None` unless the end is a circle.
pub fn refocused_line(focus: DVec2, end_curvature: f64, direction: DVec2) -> Option<RefocusedLine> {
let radius = curvature_radius(end_curvature);
if !radius.is_finite() || radius == 0. {
return None;
}
let (center, size) = (DVec2::new(1. - radius, 0.), radius.abs());
let to_center = center - focus;
let distance = to_center.length();
let direction = if distance > 0. { to_center / distance } else { direction.try_normalize()? };
Some(RefocusedLine {
start: focus,
end: center + direction * size,
end_curvature: radius_curvature(size / (distance + size)),
})
}
/// The transform placing a gradient along `line`, given in the gradient space of the `old` transform. Its frame turns and scales uniformly within
/// that space, so a contour that's a circle there keeps its shape, even where `old` stretches it into an ellipse.
pub fn transform_along(old: DAffine2, line: RefocusedLine) -> DAffine2 {
let x_axis = line.end - line.start;
old * DAffine2::from_cols(x_axis, x_axis.perp(), line.start)
}
/// One side of the gradient line, across which its perpendicular axis points one way or the other.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LineSide {
Positive,
Negative,
}
impl LineSide {
/// Which way across the gradient line its perpendicular axis points to reach this side.
pub fn sign(self) -> f64 {
match self {
Self::Positive => 1.,
Self::Negative => -1.,
}
}
}
/// The semi-minor axis to this side of this end's circle from its `curvature`, from the circle's center a radius across the gradient line to where
/// a handle stretching the gradient across its line sits, in gradient space. `None` for a line or a point.
pub fn aspect_axis(end: GradientEnd, curvature: f64, side: LineSide) -> Option<[DVec2; 2]> {
let radius = curvature_radius(curvature).abs();
let center = contour_center(end, curvature).filter(|_| radius > 0.)?;
Some([center, center + DVec2::new(0., side.sign() * radius)])
}
/// The transform stretched across its line so the point `handle` in its gradient space lies as far across the line as `pointer` does
/// (in the transform's output space), keeping the line and how far its perpendicular axis leans along it. `None` where it would collapse.
pub fn stretched_transform(transform: DAffine2, handle: DVec2, pointer: DVec2) -> Option<DAffine2> {
let x_axis = transform.matrix2.x_axis;
let along = x_axis.try_normalize()?;
let across = along.perp();
// The handle lies `handle.y` times the perpendicular axis's span across the line
let span_across = (pointer - transform.translation).dot(across) / handle.y;
if !(span_across.abs() > 1e-9 * x_axis.length()) {
return None;
}
let y_axis = along * transform.matrix2.y_axis.dot(along) + across * span_across;
Some(DAffine2::from_cols(x_axis, y_axis, transform.translation))
}
/// The smallest factor `transform` scales any length by, the least singular value of its linear part.
fn least_scale(transform: DAffine2) -> f64 {
let [x_axis, y_axis] = [transform.matrix2.x_axis, transform.matrix2.y_axis];
let determinant = transform.matrix2.determinant().abs();
// Of the singular values `√(mean ± √(mean² - determinant²))`, the least is the determinant over the greatest, which avoids cancellation
let mean = (x_axis.length_squared() + y_axis.length_squared()) / 2.;
let greatest = (mean + (mean * mean - determinant * determinant).max(0.).sqrt()).sqrt();
if greatest > 0. { determinant / greatest } else { 0. }
}
/// Points through which this end's contour is drawn in the viewport, from `unit_to_viewport`, as far as `reach` viewport pixels from
/// its endpoint along it (or around the whole circle if that's shorter). Empty for a point, or where the transform collapses.
pub fn contour_polyline(end: GradientEnd, curvature: f64, unit_to_viewport: DAffine2, reach: f64) -> Vec<DVec2> {
let radius = curvature_radius(curvature);
let endpoint = end.endpoint();
let least_scale = least_scale(unit_to_viewport);
if radius == 0. || least_scale <= 0. {
return Vec::new();
}
// A line runs straight across the gradient line through the endpoint
if radius.is_infinite() {
let Some(direction) = unit_to_viewport.transform_vector2(DVec2::Y).try_normalize() else {
return Vec::new();
};
let viewport_endpoint = unit_to_viewport.transform_point2(endpoint);
return vec![viewport_endpoint - direction * reach, viewport_endpoint + direction * reach];
}
// Sweep from the endpoint both ways around the circle, by the angle reaching `reach` pixels at the least scale
let size = radius.abs();
let sweep = (reach / (size * least_scale)).min(PI);
// Uniform steps small enough that each chord stays within the sag tolerance, even at twice the longest axis's scale (which bounds the greatest)
let viewport_radius_bound = size * unit_to_viewport.matrix2.x_axis.length().max(unit_to_viewport.matrix2.y_axis.length()) * 2.;
let step = (8. * CONTOUR_SAG_TOLERANCE / viewport_radius_bound).sqrt();
let chords_each_way = ((sweep / step).ceil() as usize).clamp(4, CONTOUR_MAX_CHORDS / 2);
let chords = 2 * chords_each_way;
// Measured from the endpoint rather than the center, the points stay precise on huge circles
(0..=chords)
.map(|index| {
let angle = sweep * (2. * index as f64 / chords as f64 - 1.);
let half_sine = (angle / 2.).sin();
let offset = DVec2::new(2. * end.inward() * radius * half_sine * half_sine, size * angle.sin());
unit_to_viewport.transform_point2(endpoint + offset)
})
.collect()
}
/// The distance from `point` to the nearest place on the polyline through `points`, or `None` if it has none.
pub fn distance_to_polyline(points: &[DVec2], point: DVec2) -> Option<f64> {
if let [only] = points {
return Some(only.distance(point));
}
points
.windows(2)
.map(|pair| {
let (start, end) = (pair[0], pair[1]);
let along = (point - start).dot(end - start) / (end - start).length_squared();
let nearest = if along.is_finite() { start.lerp(end, along.clamp(0., 1.)) } else { start };
nearest.distance(point)
})
.min_by(f64::total_cmp)
}
#[cfg(test)]
mod tests {
use super::*;
/// Curvatures through circles of each size and bend, both lines, and the points.
fn curvatures() -> impl Iterator<Item = f64> {
(-20..=20).map(|step| step as f64 * 0.05)
}
#[test]
fn a_rim_dragged_to_a_point_takes_the_curvature_of_the_circle_through_it() {
for end in [GradientEnd::Start, GradientEnd::End] {
for point in [DVec2::new(0.3, 0.4), DVec2::new(-0.7, 1.2), DVec2::new(2.5, -0.25), DVec2::new(0.5, 3.)] {
let curvature = rim_curvature(end, point).unwrap();
// The contour of that curvature passes through the point, centered on the gradient line
let center = contour_center(end, curvature).unwrap();
assert!(center.y == 0.);
let radius = center.distance(end.endpoint());
assert!((center.distance(point) - radius).abs() < 1e-9 * radius.max(1.), "{end:?} through {point}: curvature {curvature}");
}
// Straight across from the endpoint is the line, and either side of it bends toward that side
let across = end.endpoint() + DVec2::Y;
assert_eq!(rim_curvature(end, across), Some(0.));
let inward = DVec2::new(end.inward() * 0.1, 0.);
assert!(rim_curvature(end, across + inward).unwrap() > 0.);
assert!(rim_curvature(end, across - inward).unwrap() < 0.);
// The endpoint is on every contour, so it sets none
assert_eq!(rim_curvature(end, end.endpoint()), None);
}
}
#[test]
fn a_rim_dragged_along_its_own_contour_keeps_its_curvature() {
for end in [GradientEnd::Start, GradientEnd::End] {
for curvature in curvatures().filter(|curvature| curvature.abs() != 1.) {
for point in contour_polyline(end, curvature, DAffine2::IDENTITY, 3.) {
// Every point but the endpoint sets the curvature back, as a line's points beside the endpoint do
if point.distance(end.endpoint()) < 1e-6 {
continue;
}
let found = rim_curvature(end, point).unwrap();
assert!((found - curvature).abs() < 1e-9, "{end:?} curvature {curvature} at {point}: {found}");
}
}
}
}
#[test]
fn a_center_dragged_along_the_line_takes_the_curvature_centered_there() {
for end in [GradientEnd::Start, GradientEnd::End] {
for curvature in curvatures().filter(|&curvature| curvature != 0.) {
let center = contour_center(end, curvature).unwrap();
let found = center_curvature(end, center.x);
// A point is both -1 and 1, which the drag settles at -1
let expected = if curvature.abs() == 1. { -1. } else { curvature };
assert!((found - expected).abs() < 1e-9, "{end:?} curvature {curvature}: {found}");
}
// Toward the other end bows toward it, and onto the endpoint is a point
assert!(center_curvature(end, 0.5) > 0.);
assert!(center_curvature(end, end.endpoint().x - end.inward()) < 0.);
assert_eq!(center_curvature(end, end.endpoint().x), -1.);
}
// The start contour centered at the end point, and the end contour at the start point, are each the circle of radius 1 between them
assert!((center_curvature(GradientEnd::Start, 1.) - 0.5).abs() < 1e-12);
assert!((center_curvature(GradientEnd::End, 0.) - 0.5).abs() < 1e-12);
}
/// The center and radius of the end circle of a gradient along `line`, in the gradient space `line` is given in.
fn end_circle(line: RefocusedLine) -> (DVec2, f64) {
let radius = curvature_radius(line.end_curvature);
(line.start.lerp(line.end, 1. - radius), radius.abs() * line.start.distance(line.end))
}
#[test]
fn a_moved_focus_keeps_the_end_circle_in_place() {
// The end circle of radius 0.75 centered at 0.25, with foci inside it, outside it, and behind its center
let end_curvature = radius_curvature(0.75);
let (center, radius) = (DVec2::new(0.25, 0.), 0.75);
for focus in [DVec2::new(0.1, 0.3), DVec2::new(-0.2, -0.4), DVec2::new(3., 2.), DVec2::new(0.9, 0.), DVec2::new(-5., 0.)] {
let line = refocused_line(focus, end_curvature, DVec2::X).unwrap();
assert_eq!(line.start, focus);
let (new_center, new_radius) = end_circle(line);
assert!(new_center.distance(center) < 1e-12 && (new_radius - radius).abs() < 1e-12, "focus {focus}: {line:?}");
// The line runs on through the center to the circle's far side
assert!((line.end.distance(focus) - (focus.distance(center) + radius)).abs() < 1e-12, "focus {focus}: {line:?}");
}
// A focus off the circle's line still aims the line through its center
let line = refocused_line(DVec2::new(0.25, 2.), end_curvature, DVec2::X).unwrap();
assert!(line.end.abs_diff_eq(DVec2::new(0.25, -0.75), 1e-12));
}
#[test]
fn a_focus_on_the_center_keeps_the_direction_and_makes_the_radial_form() {
let end_curvature = radius_curvature(0.75);
let line = refocused_line(contour_center(GradientEnd::End, end_curvature).unwrap(), end_curvature, DVec2::new(0., 2.)).unwrap();
assert_eq!(line.end_curvature, 0.5);
assert!(line.end.abs_diff_eq(DVec2::new(0.25, 0.75), 1e-12));
assert_eq!(
graphene_std::vector::style::GradientForm::from_curvatures([-1., line.end_curvature]),
Some(graphene_std::vector::style::GradientForm::Radial)
);
// Only an end circle has a focus to move around
assert!(has_focus([-1., 0.5]) && has_focus([1., -0.3]));
assert!(!has_focus([0., 0.5]) && !has_focus([-1., 0.]) && !has_focus([-1., 1.]));
assert_eq!(refocused_line(DVec2::ZERO, 0., DVec2::X), None);
}
#[test]
fn a_refocused_transform_keeps_an_elliptical_end_contour_in_place() {
// A radial gradient squashed to half its height and skewed, whose focus moves off its line
let old = DAffine2::from_cols(DVec2::new(100., 20.), DVec2::new(-5., 50.), DVec2::new(30., 40.));
let line = refocused_line(DVec2::new(0.3, 0.4), 0.5, DVec2::X).unwrap();
let new = transform_along(old, line);
// The end contour's points land on the same ellipse before and after (within its chords' sag), though spread differently around it
let before = contour_polyline(GradientEnd::End, 0.5, old, 1e6);
let after = contour_polyline(GradientEnd::End, line.end_curvature, new, 1e6);
for point in after {
assert!(distance_to_polyline(&before, point).unwrap() <= CONTOUR_SAG_TOLERANCE, "{point} left the ellipse");
}
assert!(new.transform_point2(DVec2::ZERO).abs_diff_eq(old.transform_point2(DVec2::new(0.3, 0.4)), 1e-9));
}
#[test]
fn each_end_circle_has_an_aspect_handle_a_radius_to_either_side_of_its_center() {
use LineSide::{Negative, Positive};
// The radial form's end circle around the start point, but not its start point
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Positive), Some([DVec2::ZERO, DVec2::Y]));
assert_eq!(aspect_axis(GradientEnd::End, 0.5, Negative), Some([DVec2::ZERO, -DVec2::Y]));
assert_eq!(aspect_axis(GradientEnd::Start, -1., Positive), None);
// Each of two crossing circles, and a huge nearly flat one
let radius = curvature_radius(0.6);
assert_eq!(aspect_axis(GradientEnd::Start, 0.6, Positive), Some([DVec2::new(radius, 0.), DVec2::new(radius, radius)]));
assert_eq!(aspect_axis(GradientEnd::End, 0.6, Negative), Some([DVec2::new(1. - radius, 0.), DVec2::new(1. - radius, -radius)]));
assert!(aspect_axis(GradientEnd::End, 1e-3, Positive).is_some_and(|[_, handle]| handle.y > 100.));
// Lines and points have none
for end in [GradientEnd::Start, GradientEnd::End] {
for curvature in [0., 1., -1.] {
for side in [Positive, Negative] {
assert_eq!(aspect_axis(end, curvature, side), None, "{end:?} curvature {curvature} {side:?}");
}
}
}
}
#[test]
fn stretching_moves_each_aspect_handle_across_the_line_and_keeps_the_line() {
// A skewed gradient, its perpendicular axis leaning along the line
let transform = DAffine2::from_cols(DVec2::new(80., 60.), DVec2::new(-50., 70.), DVec2::new(10., 20.));
let along = transform.matrix2.x_axis.normalize();
// The radial form's handles and those of two crossing circles of different sizes, each pulled to its own side of the line
let axes = [(GradientEnd::End, 0.5), (GradientEnd::Start, 0.6), (GradientEnd::End, 0.3)];
let handles = axes
.into_iter()
.flat_map(|(end, curvature)| [LineSide::Positive, LineSide::Negative].map(|side| (aspect_axis(end, curvature, side).unwrap()[1], side)));
for (handle, side) in handles {
let pointer = transform.transform_point2(DVec2::new(0.4, side.sign() * 0.7));
let stretched = stretched_transform(transform, handle, pointer).unwrap();
assert!(stretched.matrix2.determinant() * transform.matrix2.determinant() > 0., "the gradient shouldn't mirror");
for point in [DVec2::ZERO, DVec2::X] {
assert!(stretched.transform_point2(point).abs_diff_eq(transform.transform_point2(point), 1e-9));
}
// The handle lands as far across the line as the pointer, sliding only across it, and the lean along the line stays
let (old_handle, new_handle) = (transform.transform_point2(handle), stretched.transform_point2(handle));
assert!(((new_handle - transform.translation).dot(along.perp()) - (pointer - transform.translation).dot(along.perp())).abs() < 1e-9);
assert!((new_handle - old_handle).dot(along).abs() < 1e-9);
assert!((stretched.matrix2.y_axis.dot(along) - transform.matrix2.y_axis.dot(along)).abs() < 1e-9);
// Onto the line, it would collapse
assert_eq!(stretched_transform(transform, handle, transform.transform_point2(DVec2::new(0.5, 0.))), None);
}
}
#[test]
fn contours_are_drawn_through_their_endpoints_out_to_their_reach() {
let unit_to_viewport = DAffine2::from_scale_angle_translation(DVec2::new(200., 100.), 0.3, DVec2::new(40., 60.));
for end in [GradientEnd::Start, GradientEnd::End] {
let endpoint = unit_to_viewport.transform_point2(end.endpoint());
// A point draws nothing, and a line is one long chord through the endpoint
assert!(contour_polyline(end, 1., unit_to_viewport, 500.).is_empty());
let line = contour_polyline(end, 0., unit_to_viewport, 500.);
assert_eq!(line.len(), 2);
assert!(distance_to_polyline(&line, endpoint).unwrap() < 1e-9);
// A small circle is drawn whole, closing on itself, and a huge one only as far as its reach, nearly straight
let small = contour_polyline(end, 0.5, unit_to_viewport, 500.);
assert!(small.first().unwrap().distance(*small.last().unwrap()) < 1e-6);
let huge = contour_polyline(end, 1e-6, unit_to_viewport, 500.);
let farthest = huge.iter().map(|point| point.distance(endpoint)).fold(0., f64::max);
assert!((400. ..=1000.).contains(&farthest), "a huge circle should reach about 500 pixels, not {farthest}");
for polyline in [small, huge] {
assert!(distance_to_polyline(&polyline, endpoint).unwrap() < 1e-6);
}
}
}
}
@@ -11,7 +11,7 @@ use graphene_std::Color;
use graphene_std::raster::BlendMode; use graphene_std::raster::BlendMode;
use graphene_std::text::{Font, TypesettingConfig}; use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId; use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box}; use graphene_std::vector::style::{FillChoice, GradientDirection, GradientModel, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
use graphene_std::vector::{Gradient, GradientForm, GradientRamp, GradientSettings, PointId, SegmentId, VectorModificationType}; use graphene_std::vector::{Gradient, GradientForm, GradientRamp, GradientSettings, PointId, SegmentId, VectorModificationType};
use graphene_std::{NodeParameter, ParameterRef}; use graphene_std::{NodeParameter, ParameterRef};
use std::collections::VecDeque; use std::collections::VecDeque;
@@ -859,6 +859,9 @@ pub struct FillNodeGradient {
pub curvatures: Option<[f64; 2]>, pub curvatures: Option<[f64; 2]>,
/// The form its curvatures make, which is linear for any that make neither. /// The form its curvatures make, which is linear for any that make neither.
pub gradient_form: GradientForm, pub gradient_form: GradientForm,
/// Its model and direction, each unless the graph feeds it.
pub model: Option<GradientModel>,
pub direction: Option<GradientDirection>,
pub settings: GradientSettings, pub settings: GradientSettings,
pub transform: DAffine2, pub transform: DAffine2,
/// Whether the transform input holds a plain value (so it may be written to) rather than a wire. /// Whether the transform input holds a plain value (so it may be written to) rather than a wire.
@@ -876,6 +879,14 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
let stops = Gradient::from(ramp); let stops = Gradient::from(ramp);
let curvatures = fill_node_curvatures(fill_node); let curvatures = fill_node_curvatures(fill_node);
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default(); let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default();
let model = match fill_node.input(fill::ModelInput).and_then(NodeInput::as_non_exposed_value) {
Some(&TaggedValue::GradientModel(model)) => Some(model),
_ => None,
};
let direction = match fill_node.input(fill::DirectionInput).and_then(NodeInput::as_non_exposed_value) {
Some(&TaggedValue::GradientDirection(direction)) => Some(direction),
_ => None,
};
let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true))); let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value()); let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
let transform = match (has_transform, transform_input) { let transform = match (has_transform, transform_input) {
@@ -888,6 +899,8 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
stops, stops,
curvatures, curvatures,
gradient_form, gradient_form,
model,
direction,
settings, settings,
transform, transform,
transform_is_value: transform_input.is_some(), transform_is_value: transform_input.is_some(),
@@ -3,6 +3,7 @@ pub mod color_selector;
pub mod compass_rose; pub mod compass_rose;
pub mod edit_target; pub mod edit_target;
pub mod gizmos; pub mod gizmos;
pub mod gradient_gizmos;
pub mod graph_modification_utils; pub mod graph_modification_utils;
pub mod layer_origin_cross; pub mod layer_origin_cross;
pub mod measure; pub mod measure;
@@ -92,6 +92,8 @@ pub struct PointOptions {
pub box_features: Option<BoxFeatures>, pub box_features: Option<BoxFeatures>,
/// Whether the grid is left out, as for a turn, which the grid would otherwise step at odd angles. /// Whether the grid is left out, as for a turn, which the grid would otherwise step at odd angles.
pub ignores_grid: bool, 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. /// Which features of a gesture make up a box.
@@ -122,6 +124,8 @@ pub struct Shown {
pub features: Vec<DVec2>, pub features: Vec<DVec2>,
/// The index of the feature the pointer carries. /// The index of the feature the pointer carries.
pub lead: usize, 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. /// 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(), features: features.iter().map(|feature| feature.position(parameters)).collect(),
lead, lead,
outcome, 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 // 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)], features: vec![position_of(snapped)],
lead: 0, lead: 0,
outcome, outcome,
marked_by_tool: false,
}); });
snapped snapped
@@ -19,14 +19,24 @@ impl SnapSession {
self.draw_awake(target, to_viewport, overlay_context); 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 // 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) if matches!(outcome.snap, Snap::Grid | Snap::Free)
&& self.gesture.is_none() && self.gesture.is_none()
&& let Some(&position) = features.get(*lead) && 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; return;
} }
File diff suppressed because it is too large. Load diff
@@ -571,6 +571,7 @@ tagged_value! {
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code #[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
GradientForm(vector::style::GradientForm), GradientForm(vector::style::GradientForm),
GradientModel(vector::style::GradientModel), GradientModel(vector::style::GradientModel),
GradientDirection(vector::style::GradientDirection),
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code #[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
GradientSpread(vector::style::GradientSpread), GradientSpread(vector::style::GradientSpread),
GradientSpace(vector::style::GradientSpace), GradientSpace(vector::style::GradientSpace),
@@ -26,7 +26,9 @@ use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
WeldMethod, WeldMethod,
}; };
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin}; use graphene_std::vector::style::{
DashPattern, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification}; use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type}; use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution}; use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
@@ -271,6 +273,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
StrokeCap, StrokeCap,
GradientForm, GradientForm,
GradientModel, GradientModel,
GradientDirection,
GradientSpread, GradientSpread,
GradientSpace, GradientSpace,
GradientHueDirection, GradientHueDirection,
@@ -516,6 +519,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
attribute_value_node!(Item<BlendMode>), attribute_value_node!(Item<BlendMode>),
attribute_value_node!(Item<GradientForm>), attribute_value_node!(Item<GradientForm>),
attribute_value_node!(Item<GradientModel>), attribute_value_node!(Item<GradientModel>),
attribute_value_node!(Item<GradientDirection>),
attribute_value_node!(Item<GradientSpread>), attribute_value_node!(Item<GradientSpread>),
attribute_value_node!(Item<GradientSpace>), attribute_value_node!(Item<GradientSpace>),
attribute_value_node!(Item<GradientHueDirection>), attribute_value_node!(Item<GradientHueDirection>),
+3 -3
View File
@@ -33,9 +33,9 @@ pub use graphene_hash;
pub use graphene_hash::CacheHash; pub use graphene_hash::CacheHash;
pub use list::{ pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL, ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT,
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
}; };
pub use memo::MemoHash; pub use memo::MemoHash;
pub use num_traits; pub use num_traits;
@@ -67,6 +67,8 @@ pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
/// Gradient's `GradientModel` (`Standard` or `Apollonian`), how the contours between its curved ends are laid out: as SVG 2's cone /// Gradient's `GradientModel` (`Standard` or `Apollonian`), how the contours between its curved ends are laid out: as SVG 2's cone
/// between the end circles, or as the family of circles the ends span. Absent, it's `Standard`. /// between the end circles, or as the family of circles the ends span. Absent, it's `Standard`.
pub const ATTR_GRADIENT_MODEL: &str = "gradient_model"; pub const ATTR_GRADIENT_MODEL: &str = "gradient_model";
/// Gradient's `GradientDirection` (`Along` or `Across`), whether its colors run from one end contour to the other or around each contour. Absent, it's `Along`.
pub const ATTR_GRADIENT_DIRECTION: &str = "gradient_direction";
/// Gradient's `GradientSpace`, the color space its stops interpolate in. /// Gradient's `GradientSpace`, the color space its stops interpolate in.
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space"; pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the /// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
@@ -10,8 +10,8 @@ use core_types::none;
use core_types::ops::FromAnchorPosition; use core_types::ops::FromAnchorPosition;
use core_types::transform::Transform; use core_types::transform::Transform;
use core_types::{ use core_types::{
ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY,
Color, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color,
}; };
use dyn_any::DynAny; use dyn_any::DynAny;
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
@@ -19,7 +19,7 @@ use raster_types::{CPU, GPU, Raster};
pub use vector_types::Vector; pub use vector_types::Vector;
use vector_types::gradient_standard::GradientShape; use vector_types::gradient_standard::GradientShape;
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes}; use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
use vector_types::{Gradient, GradientModel, GradientSpread}; use vector_types::{Gradient, GradientDirection, GradientModel, GradientSpread};
/// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node. /// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node.
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)] #[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
@@ -859,6 +859,7 @@ fn gradient_paints_everywhere<'a>(attribute: &dyn Fn(&str) -> Option<&'a dyn std
read::<f64>(attribute, ATTR_GRADIENT_START_CURVATURE).copied().unwrap_or_default(), read::<f64>(attribute, ATTR_GRADIENT_START_CURVATURE).copied().unwrap_or_default(),
read::<f64>(attribute, ATTR_GRADIENT_END_CURVATURE).copied().unwrap_or_default(), read::<f64>(attribute, ATTR_GRADIENT_END_CURVATURE).copied().unwrap_or_default(),
read::<GradientModel>(attribute, ATTR_GRADIENT_MODEL).copied().unwrap_or_default(), read::<GradientModel>(attribute, ATTR_GRADIENT_MODEL).copied().unwrap_or_default(),
read::<GradientDirection>(attribute, ATTR_GRADIENT_DIRECTION).copied().unwrap_or_default(),
read::<DAffine2>(attribute, ATTR_TRANSFORM).copied().unwrap_or_default(), read::<DAffine2>(attribute, ATTR_TRANSFORM).copied().unwrap_or_default(),
) )
.paints_everywhere() .paints_everywhere()
@@ -13,7 +13,7 @@ use crate::warp_kernels::WarpRasterizer;
use core_types::FallibleVec2Operations; use core_types::FallibleVec2Operations;
use core_types::blending::BlendMode; use core_types::blending::BlendMode;
use core_types::color::{linear_to_srgb, srgb_to_linear}; use core_types::color::{linear_to_srgb, srgb_to_linear};
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE, Item, List}; use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE, Item, List};
use core_types::transfer_curve::TransferCurve; use core_types::transfer_curve::TransferCurve;
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color}; use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
use glam::{DAffine2, DMat2, DVec2}; use glam::{DAffine2, DMat2, DVec2};
@@ -1510,6 +1510,7 @@ fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> Optio
item.attribute_cloned_or_default(ATTR_GRADIENT_START_CURVATURE), item.attribute_cloned_or_default(ATTR_GRADIENT_START_CURVATURE),
item.attribute_cloned_or_default(ATTR_GRADIENT_END_CURVATURE), item.attribute_cloned_or_default(ATTR_GRADIENT_END_CURVATURE),
item.attribute_cloned_or_default(ATTR_GRADIENT_MODEL), item.attribute_cloned_or_default(ATTR_GRADIENT_MODEL),
item.attribute_cloned_or_default(ATTR_GRADIENT_DIRECTION),
placement, placement,
); );
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse()); let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
@@ -1536,6 +1537,10 @@ fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> Optio
let to_unit = to_unit?; let to_unit = to_unit?;
Some(Box::new(move |point| Some(parameters.t(to_unit.transform_point2(point))))) Some(Box::new(move |point| Some(parameters.t(to_unit.transform_point2(point)))))
} }
GradientShape::Across(across) => {
let to_unit = to_unit?;
Some(Box::new(move |point| across.chart.v(to_unit.transform_point2(point))))
}
} }
} }
@@ -1622,6 +1627,33 @@ mod tests {
assert!(alpha_at(5, 5) > 0.9, "{}", alpha_at(5, 5)); assert!(alpha_at(5, 5) > 0.9, "{}", alpha_at(5, 5));
} }
#[test]
fn gradients_read_across_their_contours_take_positions_around_them() {
use std::f64::consts::TAU;
use vector_types::gradient::GradientDirection;
// A sheared placement, which the linear form read across its line follows in full
let placement = DAffine2::from_cols(DVec2::new(40., 10.), DVec2::new(-5., 25.), DVec2::new(7., 3.));
let across = |[start, end]: [f64; 2]| {
Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
.with_attribute(ATTR_TRANSFORM, placement)
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start)
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end)
.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across)
};
let (Some(linear), Some(radial)) = (gradient_position(&across([0., 0.])), gradient_position(&across([-1., 0.5]))) else {
panic!("both forms should be read across their contours");
};
for unit in [DVec2::new(0.3, 0.2), DVec2::new(-0.5, 0.7), DVec2::new(0.9, -0.4)] {
let point = placement.transform_point2(unit);
assert!(linear(point).is_some_and(|v| (v - unit.y).abs() < 1e-9), "linear at {unit}");
let angle = unit.y.atan2(unit.x).rem_euclid(TAU) / TAU;
assert!(radial(point).is_some_and(|v| (v - angle).abs() < 1e-9), "radial at {unit}");
}
}
#[test] #[test]
fn image_paints_fade_by_their_fill_once_with_effects_of_their_own() { fn image_paints_fade_by_their_fill_once_with_effects_of_their_own() {
use graphic_types::EffectKind; use graphic_types::EffectKind;
@@ -105,7 +105,7 @@ fn render_gradient_paint(
let shape = gradient_shape(item); let shape = gradient_shape(item);
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start()); let mut samples = spread_adjusted_samples(&stops, settings, shape);
with_two_stops_at_least(shape, &mut samples); with_two_stops_at_least(shape, &mut samples);
let paint_opacity = item.paint_opacity(for_mask); let paint_opacity = item.paint_opacity(for_mask);
+226 -62
View File
@@ -21,7 +21,7 @@ use core_types::transform::Footprint;
use core_types::uuid::{NodeId, generate_uuid}; use core_types::uuid::{NodeId, generate_uuid};
use core_types::{ use core_types::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
ATTR_EFFECTS, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPACE, ATTR_EFFECTS, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPACE,
ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TEXT_ALIGN, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TEXT_ALIGN,
ATTR_TRANSFORM, ATTR_TRANSFORM,
}; };
@@ -37,6 +37,7 @@ use graphic_types::masks::{MaskMode, masked_radius_blur_levels};
use graphic_types::raster_types::{CPU, GPU, Raster}; use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::resampling::{EffectFrame, frame_of_bounds}; use graphic_types::resampling::{EffectFrame, frame_of_bounds};
use graphic_types::vector_types::gradient::{Gradient, GradientForm}; use graphic_types::vector_types::gradient::{Gradient, GradientForm};
use graphic_types::vector_types::gradient_across::{AcrossChart, GradientAcross};
use graphic_types::vector_types::gradient_apollonian::{AxisCircle, CrossingSelection, GradientApollonian}; use graphic_types::vector_types::gradient_apollonian::{AxisCircle, CrossingSelection, GradientApollonian};
use graphic_types::vector_types::gradient_standard::{AxisRamp, Cone, GradientShape, GradientStandard, HalfPlane, RampEnd}; use graphic_types::vector_types::gradient_standard::{AxisRamp, Cone, GradientShape, GradientStandard, HalfPlane, RampEnd};
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint, TargetPath}; use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint, TargetPath};
@@ -3094,12 +3095,13 @@ fn transform_relative_to(reference: DAffine2, transform: DAffine2) -> DAffine2 {
} }
} }
/// How a gradient item's contours are laid out, decided by its curvatures and model. /// How a gradient item's contours are laid out, decided by its curvatures and model, and which way its colors run.
pub(crate) fn gradient_shape(item: ItemRef<'_, Gradient>) -> GradientShape { pub(crate) fn gradient_shape(item: ItemRef<'_, Gradient>) -> GradientShape {
GradientShape::new( GradientShape::new(
item.attribute_cloned_or_default(ATTR_GRADIENT_START_CURVATURE), item.attribute_cloned_or_default(ATTR_GRADIENT_START_CURVATURE),
item.attribute_cloned_or_default(ATTR_GRADIENT_END_CURVATURE), item.attribute_cloned_or_default(ATTR_GRADIENT_END_CURVATURE),
item.attribute_cloned_or_default(ATTR_GRADIENT_MODEL), item.attribute_cloned_or_default(ATTR_GRADIENT_MODEL),
item.attribute_cloned_or_default(ATTR_GRADIENT_DIRECTION),
item.attribute_cloned_or_default(ATTR_TRANSFORM), item.attribute_cloned_or_default(ATTR_TRANSFORM),
) )
} }
@@ -3112,7 +3114,7 @@ pub(crate) fn gradient_draws_masked(item: ItemRef<'_, Gradient>) -> bool {
/// How SVG draws a gradient of this shape when it isn't one of the forms: as SVG 2 draws its curvatures, or under the Apollonian model, as its stand-in where no image the GPU renders replaces it. /// How SVG draws a gradient of this shape when it isn't one of the forms: as SVG 2 draws its curvatures, or under the Apollonian model, as its stand-in where no image the GPU renders replaces it.
pub(crate) fn svg_gradient_standard(shape: GradientShape) -> Option<GradientStandard> { pub(crate) fn svg_gradient_standard(shape: GradientShape) -> Option<GradientStandard> {
match shape { match shape {
GradientShape::Linear | GradientShape::Radial => None, GradientShape::Linear | GradientShape::Radial | GradientShape::Across(_) => None,
GradientShape::Standard(gradient) | GradientShape::Apollonian(GradientApollonian { svg_stand_in: gradient, .. }) => Some(gradient), GradientShape::Standard(gradient) | GradientShape::Apollonian(GradientApollonian { svg_stand_in: gradient, .. }) => Some(gradient),
} }
} }
@@ -3156,11 +3158,12 @@ type GradientSamples = Vec<(f64, Color, Option<f64>)>;
/// The gradient's renderable samples, bracketed for the `Clear` spread (which neither SVG nor Vello supports natively) by transparent guard stops. /// The gradient's renderable samples, bracketed for the `Clear` spread (which neither SVG nor Vello supports natively) by transparent guard stops.
/// ///
/// The guards share the unit range's end offsets, ordered so the pad extension paints transparency outward while the later /// The guards share the unit range's end offsets, ordered so the pad extension paints transparency outward while the later
/// of each pair of coincident stops cuts the paint off exactly at the range's boundaries. The guard at the start is left out /// of each pair of coincident stops cuts the paint off exactly at the range's boundaries. The guard at either end is left out
/// when the gradient's position can't reach before it. /// when the position of a gradient of this `shape` can't reach past it.
pub(crate) fn spread_adjusted_samples(gradient: &Gradient, settings: GradientSettings, reaches_before_start: bool) -> GradientSamples { pub(crate) fn spread_adjusted_samples(gradient: &Gradient, settings: GradientSettings, shape: GradientShape) -> GradientSamples {
let samples = gradient.interpolated_samples(settings); let samples = gradient.interpolated_samples(settings);
if settings.spread != GradientSpread::Clear { let (reaches_before_start, reaches_past_end) = (shape.reaches_before_start(), shape.reaches_past_end());
if settings.spread != GradientSpread::Clear || !(reaches_before_start || reaches_past_end) {
return samples; return samples;
} }
@@ -3186,7 +3189,9 @@ pub(crate) fn spread_adjusted_samples(gradient: &Gradient, settings: GradientSet
if needs_end_anchor { if needs_end_anchor {
adjusted.push((1., last_color, None)); adjusted.push((1., last_color, None));
} }
adjusted.push((1., Color::TRANSPARENT, None)); if reaches_past_end {
adjusted.push((1., Color::TRANSPARENT, None));
}
adjusted adjusted
} }
@@ -3224,6 +3229,18 @@ fn unit_gradient_kind(gradient_form: GradientForm) -> peniko::GradientKind {
} }
} }
/// The linear form read across its contours, in its own space before the brush transform places it: the line from the origin along +Y to 1.
fn across_linear_kind() -> peniko::GradientKind {
peniko::LinearGradientPosition {
start: kurbo::Point::ORIGIN,
end: kurbo::Point::new(0., 1.),
}
.into()
}
/// The geometry of [`across_linear_kind`] as an SVG linear gradient's.
const ACROSS_LINEAR_GEOMETRY: &str = r#" x1="0" y1="0" x2="0" y2="1""#;
/// The radius an end circle shrunk to a point is drawn with, since SVG paints a gradient ending in a circle of radius 0 as its last stop's color rather than the cone's limit. /// The radius an end circle shrunk to a point is drawn with, since SVG paints a gradient ending in a circle of radius 0 as its last stop's color rather than the cone's limit.
const POINT_END_RADIUS: f64 = 1e-7; const POINT_END_RADIUS: f64 = 1e-7;
@@ -3332,6 +3349,9 @@ pub(crate) fn write_svg_gradient_paint(
GradientShape::Linear => return unmasked(server(defs, "linearGradient", r#" x1="0" y1="0" x2="1" y2="0""#, &format!("{spread}{}", placed(transform)), stops)), GradientShape::Linear => return unmasked(server(defs, "linearGradient", r#" x1="0" y1="0" x2="1" y2="0""#, &format!("{spread}{}", placed(transform)), stops)),
GradientShape::Radial => return unmasked(server(defs, "radialGradient", r#" cx="0" cy="0" r="1""#, &format!("{spread}{}", placed(transform)), stops)), GradientShape::Radial => return unmasked(server(defs, "radialGradient", r#" cx="0" cy="0" r="1""#, &format!("{spread}{}", placed(transform)), stops)),
GradientShape::Standard(gradient) | GradientShape::Apollonian(GradientApollonian { svg_stand_in: gradient, .. }) => gradient, GradientShape::Standard(gradient) | GradientShape::Apollonian(GradientApollonian { svg_stand_in: gradient, .. }) => gradient,
GradientShape::Across(GradientAcross { chart: AcrossChart::Nothing, .. }) => return Vec::new(),
// Read across the gradient line like the linear form, exactly for it or as the stand-in where no image the GPU renders replaces the others
GradientShape::Across(_) => return unmasked(server(defs, "linearGradient", ACROSS_LINEAR_GEOMETRY, &format!("{spread}{}", placed(transform)), stops)),
}; };
let linear = |[x1, x2]: [f64; 2]| format!(r#" x1="{x1}" y1="0" x2="{x2}" y2="0""#); let linear = |[x1, x2]: [f64; 2]| format!(r#" x1="{x1}" y1="0" x2="{x2}" y2="0""#);
@@ -3420,7 +3440,9 @@ fn peniko_extend(gradient_spread: GradientSpread) -> peniko::Extend {
enum GradientBrush { enum GradientBrush {
Peniko(peniko::Brush), Peniko(peniko::Brush),
/// Apollonian circles, which only Vello GPU's fork draws. /// Apollonian circles, which only Vello GPU's fork draws.
Apollonian(vello_gpu::PencilGradient), Apollonian(vello_gpu::ApollonianGradient),
/// A position running around the contours, which only Vello GPU's fork draws.
Polar(vello_gpu::PolarGradient),
} }
impl<'b> From<&'b GradientBrush> for SceneBrush<'b> { impl<'b> From<&'b GradientBrush> for SceneBrush<'b> {
@@ -3428,6 +3450,7 @@ impl<'b> From<&'b GradientBrush> for SceneBrush<'b> {
match brush { match brush {
GradientBrush::Peniko(brush) => brush.into(), GradientBrush::Peniko(brush) => brush.into(),
GradientBrush::Apollonian(gradient) => gradient.into(), GradientBrush::Apollonian(gradient) => gradient.into(),
GradientBrush::Polar(gradient) => gradient.into(),
} }
} }
} }
@@ -3472,22 +3495,7 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
let brush = |kind: peniko::GradientKind, stops: peniko::ColorStops, extend: peniko::Extend| GradientBrush::Peniko(peniko::Brush::Gradient(gradient(kind, stops, extend))); let brush = |kind: peniko::GradientKind, stops: peniko::ColorStops, extend: peniko::Extend| GradientBrush::Peniko(peniko::Brush::Gradient(gradient(kind, stops, extend)));
let ramp = |kind: peniko::GradientKind| brush(kind, peniko_color_stops(samples), peniko_extend(spread)); let ramp = |kind: peniko::GradientKind| brush(kind, peniko_color_stops(samples), peniko_extend(spread));
let gradient = match shape { // Ramps along the gradient line, and steps across it, are placed like the linear form
GradientShape::Linear => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Linear)), gradient_placement(placement, shape)), None)])),
GradientShape::Radial => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Radial)), placement), None)])),
// Its contours come from its own geometry, so its ramp takes the linear kind, which goes unused
GradientShape::Apollonian(parameters) => {
let ramp = gradient(unit_gradient_kind(GradientForm::Linear), peniko_color_stops(samples), peniko_extend(spread));
let apollonian = vello_gpu::PencilGradient {
ramp,
geometry: apollonian_geometry(&parameters),
};
return Some(VelloGradientPaint(vec![((GradientBrush::Apollonian(apollonian), placement), None)]));
}
GradientShape::Standard(gradient) => gradient,
};
// Ramps along the gradient line are placed like the linear form, and circles by the full placement
let desheared = desheared_placement(placement); let desheared = desheared_placement(placement);
let linear = |[start, end]: [f64; 2]| -> peniko::GradientKind { let linear = |[start, end]: [f64; 2]| -> peniko::GradientKind {
peniko::LinearGradientPosition { peniko::LinearGradientPosition {
@@ -3496,15 +3504,6 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
} }
.into() .into()
}; };
let radial = |cone: Cone| -> peniko::GradientKind {
peniko::RadialGradientPosition {
start_center: kurbo::Point::new(cone.start_center, 0.),
start_radius: cone.start_radius as f32,
end_center: kurbo::Point::new(cone.end_center, 0.),
end_radius: cone.end_radius as f32,
}
.into()
};
let stops = |colors: &[(f32, Color)]| { let stops = |colors: &[(f32, Color)]| {
let stop = |&(offset, color): &(f32, Color)| peniko::ColorStop { let stop = |&(offset, color): &(f32, Color)| peniko::ColorStop {
offset, offset,
@@ -3512,7 +3511,6 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
}; };
peniko::ColorStops(colors.iter().map(stop).collect()) peniko::ColorStops(colors.iter().map(stop).collect())
}; };
let end_color = |end| end_stop_color(samples, end);
// A step at `at` from one color to the other, as a unit-long gradient there with both stops at its start // A step at `at` from one color to the other, as a unit-long gradient there with both stops at its start
let step = |at: f64, direction: f64, [before, after]: [Color; 2]| { let step = |at: f64, direction: f64, [before, after]: [Color; 2]| {
@@ -3520,6 +3518,79 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
(brush, rebased_transform(desheared, at)) (brush, rebased_transform(desheared, at))
}; };
// An eraser opaque wherever a layer kept to one side of a line across the gradient line is hidden
let eraser = |keep: HalfPlane| {
let colors = if keep.keeps_before {
[Color::TRANSPARENT, Color::BLACK]
} else {
[Color::BLACK, Color::TRANSPARENT]
};
step(keep.at, 1., colors)
};
let gradient = match shape {
GradientShape::Linear => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Linear)), gradient_placement(placement, shape)), None)])),
GradientShape::Radial => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Radial)), placement), None)])),
// Its contours come from its own geometry, so its ramp takes the linear kind, which goes unused
GradientShape::Apollonian(parameters) => {
let ramp = gradient(unit_gradient_kind(GradientForm::Linear), peniko_color_stops(samples), peniko_extend(spread));
let apollonian = vello_gpu::ApollonianGradient {
ramp,
geometry: apollonian_geometry(&parameters),
};
return Some(VelloGradientPaint(vec![((GradientBrush::Apollonian(apollonian), placement), None)]));
}
GradientShape::Across(GradientAcross { chart, .. }) => {
let polar = |geometry| {
let ramp = gradient(across_linear_kind(), peniko_color_stops(samples), peniko_extend(spread));
GradientBrush::Polar(vello_gpu::PolarGradient { ramp, geometry })
};
// The angle of `(numerator[0] z + numerator[1]) / (denominator[0] z + denominator[1])` with real coefficients
let mobius_angle = |numerator: [f64; 2], denominator: [f64; 2]| {
let real = |[slope, intercept]: [f64; 2]| [[slope as f32, 0.], [intercept as f32, 0.]];
let measure = vello_gpu::PolarMeasure::Angle;
polar(vello_gpu::PolarGeometry::Mobius {
numerator: real(numerator),
denominator: real(denominator),
measure,
})
};
let (brush, keep) = match chart {
AcrossChart::Nothing => return None,
AcrossChart::Linear => (ramp(across_linear_kind()), None),
// Vello's own sweep gradient, which Graphite builds without, measures the same angle as `z - center`
AcrossChart::Concentric { center } => (mobius_angle([1., -center], [0., 1.]), None),
AcrossChart::Cone { cone, keep } => (polar(cone_angle_geometry(cone)), keep),
AcrossChart::Mobius { numerator, denominator } => (mobius_angle(numerator, denominator), None),
// `(z - (center_x, -half_height)) / (z - (center_x, half_height))`
AcrossChart::Bipolar { center_x, half_height, scale } => {
let (center_x, half_height) = (center_x as f32, half_height as f32);
let geometry = vello_gpu::PolarGeometry::Mobius {
numerator: [[1., 0.], [-center_x, half_height]],
denominator: [[1., 0.], [-center_x, -half_height]],
measure: vello_gpu::PolarMeasure::LogModulus { scale: scale as f32, offset: 0. },
};
(polar(geometry), None)
}
};
return Some(VelloGradientPaint(vec![((brush, placement), keep.map(eraser))]));
}
GradientShape::Standard(gradient) => gradient,
};
// Circles are placed by the full placement
let radial = |cone: Cone| -> peniko::GradientKind {
peniko::RadialGradientPosition {
start_center: kurbo::Point::new(cone.start_center, 0.),
start_radius: cone.start_radius as f32,
end_center: kurbo::Point::new(cone.end_center, 0.),
end_radius: cone.end_radius as f32,
}
.into()
};
let end_color = |end| end_stop_color(samples, end);
let layers: Vec<_> = standard_layers(gradient) let layers: Vec<_> = standard_layers(gradient)
.into_iter() .into_iter()
.map(|(paint, mask)| { .map(|(paint, mask)| {
@@ -3534,37 +3605,37 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
StandardPaint::Solid(end) => (GradientBrush::Peniko(peniko::Brush::Solid(peniko::Color::new(end_color(end).to_gamma_srgb_channels()))), placement), StandardPaint::Solid(end) => (GradientBrush::Peniko(peniko::Brush::Solid(peniko::Color::new(end_color(end).to_gamma_srgb_channels()))), placement),
}; };
// The eraser is opaque wherever the layer is hidden (paint, mask.map(eraser))
let eraser = mask.map(|keep| {
let colors = if keep.keeps_before {
[Color::TRANSPARENT, Color::BLACK]
} else {
[Color::BLACK, Color::TRANSPARENT]
};
step(keep.at, 1., colors)
});
(paint, eraser)
}) })
.collect(); .collect();
(!layers.is_empty()).then_some(VelloGradientPaint(layers)) (!layers.is_empty()).then_some(VelloGradientPaint(layers))
} }
/// SVG 2's cone as Vello GPU's polar gradient paint takes it, in single precision.
fn cone_angle_geometry(cone: Cone) -> vello_gpu::PolarGeometry {
vello_gpu::PolarGeometry::ConeAngle {
start_center: [cone.start_center as f32, 0.],
start_radius: cone.start_radius as f32,
end_center: [cone.end_center as f32, 0.],
end_radius: cone.end_radius as f32,
}
}
/// The Apollonian circles of a gradient as Vello GPU's Apollonian gradient paint takes them, in single precision. /// The Apollonian circles of a gradient as Vello GPU's Apollonian gradient paint takes them, in single precision.
fn apollonian_geometry(parameters: &GradientApollonian) -> vello_gpu::PencilGeometry { fn apollonian_geometry(parameters: &GradientApollonian) -> vello_gpu::ApollonianGeometry {
let circle = |circle: &AxisCircle| [circle.a as f32, circle.b as f32, circle.c as f32]; let circle = |circle: &AxisCircle| [circle.a as f32, circle.b as f32, circle.c as f32];
vello_gpu::PencilGeometry { vello_gpu::ApollonianGeometry {
start: circle(&parameters.start), start: circle(&parameters.start),
end: circle(&parameters.end), end: circle(&parameters.end),
selection: match parameters.selection { selection: match parameters.selection {
CrossingSelection::SameSideAs { radical_x } => vello_gpu::PencilSelection::SameSideAs { radical_x: radical_x as f32 }, CrossingSelection::SameSideAs { radical_x } => vello_gpu::ApollonianSelection::SameSideAs { radical_x: radical_x as f32 },
CrossingSelection::OnArc { quadratic } => vello_gpu::PencilSelection::OnArc { CrossingSelection::OnArc { quadratic } => vello_gpu::ApollonianSelection::OnArc {
quadratic: quadratic.map(|coefficient| coefficient as f32), quadratic: quadratic.map(|coefficient| coefficient as f32),
}, },
}, },
wrap: parameters.wrap.map(|wrap| vello_gpu::PencilWrap { wrap: parameters.wrap.map(|wrap| vello_gpu::ApollonianWrap {
reference_x: wrap.reference_x as f32, reference_x: wrap.reference_x as f32,
band_side: wrap.band_side as f32, band_side: wrap.band_side as f32,
t: wrap.t as f32, t: wrap.t as f32,
@@ -3582,7 +3653,7 @@ fn create_gradient_paint(gradient_item: ItemRef<'_, Gradient>, multiplied_transf
let shape = gradient_shape(gradient_item); let shape = gradient_shape(gradient_item);
let gradient_transform: DAffine2 = gradient_item.attribute_cloned_or_default(ATTR_TRANSFORM); let gradient_transform: DAffine2 = gradient_item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start()); let mut samples = spread_adjusted_samples(&stops, settings, shape);
with_two_stops_at_least(shape, &mut samples); with_two_stops_at_least(shape, &mut samples);
let paint_opacity = gradient_item.paint_opacity(for_mask); let paint_opacity = gradient_item.paint_opacity(for_mask);
@@ -6791,7 +6862,7 @@ fn render_gradient_shape_svg(
let shape = gradient_shape(item); let shape = gradient_shape(item);
let tag = if thumbnail_rect.is_some() { "rect" } else { "polyline" }; let tag = if thumbnail_rect.is_some() { "rect" } else { "polyline" };
let mut samples = spread_adjusted_samples(gradient, settings, shape.reaches_before_start()); let mut samples = spread_adjusted_samples(gradient, settings, shape);
with_two_stops_at_least(shape, &mut samples); with_two_stops_at_least(shape, &mut samples);
let mut stop_string = String::new(); let mut stop_string = String::new();
@@ -6920,7 +6991,7 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS
fn endless_gradient_paint(item: ItemRef<'_, Gradient>, gradient: &Gradient, settings: GradientSettings, parent_transform: DAffine2) -> Option<VelloGradientPaint> { fn endless_gradient_paint(item: ItemRef<'_, Gradient>, gradient: &Gradient, settings: GradientSettings, parent_transform: DAffine2) -> Option<VelloGradientPaint> {
let shape = gradient_shape(item); let shape = gradient_shape(item);
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut samples = spread_adjusted_samples(gradient, settings, shape.reaches_before_start()); let mut samples = spread_adjusted_samples(gradient, settings, shape);
with_two_stops_at_least(shape, &mut samples); with_two_stops_at_least(shape, &mut samples);
vello_gradient_paint(shape, &samples, settings.spread, parent_transform * transform) vello_gradient_paint(shape, &samples, settings.spread, parent_transform * transform)
@@ -6967,11 +7038,11 @@ fn collect_gradient_items_metadata<'a>(items: impl Iterator<Item = ItemRef<'a, G
} }
} }
/// The form of the control geometry a gradient item shows, which is linear for every shape but the radial one. /// The form of the control geometry a gradient item shows, which is linear for every shape but the radial form's, read along or across its contours.
fn gradient_control_form(item: ItemRef<'_, Gradient>) -> GradientForm { fn gradient_control_form(item: ItemRef<'_, Gradient>) -> GradientForm {
match gradient_shape(item) { match gradient_shape(item) {
GradientShape::Radial => GradientForm::Radial, GradientShape::Radial | GradientShape::Across(GradientAcross { form: Some(GradientForm::Radial), .. }) => GradientForm::Radial,
GradientShape::Linear | GradientShape::Standard(_) | GradientShape::Apollonian(_) => GradientForm::Linear, GradientShape::Linear | GradientShape::Standard(_) | GradientShape::Apollonian(_) | GradientShape::Across(_) => GradientForm::Linear,
} }
} }
@@ -7665,7 +7736,7 @@ impl SvgRenderAttrs<'_> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use vector_types::gradient::{GradientModel, GradientSpace}; use vector_types::gradient::{GradientDirection, GradientModel, GradientSpace};
#[test] #[test]
fn stacked_paint_colors_composite_in_straight_alpha() { fn stacked_paint_colors_composite_in_straight_alpha() {
@@ -7715,18 +7786,18 @@ mod tests {
}; };
// Other spreads pass the samples through unchanged // Other spreads pass the samples through unchanged
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Repeat), true); let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Repeat), GradientShape::Linear);
assert_eq!(samples, gradient.interpolated_samples(settings(GradientSpread::Pad))); assert_eq!(samples, gradient.interpolated_samples(settings(GradientSpread::Pad)));
// The guards share the range ends' exact offsets, ordered so the pad extension resolves to the transparent outer stops // The guards share the range ends' exact offsets, ordered so the pad extension resolves to the transparent outer stops
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Clear), true); let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Clear), GradientShape::Linear);
assert_eq!( assert_eq!(
samples, samples,
vec![(0., Color::TRANSPARENT, None), (0., Color::BLACK, None), (1., Color::WHITE, None), (1., Color::TRANSPARENT, None)] vec![(0., Color::TRANSPARENT, None), (0., Color::BLACK, None), (1., Color::WHITE, None), (1., Color::TRANSPARENT, None)]
); );
// A radial has no guard below the center // A radial has no guard below the center
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Clear), GradientShape::Radial.reaches_before_start()); let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Clear), GradientShape::Radial);
assert_eq!(samples, vec![(0., Color::BLACK, None), (1., Color::WHITE, None), (1., Color::TRANSPARENT, None)]); assert_eq!(samples, vec![(0., Color::BLACK, None), (1., Color::WHITE, None), (1., Color::TRANSPARENT, None)]);
} }
@@ -7739,7 +7810,7 @@ mod tests {
space: GradientSpace::RgbGamma, space: GradientSpace::RgbGamma,
..Default::default() ..Default::default()
}, },
true, GradientShape::Linear,
); );
let colors: Vec<Color> = samples.iter().map(|&(_, color, _)| color).collect(); let colors: Vec<Color> = samples.iter().map(|&(_, color, _)| color).collect();
assert_eq!(colors, vec![Color::TRANSPARENT, Color::BLACK, Color::BLACK, Color::TRANSPARENT]); assert_eq!(colors, vec![Color::TRANSPARENT, Color::BLACK, Color::BLACK, Color::TRANSPARENT]);
@@ -8054,6 +8125,99 @@ mod tests {
assert!(deferred_images_of(Graphic::Gradient(curved_gradient(crossing, GradientModel::Apollonian)), &thumbnail).is_empty()); assert!(deferred_images_of(Graphic::Gradient(curved_gradient(crossing, GradientModel::Apollonian)), &thumbnail).is_empty());
} }
/// A black to white gradient read in gamma across its contours, with these curvatures and model.
fn across_gradient(curvatures: [f64; 2], model: GradientModel) -> Item<Gradient> {
curved_gradient(curvatures, model).with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across)
}
#[test]
fn across_gradients_render_in_svg_as_the_linear_forms_ramp_across_its_line() {
use graphic_types::vector_types::gradient_standard::radius_curvature;
// The linear form's ramp across its line, toward the placement's y axis, is placed by the full placement under either model
let placement = DAffine2::from_cols(DVec2::new(40., 10.), DVec2::new(-5., 25.), DVec2::new(7., 3.));
let expected = format!(
r#"<linearGradient id="0" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="0" y2="1" gradientTransform="{}">{BLACK_TO_WHITE_STOPS}</linearGradient><polyline points="{ENDLESS_POINTS}" fill="url('#0')"/>"#,
format_transform_matrix(placement)
);
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let linear = across_gradient(GradientForm::Linear.curvatures(), model).with_attribute(ATTR_TRANSFORM, placement);
assert!(gradient_shape(ItemRef::Item(&linear)).svg_draws_exactly());
assert_eq!(gradient_svg(linear), expected, "{model:?} model");
}
// SVG only approximates every other shape, standing in with the same ramp where no image the GPU renders replaces it
let crossing = [radius_curvature(0.6), radius_curvature(0.6)];
let concentric = [radius_curvature(2.), radius_curvature(-1.)];
for (curvatures, model) in [
(GradientForm::Radial.curvatures(), GradientModel::Standard),
(crossing, GradientModel::Standard),
(crossing, GradientModel::Apollonian),
(concentric, GradientModel::Apollonian),
] {
let gradient = across_gradient(curvatures, model).with_attribute(ATTR_TRANSFORM, placement);
assert!(!gradient_shape(ItemRef::Item(&gradient)).svg_draws_exactly(), "curvatures {curvatures:?}, {model:?} model");
assert_eq!(gradient_svg(gradient), expected, "curvatures {curvatures:?}, {model:?} model");
}
// Identical end circles leave nothing to read across under the Standard model
let identical = radius_curvature(0.5);
assert_eq!(gradient_svg(across_gradient([identical, identical], GradientModel::Standard)), "");
}
#[test]
fn svg_across_gradients_svg_only_approximates_take_the_gpus_image() {
use glam::UVec2;
use graphic_types::vector_types::gradient_standard::radius_curvature;
let view = Footprint {
resolution: UVec2::new(96, 64),
..Default::default()
};
let render_params = RenderParams {
view: Some(view),
..Default::default()
};
let crossing = [radius_curvature(0.6), radius_curvature(0.6)];
// Endless, and painting a vector, the radial form read around its center takes an image while the linear form's ramp across its line keeps its markup
let radial = across_gradient(GradientForm::Radial.curvatures(), GradientModel::Standard);
let linear = across_gradient(GradientForm::Linear.curvatures(), GradientModel::Standard);
assert_eq!(deferred_images_of(Graphic::Gradient(radial.clone()), &render_params).len(), 1);
assert!(deferred_images_of(Graphic::Gradient(linear.clone()), &render_params).is_empty());
let images_of = |paint: Item<Gradient>| deferred_images_of(Graphic::VectorList(List::new_from_item(square_painted(Coverage::new_fill(), paint))), &render_params);
for paint in [radial, across_gradient(crossing, GradientModel::Standard), across_gradient(crossing, GradientModel::Apollonian)] {
assert_eq!(images_of(paint).len(), 1);
}
assert!(images_of(linear).is_empty());
}
#[test]
fn clear_spreads_guard_only_the_ends_a_position_across_contours_passes() {
use graphic_types::vector_types::gradient_standard::radius_curvature;
let gradient = Gradient::from(vec![Color::BLACK, Color::WHITE]);
let clear = GradientSettings {
spread: GradientSpread::Clear,
space: GradientSpace::RgbGamma,
..Default::default()
};
let across = |[start, end]: [f64; 2], model| GradientShape::new(start, end, model, GradientDirection::Across, DAffine2::IDENTITY);
// An angle around the contours stays within the range, so it takes no guard
let winding = across(GradientForm::Radial.curvatures(), GradientModel::Standard);
assert!(!winding.reaches_before_start() && !winding.reaches_past_end());
assert_eq!(spread_adjusted_samples(&gradient, clear, winding), gradient.interpolated_samples(clear));
// A distance beside the gradient line reaches both ways, as the linear form's along it does
let crossing = [radius_curvature(0.6), radius_curvature(0.6)];
for shape in [across(GradientForm::Linear.curvatures(), GradientModel::Standard), across(crossing, GradientModel::Apollonian)] {
assert!(shape.reaches_before_start() && shape.reaches_past_end(), "{shape:?}");
assert_eq!(spread_adjusted_samples(&gradient, clear, shape), spread_adjusted_samples(&gradient, clear, GradientShape::Linear));
}
}
#[test] #[test]
fn a_cut_far_along_the_gradient_line_keeps_its_place_on_screen() { fn a_cut_far_along_the_gradient_line_keeps_its_place_on_screen() {
use graphic_types::vector_types::gradient_standard::radius_curvature; use graphic_types::vector_types::gradient_standard::radius_curvature;
@@ -11,7 +11,7 @@ use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use vello_gpu::peniko::{self, BlendMode, BrushRef, Fill}; use vello_gpu::peniko::{self, BlendMode, BrushRef, Fill};
use vello_gpu::{Image, ImageSource, PaintType, PencilGradient, TextureId, TextureRegion}; use vello_gpu::{ApollonianGradient, Image, ImageSource, PaintType, PolarGradient, TextureId, TextureRegion};
/// Tolerance for turning shapes other than paths into paths, matching Vello's own. /// Tolerance for turning shapes other than paths into paths, matching Vello's own.
const SHAPE_TOLERANCE: f64 = 0.1; const SHAPE_TOLERANCE: f64 = 0.1;
@@ -100,7 +100,9 @@ pub enum SceneBrush<'b> {
/// A solid color, gradient, or image. /// A solid color, gradient, or image.
Peniko(BrushRef<'b>), Peniko(BrushRef<'b>),
/// A gradient whose contours are Apollonian circles, which only Vello GPU's fork draws. /// A gradient whose contours are Apollonian circles, which only Vello GPU's fork draws.
Apollonian(&'b PencilGradient), Apollonian(&'b ApollonianGradient),
/// A gradient whose position runs around its contours, which only Vello GPU's fork draws.
Polar(&'b PolarGradient),
} }
impl<'b> From<BrushRef<'b>> for SceneBrush<'b> { impl<'b> From<BrushRef<'b>> for SceneBrush<'b> {
@@ -133,12 +135,18 @@ impl From<&peniko::Color> for SceneBrush<'_> {
} }
} }
impl<'b> From<&'b PencilGradient> for SceneBrush<'b> { impl<'b> From<&'b ApollonianGradient> for SceneBrush<'b> {
fn from(gradient: &'b PencilGradient) -> Self { fn from(gradient: &'b ApollonianGradient) -> Self {
Self::Apollonian(gradient) Self::Apollonian(gradient)
} }
} }
impl<'b> From<&'b PolarGradient> for SceneBrush<'b> {
fn from(gradient: &'b PolarGradient) -> Self {
Self::Polar(gradient)
}
}
/// The pixels behind an image the scene draws. /// The pixels behind an image the scene draws.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum SceneImage { pub enum SceneImage {
@@ -744,7 +752,11 @@ impl<'a> VelloSceneBuilder<'a> {
fn set_paint(&mut self, brush: SceneBrush<'_>) -> Option<Affine> { fn set_paint(&mut self, brush: SceneBrush<'_>) -> Option<Affine> {
let (paint, paint_to_brush) = match brush { let (paint, paint_to_brush) = match brush {
SceneBrush::Apollonian(gradient) => { SceneBrush::Apollonian(gradient) => {
self.scene.set_pencil_gradient_paint(gradient.clone()); self.scene.set_apollonian_gradient_paint(gradient.clone());
return Some(Affine::IDENTITY);
}
SceneBrush::Polar(gradient) => {
self.scene.set_polar_gradient_paint(gradient.clone());
return Some(Affine::IDENTITY); return Some(Affine::IDENTITY);
} }
SceneBrush::Peniko(BrushRef::Solid(color)) => (PaintType::Solid(color), Affine::IDENTITY), SceneBrush::Peniko(BrushRef::Solid(color)) => (PaintType::Solid(color), Affine::IDENTITY),
@@ -1856,6 +1856,19 @@ pub enum GradientModel {
Apollonian, Apollonian,
} }
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[widget(Radio)]
pub enum GradientDirection {
/// Reads the colors from start to end, each contour taking one color.
#[default]
Along,
/// Reads the colors around each contour instead, once clockwise around curved ones, or beside the gradient line in the linear form. Except for the linear form, SVG exports include it as an image, and PDF exports show an approximation.
Across,
}
#[repr(C)] #[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)] #[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
@@ -0,0 +1,479 @@
//! Gradients read across their contours rather than along them, where each point's position `v` runs around or beside the contour through it.
//!
//! Everything here is in gradient space, laid out as in [`crate::gradient_standard`], and `v` increases toward +y (clockwise on screen for an
//! unreflected placement). A winding chart measures an angle in turns within `[0, 1)`, wrapping at a seam on the +x side where the spread has no
//! effect. The others measure from the gradient line, 0 on it and one unit per gradient length across its midpoint, which the spread then repeats.
use crate::gradient::{GradientForm, GradientModel};
use crate::gradient_apollonian::{AxisCircle, CircleFamily, Homogeneous};
use crate::gradient_standard::{Cone, GradientStandard, HalfPlane, NEAR_LINE_RADIUS, curvature_radius};
use glam::DVec2;
use std::f64::consts::TAU;
/// How far apart a cone's two centers may be, relative to its size, for it to be drawn as concentric circles.
const CONCENTRIC_TOLERANCE: f64 = 1e-9;
/// A gradient read across its contours.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GradientAcross {
pub chart: AcrossChart,
/// The form its curvatures make, if either.
pub form: Option<GradientForm>,
}
/// How each point of a gradient read across its contours finds its position `v`, in gradient space.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AcrossChart {
/// The linear form's: `v = y`.
Linear,
/// Concentric circles': the angle around their shared center at `(center, 0)`, from the +x ray.
Concentric { center: f64 },
/// SVG 2's cone's: the angle of the point around the center of the cone's circle through it, unpainted where the cone is and past `keep`'s line.
Cone { cone: Cone, keep: Option<HalfPlane> },
/// Apollonian circles nesting around two limit points: the angle of `M(z) = (n₀ z + n₁) / (d₀ z + d₁)`, which sends the limit point the
/// end contour encloses to 0 and the other to infinity, so each contour of constant `v` is an arc from one limit point to the other.
Mobius { numerator: [f64; 2], denominator: [f64; 2] },
/// Apollonian circles crossing at `(center_x, ±half_height)`: `scale · ln(|z - (center_x, -half_height)| / |z - (center_x, half_height)|)`,
/// the bipolar coordinate whose contours are the circles around the two crossings.
Bipolar { center_x: f64, half_height: f64, scale: f64 },
/// Unpainted everywhere, as SVG 2 leaves identical end circles.
Nothing,
}
impl AcrossChart {
/// The chart of a gradient with these curvatures, which must be finite and within -1 to 1, and model.
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel) -> Self {
match (GradientForm::from_curvatures([start_curvature, end_curvature]), model) {
(Some(GradientForm::Linear), _) => Self::Linear,
(Some(GradientForm::Radial), _) => Self::Concentric { center: 0. },
(None, GradientModel::Standard) => Self::standard(start_curvature, end_curvature),
(None, GradientModel::Apollonian) => Self::apollonian(start_curvature, end_curvature),
}
}
/// The angle around SVG 2's circles, painting where the Standard model's gradient read along them paints.
fn standard(start_curvature: f64, end_curvature: f64) -> Self {
match GradientStandard::new(start_curvature, end_curvature) {
GradientStandard::Cone(cone) => Self::cone(cone, None),
// A line end and a nearly flat cone, drawn as a profile along the gradient line, measure around the cone that's drawn at the flattest radius
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => Self::cone(near_line_cone(start_curvature, end_curvature), keep),
GradientStandard::Profile { .. } => Self::cone(near_line_cone(start_curvature, end_curvature), None),
GradientStandard::Nothing => Self::Nothing,
}
}
fn cone(cone: Cone, keep: Option<HalfPlane>) -> Self {
let size = cone.start_center.abs().max(cone.end_center.abs()).max(cone.start_radius).max(cone.end_radius);
let concentric = (cone.end_center - cone.start_center).abs() <= CONCENTRIC_TOLERANCE * size;
match keep {
None if concentric => Self::Concentric { center: cone.start_center },
_ => Self::Cone { cone, keep },
}
}
/// The angle around the limit points of the Apollonian circles, or the bipolar coordinate beside their crossings.
fn apollonian(start_curvature: f64, end_curvature: f64) -> Self {
// Identical end circles span no family of circles, and draw the linear form's plain ramp
let (start_radius, end_radius) = (curvature_radius(start_curvature), curvature_radius(end_curvature));
if start_radius.is_finite() && end_radius.is_finite() && Cone::between(start_radius, end_radius).is_identical() {
return Self::Linear;
}
let (start, end) = (AxisCircle::start(start_curvature), AxisCircle::end(end_curvature));
match CircleFamily::of(start, end) {
CircleFamily::Crossing { radical_x } => Self::bipolar(start, end, radical_x),
CircleFamily::Nesting { limit_points } => Self::mobius(start, end, limit_points),
}
}
fn bipolar(start: AxisCircle, end: AxisCircle, radical_x: f64) -> Self {
// The crossings lie on whichever end contour is rounder, which places them most precisely
let circle = if start.a.abs() >= end.a.abs() { start } else { end };
let half_height = (-(circle.b * radical_x + circle.c) / circle.a - radical_x * radical_x).max(0.).sqrt().max(f64::MIN_POSITIVE);
// The coordinate's rate across the gradient line at its midpoint is `half_height / (half_height² + (1/2 - radical_x)²)` before this scale
let midpoint_offset = 0.5 - radical_x;
let scale = (half_height * half_height + midpoint_offset * midpoint_offset) / (2. * half_height);
Self::Bipolar {
center_x: radical_x,
half_height,
scale,
}
}
fn mobius(start: AxisCircle, end: AxisCircle, limit_points: [Homogeneous; 2]) -> Self {
// With nonnegative denominators, a point's sign on a contour doesn't depend on how it's scaled
let oriented = |point: Homogeneous| {
let sign = if point.denominator < 0. { -1. } else { 1. };
Homogeneous {
numerator: point.numerator * sign,
denominator: point.denominator * sign,
}
};
let [first, second] = limit_points.map(oriented);
// The limit point inside the end contour, or the start contour where the end is a line, is negative on it (or zero, for a point contour on it)
let inside = |circle: AxisCircle, point: Homogeneous| {
let Homogeneous { numerator, denominator } = point;
circle.a * (circle.a * numerator * numerator + circle.b * numerator * denominator + circle.c * denominator * denominator)
};
let enclosing = if end.a != 0. { end } else { start };
let (enclosed, other) = if inside(enclosing, first) <= inside(enclosing, second) {
(first, second)
} else {
(second, first)
};
// Concentric circles have their other limit point at infinity, about which the angle is around their shared center
let Some(center) = enclosed.value() else { return Self::Linear };
if other.denominator == 0. {
return Self::Concentric { center };
}
// `M(z) = ±(z - enclosed) / (other - z)`, signed so `M` is positive on the +x ray from the enclosed limit point as `other` passes through infinity
let product = other.numerator * enclosed.denominator - enclosed.numerator * other.denominator;
let sign = if product < 0. { -1. } else { 1. };
Self::Mobius {
numerator: [sign * enclosed.denominator, -sign * enclosed.numerator],
denominator: [-other.denominator, other.numerator],
}
}
/// The position at `point`, or `None` where it's unpainted.
pub fn v(&self, point: DVec2) -> Option<f64> {
match *self {
Self::Linear => Some(point.y),
Self::Concentric { center } => Some(turns(point.y, point.x - center)),
Self::Cone { cone, keep } => {
if keep.is_some_and(|keep| !keep.keeps(point.x)) {
return None;
}
let t = cone.t(point)?;
let center = cone.start_center + t * (cone.end_center - cone.start_center);
Some(turns(point.y, point.x - center))
}
Self::Mobius { numerator, denominator } => {
// The angle of `numerator / denominator` is that of `numerator · conj(denominator)`
let affine = |[slope, intercept]: [f64; 2]| DVec2::new(slope * point.x + intercept, slope * point.y);
let (numerator, denominator) = (affine(numerator), affine(denominator));
Some(turns(numerator.y * denominator.x - numerator.x * denominator.y, numerator.dot(denominator)))
}
Self::Bipolar { center_x, half_height, scale } => {
// The squared distances to the crossings differ by `4 half_height y`, whose ratio's logarithm keeps its precision near the gradient line
let to_upper = DVec2::new(point.x - center_x, point.y - half_height).length_squared();
Some(scale * 0.5 * (4. * half_height * point.y / to_upper).ln_1p())
}
Self::Nothing => None,
}
}
/// Whether it measures an angle, wrapping from 1 back to 0 at a seam, rather than a distance from the gradient line.
pub fn winds(&self) -> bool {
matches!(self, Self::Concentric { .. } | Self::Cone { .. } | Self::Mobius { .. })
}
/// Whether it paints every point, rather than leaving some unpainted.
pub fn paints_everywhere(&self) -> bool {
match self {
Self::Linear | Self::Concentric { .. } | Self::Mobius { .. } | Self::Bipolar { .. } => true,
Self::Cone { cone, keep } => keep.is_none() && cone.is_nested(),
Self::Nothing => false,
}
}
/// Whether SVG draws it exactly, which only the linear form's ramp across the gradient line is (and nothing at all).
pub fn svg_draws_exactly(&self) -> bool {
matches!(self, Self::Linear | Self::Nothing)
}
}
/// The cone between the end contours with these curvatures, each a nearly flat circle or a line drawn at the flattest radius a cone is (a line bowing toward the other end).
fn near_line_cone(start_curvature: f64, end_curvature: f64) -> Cone {
let near_line_radius = |curvature: f64| {
let radius = curvature_radius(curvature);
if radius.is_infinite() {
NEAR_LINE_RADIUS
} else {
radius.clamp(-NEAR_LINE_RADIUS, NEAR_LINE_RADIUS)
}
};
Cone::between(near_line_radius(start_curvature), near_line_radius(end_curvature))
}
/// The angle of `(x, y)` from the +x axis toward the +y axis, in turns within `[0, 1)`.
fn turns(y: f64, x: f64) -> f64 {
let turns = y.atan2(x).rem_euclid(TAU) / TAU;
if turns >= 1. { 0. } else { turns }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gradient::{LINEAR_CURVATURES, RADIAL_CURVATURES};
use crate::gradient_apollonian::GradientApollonian;
use crate::gradient_standard::radius_curvature;
/// Points spread over a view around the gradient line, kept off its exact rational coordinates.
fn sample_points() -> impl Iterator<Item = DVec2> {
(-30..=40).flat_map(|x| (-25..=25).map(move |y| DVec2::new(x as f64 * 0.1 + 0.0013, y as f64 * 0.1 + 0.0007)))
}
/// The distance between two angles in turns, the short way around.
fn turn_distance(first: f64, second: f64) -> f64 {
let distance = (first - second).rem_euclid(1.);
distance.min(1. - distance)
}
/// Curvature pairs of every kind: circles crossing, nested, apart, and concentric, lines and points beside them, and nearly flat circles.
fn curvature_pairs() -> Vec<[f64; 2]> {
let mut pairs: Vec<[f64; 2]> = [
(0., 0.75),
(0.2, 1.5),
(2., -0.5),
(0.6, 0.6),
(-0.3, -0.3),
(0., -0.4),
(2., -1.),
(-0.5, 1.5),
(0.8, 1e9),
(-0.3, 1e9),
(1e9, 0.25),
(1e9, 2.),
(3000., -2500.),
(0.3, 2500.),
]
.into_iter()
.map(|(start, end)| [radius_curvature(start), radius_curvature(end)])
.collect();
pairs.extend([[1., 0.3], [1., 1.], [0.8, -1.], [0.4, 0.], [0., -0.4], [-0.3, 0.]]);
pairs
}
#[test]
fn the_linear_form_reads_across_the_gradient_line() {
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let chart = AcrossChart::new(LINEAR_CURVATURES[0], LINEAR_CURVATURES[1], model);
assert_eq!(chart, AcrossChart::Linear);
for point in sample_points() {
assert_eq!(chart.v(point), Some(point.y));
}
}
}
#[test]
fn the_radial_form_reads_the_angle_around_its_center() {
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let chart = AcrossChart::new(RADIAL_CURVATURES[0], RADIAL_CURVATURES[1], model);
for point in sample_points() {
let expected = point.y.atan2(point.x).rem_euclid(TAU) / TAU;
assert!(turn_distance(chart.v(point).unwrap(), expected) < 1e-12, "{model:?} at {point}");
}
// Clockwise on screen, from the seam along the gradient line
assert!((chart.v(DVec2::new(0., 1.)).unwrap() - 0.25).abs() < 1e-12);
assert!(chart.v(DVec2::new(0.5, 1e-9)).unwrap() < 1e-6 && chart.v(DVec2::new(0.5, -1e-9)).unwrap() > 1. - 1e-6);
}
}
#[test]
fn both_models_read_concentric_circles_around_their_center() {
// The start circle centered at its radius and the end at 1 minus its own share a center, with the end circle outside or inside the start circle
for start_radius in [-1., -0.5, 0.25, 2., 3.] {
let curvatures = [radius_curvature(start_radius), radius_curvature(1. - start_radius)];
let [standard, apollonian] = [GradientModel::Standard, GradientModel::Apollonian].map(|model| AcrossChart::new(curvatures[0], curvatures[1], model));
let cone = AcrossChart::Cone {
cone: Cone::between(start_radius, 1. - start_radius),
keep: None,
};
assert!(matches!(standard, AcrossChart::Concentric { .. }), "{standard:?}");
assert!(matches!(apollonian, AcrossChart::Concentric { .. }), "{apollonian:?}");
for point in sample_points() {
let expected = (point.y).atan2(point.x - start_radius).rem_euclid(TAU) / TAU;
for (chart, name) in [(standard, "Standard"), (apollonian, "Apollonian"), (cone, "cone")] {
let v = chart.v(point).unwrap_or_else(|| panic!("{name} leaves {point} unpainted with start radius {start_radius}"));
assert!(turn_distance(v, expected) < 1e-9, "{name} with start radius {start_radius} at {point}: {v} rather than {expected}");
}
}
}
}
#[test]
fn standard_contours_of_constant_position_are_rays_from_the_apex() {
// Off-center pairs with an apex where the cone's circles shrink to a point
for (start, end) in [(0., 0.75), (0.2, 1.5), (0.6, 0.3), (-0.3, -0.6), (2., -0.5)] {
let cone = Cone::between(start, end);
let chart = AcrossChart::new(radius_curvature(start), radius_curvature(end), GradientModel::Standard);
assert!(matches!(chart, AcrossChart::Cone { .. }), "({start}, {end}) should be a cone, not {chart:?}");
let delta_radius = cone.end_radius - cone.start_radius;
let apex_t = -cone.start_radius / delta_radius;
let apex = DVec2::new(cone.start_center + apex_t * (cone.end_center - cone.start_center), 0.);
for angle in (0..24).map(|step| (step as f64 + 0.37) * TAU / 24.) {
let direction = DVec2::from_angle(angle);
let positions: Vec<f64> = [0.2, 0.5, 1., 2., 4.].into_iter().filter_map(|distance| chart.v(apex + direction * distance)).collect();
for &v in &positions {
assert!(turn_distance(v, positions[0]) < 1e-9, "({start}, {end}) along the ray at {angle}: {positions:?}");
}
}
}
}
#[test]
fn across_paints_exactly_where_along_does() {
for curvatures in curvature_pairs() {
let standard = GradientStandard::new(curvatures[0], curvatures[1]);
let chart = AcrossChart::new(curvatures[0], curvatures[1], GradientModel::Standard);
// A line end's cut and a nearly flat cone's split are drawn as straight lines across the gradient line, which the cone drawn at the flattest radius only nears
let cut = match standard {
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => keep.map(|keep| keep.at),
GradientStandard::Profile { split, .. } => Some(split),
_ => None,
};
for point in sample_points() {
if cut.is_some_and(|cut| (point.x - cut).abs() < 0.1 * point.y.abs().max(0.1)) {
continue;
}
assert_eq!(chart.v(point).is_some(), standard.t(point).is_some(), "Standard curvatures {curvatures:?} at {point}: {chart:?}");
}
// Apollonian circles paint everywhere, read along or across them
let chart = AcrossChart::new(curvatures[0], curvatures[1], GradientModel::Apollonian);
assert!(chart.paints_everywhere(), "Apollonian curvatures {curvatures:?}: {chart:?}");
assert!(sample_points().all(|point| chart.v(point).is_some()), "Apollonian curvatures {curvatures:?}: {chart:?}");
}
}
#[test]
fn positions_change_continuously_except_at_seams_and_where_contours_meet() {
const STEP: f64 = 0.01;
for curvatures in curvature_pairs() {
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let chart = AcrossChart::new(curvatures[0], curvatures[1], model);
// Where every contour of constant position meets, and a cut across the gradient line
let mut singular_points = Vec::new();
let mut cut = None;
match chart {
AcrossChart::Concentric { center } => singular_points.push(DVec2::new(center, 0.)),
AcrossChart::Cone { cone, keep } => {
let apex_t = -cone.start_radius / (cone.end_radius - cone.start_radius);
singular_points.push(DVec2::new(cone.start_center + apex_t * (cone.end_center - cone.start_center), 0.));
cut = keep.map(|keep| keep.at);
}
AcrossChart::Mobius { numerator, denominator } => {
singular_points.push(DVec2::new(-numerator[1] / numerator[0], 0.));
singular_points.push(DVec2::new(-denominator[1] / denominator[0], 0.));
}
AcrossChart::Bipolar { center_x, half_height, .. } => {
singular_points.push(DVec2::new(center_x, half_height));
singular_points.push(DVec2::new(center_x, -half_height));
}
AcrossChart::Linear | AcrossChart::Nothing => {}
}
let near_singular = |point: DVec2| singular_points.iter().any(|singular| (point - *singular).length() < 0.2) || cut.is_some_and(|cut| (point.x - cut).abs() < 0.02);
for point in sample_points().filter(|&point| !near_singular(point)) {
for neighbor in [point + DVec2::new(STEP, 0.), point + DVec2::new(0., STEP)] {
if near_singular(neighbor) {
continue;
}
let (Some(v), Some(neighbor_v)) = (chart.v(point), chart.v(neighbor)) else { continue };
let change = if chart.winds() { turn_distance(v, neighbor_v) } else { (v - neighbor_v).abs() };
assert!(change < 0.05, "{model:?} curvatures {curvatures:?} from {point} to {neighbor}: {v} to {neighbor_v} in {chart:?}");
}
}
}
}
}
#[test]
fn the_bipolar_chart_nears_the_linear_forms_as_crossing_curvatures_flatten() {
// Over the view, the chart strays from `y` in proportion to the curvatures
for curvature in [1e-3, 1e-4, 1e-6] {
let tolerance = 300. * curvature;
for [start, end] in [[curvature, curvature], [curvature, 2. * curvature], [3. * curvature, curvature]] {
let chart = AcrossChart::new(start, end, GradientModel::Apollonian);
assert!(matches!(chart, AcrossChart::Bipolar { .. }), "({start}, {end}) should cross, not {chart:?}");
for point in sample_points() {
let v = chart.v(point).unwrap();
assert!((v - point.y).abs() < tolerance, "({start}, {end}) at {point}: {v}");
}
}
}
// Zero on the gradient line, and one unit per gradient length across its midpoint
let chart = AcrossChart::new(0.6, 0.4, GradientModel::Apollonian);
assert!(chart.v(DVec2::new(0.3, 0.)).unwrap().abs() < 1e-15);
let rate = (chart.v(DVec2::new(0.5, 1e-6)).unwrap() - chart.v(DVec2::new(0.5, -1e-6)).unwrap()) / 2e-6;
assert!((rate - 1.).abs() < 1e-6, "{rate}");
}
#[test]
fn apollonian_angles_run_around_the_limit_point_inside_the_end_contour() {
// The start point inside the end circle, which encloses the start point as its limit point
let start_point = AcrossChart::new(-1., 0.3, GradientModel::Apollonian);
let AcrossChart::Mobius { numerator, .. } = start_point else { panic!("{start_point:?}") };
assert!((-numerator[1] / numerator[0]).abs() < 1e-12, "{start_point:?}");
// The end a point, which is its own limit point
let end_point = AcrossChart::new(0.8, 1., GradientModel::Apollonian);
let AcrossChart::Mobius { numerator, .. } = end_point else { panic!("{end_point:?}") };
assert!((-numerator[1] / numerator[0] - 1.).abs() < 1e-9, "{end_point:?}");
// Near the enclosed limit point, the position is the angle around it, from the seam on the +x side
for angle in [0.1, 1., 2., 3., 4., 5., 6.] {
let point = DVec2::from_angle(angle) * 1e-7;
assert!(turn_distance(start_point.v(point).unwrap(), angle / TAU) < 1e-5, "at angle {angle}");
}
}
#[test]
fn the_apollonian_chart_is_found_for_every_curvature_pair() {
for start_step in -10..=10 {
for end_step in -10..=10 {
let (start, end) = (start_step as f64 / 10., end_step as f64 / 10.);
let chart = AcrossChart::new(start, end, GradientModel::Apollonian);
let along = GradientApollonian::new(start, end);
for point in sample_points() {
let v = chart.v(point);
assert!(v.is_some_and(|v| !v.is_nan()), "({start}, {end}) at {point}: {v:?} in {chart:?}");
assert!(!along.t(point).is_nan());
}
}
}
}
#[test]
fn extreme_curvatures_compute_finitely() {
let extremes = [4e-309, -4e-309, 1e-300, 6e-31, -6e-31, 7e-31, -7e-31, 1e-17, -1e-17];
let curvatures = extremes.iter().flat_map(|&extreme| {
[
[extreme, 0.],
[0., extreme],
[extreme, 0.3],
[-0.3, extreme],
[extreme, extreme],
[extreme, -extreme],
[extreme, 1. - 1e-16],
]
});
for [start, end] in curvatures {
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let chart = AcrossChart::new(start, end, model);
for point in sample_points() {
let v = chart.v(point);
assert!(v.is_none_or(|v| !v.is_nan()), "{model:?} curvatures ({start}, {end}) at {point}: {chart:?}");
}
}
}
}
}
@@ -60,20 +60,20 @@ impl AxisCircle {
/// A point on the gradient line in homogeneous form, `numerator / denominator`, so the point at infinity is just a zero denominator. /// A point on the gradient line in homogeneous form, `numerator / denominator`, so the point at infinity is just a zero denominator.
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
struct Homogeneous { pub(crate) struct Homogeneous {
numerator: f64, pub(crate) numerator: f64,
denominator: f64, pub(crate) denominator: f64,
} }
impl Homogeneous { impl Homogeneous {
const INFINITY: Self = Self { numerator: 1., denominator: 0. }; pub(crate) const INFINITY: Self = Self { numerator: 1., denominator: 0. };
fn value(&self) -> Option<f64> { pub(crate) fn value(&self) -> Option<f64> {
(self.denominator != 0.).then(|| self.numerator / self.denominator) (self.denominator != 0.).then(|| self.numerator / self.denominator)
} }
/// Scaled so the larger of its two parts has a magnitude of 1, keeping products of points in range. /// Scaled so the larger of its two parts has a magnitude of 1, keeping products of points in range.
fn normalized(self) -> Self { pub(crate) fn normalized(self) -> Self {
let scale = self.numerator.abs().max(self.denominator.abs()); let scale = self.numerator.abs().max(self.denominator.abs());
if scale == 0. { if scale == 0. {
return self; return self;
@@ -85,6 +85,51 @@ impl Homogeneous {
} }
} }
/// How the family of circles two end contours span is laid out.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum CircleFamily {
/// The end contours cross, so every member passes through the two points where the line member at `radical_x` meets them.
Crossing { radical_x: f64 },
/// The members nest around two limit points (normalized), which coincide where the end contours touch.
Nesting { limit_points: [Homogeneous; 2] },
}
impl CircleFamily {
pub(crate) fn of(start: AxisCircle, end: AxisCircle) -> Self {
// The members of the family that are points have a zero discriminant, which as a quadratic form in the two members'
// weights has these coefficients. Its determinant says whether the family has two such points (it's hyperbolic), none
// (elliptic, where the end contours cross), or one (parabolic, where they touch).
let point_quadratic_start = start.b * start.b - 4. * start.a * start.c;
let point_quadratic_cross = start.b * end.b - 2. * (start.a * end.c + end.a * start.c);
let point_quadratic_end = end.b * end.b - 4. * end.a * end.c;
let determinant = point_quadratic_start * point_quadratic_end - point_quadratic_cross * point_quadratic_cross;
let scale = point_quadratic_start.abs().max(point_quadratic_end.abs()).max(point_quadratic_cross.abs()).max(f64::MIN_POSITIVE);
if determinant > 1e-12 * scale * scale {
// The line through the two points where the end contours cross is the member with no curvature
let line = start.combine(end.a, &end, -start.a);
return Self::Crossing { radical_x: -line.c / line.b };
}
// The limit points are where the point members sit, with a point member of no curvature being the point at infinity
let limit_points = point_member_weights(point_quadratic_start, point_quadratic_cross, point_quadratic_end).map(|(start_weight, end_weight)| {
let member = start.combine(start_weight, &end, end_weight);
let magnitude = member.a.abs().max(member.b.abs()).max(member.c.abs());
if member.a.abs() <= 1e-12 * magnitude {
return Homogeneous::INFINITY;
}
Homogeneous {
numerator: -member.b,
denominator: 2. * member.a,
}
.normalized()
});
Self::Nesting { limit_points }
}
}
/// The roots of `a y² + b y + c = 0`, in homogeneous form so a vanishing `a` puts a root at infinity rather than dividing by zero. /// The roots of `a y² + b y + c = 0`, in homogeneous form so a vanishing `a` puts a root at infinity rather than dividing by zero.
fn solve_quadratic(a: f64, b: f64, c: f64) -> [Homogeneous; 2] { fn solve_quadratic(a: f64, b: f64, c: f64) -> [Homogeneous; 2] {
let discriminant = (b * b - 4. * a * c).max(0.); let discriminant = (b * b - 4. * a * c).max(0.);
@@ -139,37 +184,10 @@ impl GradientApollonian {
let start = AxisCircle::start(start_curvature); let start = AxisCircle::start(start_curvature);
let end = AxisCircle::end(end_curvature); let end = AxisCircle::end(end_curvature);
// The members of the family that are points have a zero discriminant, which as a quadratic form in the two members' let limit_points = match CircleFamily::of(start, end) {
// weights has these coefficients. Its determinant says whether the family has two such points (it's hyperbolic), none CircleFamily::Crossing { radical_x } => return Self::with_band(start, end, CrossingSelection::SameSideAs { radical_x }, None, 0., 1., svg_stand_in),
// (elliptic, where the end contours cross), or one (parabolic, where they touch). CircleFamily::Nesting { limit_points } => limit_points,
let point_quadratic_start = start.b * start.b - 4. * start.a * start.c; };
let point_quadratic_cross = start.b * end.b - 2. * (start.a * end.c + end.a * start.c);
let point_quadratic_end = end.b * end.b - 4. * end.a * end.c;
let determinant = point_quadratic_start * point_quadratic_end - point_quadratic_cross * point_quadratic_cross;
let scale = point_quadratic_start.abs().max(point_quadratic_end.abs()).max(point_quadratic_cross.abs()).max(f64::MIN_POSITIVE);
if determinant > 1e-12 * scale * scale {
// The line through the two points where the end contours cross is the member with no curvature
let line = start.combine(end.a, &end, -start.a);
let radical_x = -line.c / line.b;
return Self::with_band(start, end, CrossingSelection::SameSideAs { radical_x }, None, 0., 1., svg_stand_in);
}
// The limit points are where the point members sit, with a point member of no curvature being the point at infinity
let limit_points = point_member_weights(point_quadratic_start, point_quadratic_cross, point_quadratic_end).map(|(start_weight, end_weight)| {
let member = start.combine(start_weight, &end, end_weight);
let magnitude = member.a.abs().max(member.b.abs()).max(member.c.abs());
if member.a.abs() <= 1e-12 * magnitude {
return Homogeneous::INFINITY;
}
Homogeneous {
numerator: -member.b,
denominator: 2. * member.a,
}
.normalized()
});
// Each crossing's place relative to the limit points, negative between them and positive beyond them // Each crossing's place relative to the limit points, negative between them and positive beyond them
let arc_quadratic = arc_quadratic(limit_points); let arc_quadratic = arc_quadratic(limit_points);
@@ -10,7 +10,8 @@
//! Where SVG 2 leaves the plane unpainted, so does it. A line end takes SVG 2's own limit as that end's circle flattens bowing //! Where SVG 2 leaves the plane unpainted, so does it. A line end takes SVG 2's own limit as that end's circle flattens bowing
//! toward the other end. The Apollonian drawing of the same curvatures is in [`crate::gradient_apollonian`]. //! toward the other end. The Apollonian drawing of the same curvatures is in [`crate::gradient_apollonian`].
use crate::gradient::{GradientForm, GradientModel, wrapped_curvature}; use crate::gradient::{GradientDirection, GradientForm, GradientModel, wrapped_curvature};
use crate::gradient_across::{AcrossChart, GradientAcross};
use crate::gradient_apollonian::GradientApollonian; use crate::gradient_apollonian::GradientApollonian;
use glam::{DAffine2, DVec2}; use glam::{DAffine2, DVec2};
use std::f64::consts::FRAC_PI_2; use std::f64::consts::FRAC_PI_2;
@@ -345,7 +346,7 @@ impl GradientStandard {
} }
} }
/// How a gradient's contours are laid out, decided by its curvatures and model. /// How a gradient's contours are laid out, decided by its curvatures and model, and how its colors run, decided by its direction.
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, Copy, PartialEq)]
pub enum GradientShape { pub enum GradientShape {
/// The linear form: both ends are lines. /// The linear form: both ends are lines.
@@ -356,19 +357,27 @@ pub enum GradientShape {
Standard(GradientStandard), Standard(GradientStandard),
/// Any other curvatures, drawn as Apollonian circles. /// Any other curvatures, drawn as Apollonian circles.
Apollonian(GradientApollonian), Apollonian(GradientApollonian),
/// Any curvatures, with the colors running around the contours rather than from one end to the other.
Across(GradientAcross),
} }
impl GradientShape { impl GradientShape {
/// The shape of a gradient with these curvatures, each wrapped like [`wrapped_curvature`] and a line where it isn't finite, placed by `transform`. /// The shape of a gradient with these curvatures, each wrapped like [`wrapped_curvature`] and a line where it isn't finite, placed by `transform`.
/// With curvatures other than a form's, a collapsed placement (like a zero-length gradient line) leaves the last stop's color, as SVG does. /// With curvatures other than a form's, a collapsed placement (like a zero-length gradient line) leaves the last stop's color, as SVG does.
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel, transform: DAffine2) -> Self { pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel, direction: GradientDirection, transform: DAffine2) -> Self {
let [start, end] = [start_curvature, end_curvature].map(|curvature| wrapped_curvature(curvature, 0.)); let [start, end] = [start_curvature, end_curvature].map(|curvature| wrapped_curvature(curvature, 0.));
let form = GradientForm::from_curvatures([start, end]);
let collapsed = !transform.matrix2.determinant().recip().is_finite();
match GradientForm::from_curvatures([start, end]) { match (form, direction) {
Some(GradientForm::Linear) => Self::Linear, (None, _) if collapsed => Self::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }),
Some(GradientForm::Radial) => Self::Radial, (_, GradientDirection::Across) => Self::Across(GradientAcross {
None if !transform.matrix2.determinant().recip().is_finite() => Self::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }), chart: AcrossChart::new(start, end, model),
None if model == GradientModel::Apollonian => { form,
}),
(Some(GradientForm::Linear), GradientDirection::Along) => Self::Linear,
(Some(GradientForm::Radial), GradientDirection::Along) => Self::Radial,
(None, GradientDirection::Along) if model == GradientModel::Apollonian => {
// Identical end circles span no family of circles, so they draw the plain ramp // Identical end circles span no family of circles, so they draw the plain ramp
let (start_radius, end_radius) = (curvature_radius(start), curvature_radius(end)); let (start_radius, end_radius) = (curvature_radius(start), curvature_radius(end));
if start_radius.is_finite() && end_radius.is_finite() && Cone::between(start_radius, end_radius).is_identical() { if start_radius.is_finite() && end_radius.is_finite() && Cone::between(start_radius, end_radius).is_identical() {
@@ -377,13 +386,22 @@ impl GradientShape {
Self::Apollonian(GradientApollonian::new(start, end)) Self::Apollonian(GradientApollonian::new(start, end))
} }
None => Self::Standard(GradientStandard::new(start, end)), (None, GradientDirection::Along) => Self::Standard(GradientStandard::new(start, end)),
} }
} }
/// Whether its position can fall before the start, which only a radial gradient's can't since its distance from the center never goes below zero. /// Whether its position can fall before the start, which a radial gradient's distance from its center and an angle around the contours can't.
pub fn reaches_before_start(&self) -> bool { pub fn reaches_before_start(&self) -> bool {
!matches!(self, Self::Radial) match self {
Self::Radial => false,
Self::Across(across) => !across.chart.winds(),
Self::Linear | Self::Standard(_) | Self::Apollonian(_) => true,
}
}
/// Whether its position can fall past the end, which an angle around the contours can't.
pub fn reaches_past_end(&self) -> bool {
!matches!(self, Self::Across(across) if across.chart.winds())
} }
/// Whether it paints every point, rather than leaving some unpainted. /// Whether it paints every point, rather than leaving some unpainted.
@@ -391,11 +409,15 @@ impl GradientShape {
match self { match self {
Self::Linear | Self::Radial | Self::Apollonian(_) => true, Self::Linear | Self::Radial | Self::Apollonian(_) => true,
Self::Standard(gradient) => gradient.paints_everywhere(), Self::Standard(gradient) => gradient.paints_everywhere(),
Self::Across(across) => across.chart.paints_everywhere(),
} }
} }
/// Whether SVG draws it exactly, which it does unless it's Apollonian circles, other than those between concentric end circles drawn as SVG 2's cone. /// Whether SVG draws it exactly, which it does unless it's Apollonian circles (other than those between concentric end circles drawn as SVG 2's cone), or read across contours other than the linear form's.
pub fn svg_draws_exactly(&self) -> bool { pub fn svg_draws_exactly(&self) -> bool {
if let Self::Across(across) = self {
return across.chart.svg_draws_exactly();
}
let Self::Apollonian(GradientApollonian { start, end, svg_stand_in, .. }) = self else { let Self::Apollonian(GradientApollonian { start, end, svg_stand_in, .. }) = self else {
return true; return true;
}; };
@@ -743,7 +765,7 @@ mod tests {
fn a_zero_length_gradient_line_leaves_the_last_stop_once_curved() { fn a_zero_length_gradient_line_leaves_the_last_stop_once_curved() {
let collapsed = DAffine2::from_cols(DVec2::ZERO, DVec2::Y, DVec2::new(3., 4.)); let collapsed = DAffine2::from_cols(DVec2::ZERO, DVec2::Y, DVec2::new(3., 4.));
for model in [GradientModel::Standard, GradientModel::Apollonian] { for model in [GradientModel::Standard, GradientModel::Apollonian] {
let shape = |[start, end]: [f64; 2]| GradientShape::new(start, end, model, collapsed); let shape = |[start, end]: [f64; 2]| GradientShape::new(start, end, model, GradientDirection::Along, collapsed);
assert_eq!(shape([0.3, 0.2]), GradientShape::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None })); assert_eq!(shape([0.3, 0.2]), GradientShape::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }));
// The forms keep drawing as they always have // The forms keep drawing as they always have
@@ -755,7 +777,7 @@ mod tests {
#[test] #[test]
fn apollonian_gradients_stand_in_for_svg_with_its_own_drawing_where_that_paints_everywhere() { fn apollonian_gradients_stand_in_for_svg_with_its_own_drawing_where_that_paints_everywhere() {
let placement = DAffine2::IDENTITY; let placement = DAffine2::IDENTITY;
let stand_in = |curvatures: [f64; 2]| match GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, placement) { let stand_in = |curvatures: [f64; 2]| match GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, placement) {
GradientShape::Apollonian(apollonian) => apollonian.svg_stand_in, GradientShape::Apollonian(apollonian) => apollonian.svg_stand_in,
shape => panic!("curvatures {curvatures:?} should draw Apollonian circles, not {shape:?}"), shape => panic!("curvatures {curvatures:?} should draw Apollonian circles, not {shape:?}"),
}; };
@@ -773,22 +795,25 @@ mod tests {
// Identical end circles span no family of circles, so they draw the plain ramp everywhere // Identical end circles span no family of circles, so they draw the plain ramp everywhere
let identical = radius_curvature(0.5); let identical = radius_curvature(0.5);
assert_eq!(GradientShape::new(identical, identical, GradientModel::Apollonian, placement), GradientShape::Standard(plain_ramp)); assert_eq!(
GradientShape::new(identical, identical, GradientModel::Apollonian, GradientDirection::Along, placement),
GradientShape::Standard(plain_ramp)
);
// The forms stay native under either model // The forms stay native under either model
assert_eq!(GradientShape::new(0., 0., GradientModel::Apollonian, placement), GradientShape::Linear); assert_eq!(GradientShape::new(0., 0., GradientModel::Apollonian, GradientDirection::Along, placement), GradientShape::Linear);
assert_eq!(GradientShape::new(-1., 0.5, GradientModel::Apollonian, placement), GradientShape::Radial); assert_eq!(GradientShape::new(-1., 0.5, GradientModel::Apollonian, GradientDirection::Along, placement), GradientShape::Radial);
} }
#[test] #[test]
fn svg_draws_every_shape_exactly_but_apollonian_circles_it_cant_draw_as_a_cone() { fn svg_draws_every_shape_exactly_but_apollonian_circles_it_cant_draw_as_a_cone() {
let exact = |curvatures: [f64; 2], model: GradientModel| GradientShape::new(curvatures[0], curvatures[1], model, DAffine2::IDENTITY).svg_draws_exactly(); let exact = |curvatures: [f64; 2], model: GradientModel| GradientShape::new(curvatures[0], curvatures[1], model, GradientDirection::Along, DAffine2::IDENTITY).svg_draws_exactly();
// Concentric end circles, the start centered at its radius and the end at 1 minus its own, have Apollonian circles that are SVG 2's cone // Concentric end circles, the start centered at its radius and the end at 1 minus its own, have Apollonian circles that are SVG 2's cone
for [start, end] in [[2., -1.], [-0.5, 1.5], [0.25, 0.75]] { for [start, end] in [[2., -1.], [-0.5, 1.5], [0.25, 0.75]] {
let curvatures = [radius_curvature(start), radius_curvature(end)]; let curvatures = [radius_curvature(start), radius_curvature(end)];
assert!(matches!( assert!(matches!(
GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, DAffine2::IDENTITY), GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, DAffine2::IDENTITY),
GradientShape::Apollonian(_) GradientShape::Apollonian(_)
)); ));
assert!(exact(curvatures, GradientModel::Apollonian), "radii {start} and {end}"); assert!(exact(curvatures, GradientModel::Apollonian), "radii {start} and {end}");
+4 -1
View File
@@ -2,6 +2,7 @@
extern crate log; extern crate log;
pub mod gradient; pub mod gradient;
pub mod gradient_across;
pub mod gradient_apollonian; pub mod gradient_apollonian;
pub mod gradient_standard; pub mod gradient_standard;
pub mod math; pub mod math;
@@ -9,7 +10,9 @@ pub mod vector;
// Re-export commonly used types at the crate root // Re-export commonly used types at the crate root
pub use core_types as gcore; pub use core_types as gcore;
pub use gradient::{Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop}; pub use gradient::{
Gradient, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop,
};
pub use math::QuadExt; pub use math::QuadExt;
pub use vector::Vector; pub use vector::Vector;
pub use vector::reference_point::ReferencePoint; pub use vector::reference_point::ReferencePoint;
@@ -7,7 +7,7 @@ use crate::WgpuExecutor;
use core_types::blending::BlendMode; use core_types::blending::BlendMode;
use glam::{DAffine2, UVec2}; use glam::{DAffine2, UVec2};
use graphic_types::MinimumMaximumMode; use graphic_types::MinimumMaximumMode;
use graphic_types::vector_types::gradient::{GradientModel, GradientSpread}; use graphic_types::vector_types::gradient::{GradientDirection, GradientModel, GradientSpread};
use rendering::vello_scene_builder::VelloSceneBuilder; use rendering::vello_scene_builder::VelloSceneBuilder;
use vello_gpu::kurbo::{Affine, BezPath, Line, ParamCurve, PathSeg, Point, Rect, Stroke, Vec2}; use vello_gpu::kurbo::{Affine, BezPath, Line, ParamCurve, PathSeg, Point, Rect, Stroke, Vec2};
use vello_gpu::peniko::{self, Color, Fill}; use vello_gpu::peniko::{self, Color, Fill};
@@ -555,7 +555,7 @@ fn apollonian_gradients_match_their_cpu_evaluation() {
[0.9, 0.6], [0.9, 0.6],
[0.6, 1.], [0.6, 1.],
] { ] {
let GradientShape::Apollonian(parameters) = GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, placement) else { let GradientShape::Apollonian(parameters) = GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, placement) else {
panic!("curvatures {curvatures:?} should draw Apollonian circles"); panic!("curvatures {curvatures:?} should draw Apollonian circles");
}; };
let graphic = curved_black_to_white_gradient(placement, Some(curvatures), GradientModel::Apollonian); let graphic = curved_black_to_white_gradient(placement, Some(curvatures), GradientModel::Apollonian);
@@ -575,6 +575,114 @@ fn apollonian_gradients_match_their_cpu_evaluation() {
} }
} }
#[test]
fn across_gradients_match_their_cpu_evaluation() {
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::radius_curvature;
use std::fmt::Write;
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100), and then sheared
let placements = [
DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.)),
DAffine2::from_cols(DVec2::new(50., 10.), DVec2::new(15., 35.), DVec2::new(60., 100.)),
];
let radius = radius_curvature;
let (standard, apollonian) = (GradientModel::Standard, GradientModel::Apollonian);
let settings = [
([0., 0.], standard, "the linear form"),
([-1., 0.5], standard, "the radial form"),
([radius(2.), radius(-1.)], standard, "concentric circles"),
([-1., radius(0.75)], standard, "a focal point inside the end circle, off its center"),
([radius(0.2), radius(1.5)], standard, "a focal circle nested inside the end circle"),
([radius(0.6), radius(0.6)], standard, "crossing circles"),
([radius(-0.2), radius(-0.4)], standard, "separate circles"),
([radius(0.8), 0.], standard, "an end line beside a start circle reaching past the end"),
([radius(0.45), 0.], standard, "an end line beside a start circle nearly reaching the end"),
([radius(0.6), 0.], standard, "an end line beside a start circle just past the end"),
([radius(3000.), radius(-4000.)], standard, "both ends nearly flat around an apex"),
([radius(2.), radius(-1.)], apollonian, "concentric Apollonian circles"),
([1., 0.3], apollonian, "Apollonian circles around the start point"),
([0.9, 0.2], apollonian, "nested Apollonian circles"),
([0.8, 1.], apollonian, "Apollonian circles around the end point"),
([1., 1.], apollonian, "Apollonian circles of two points"),
([0.6, 0.6], apollonian, "crossing Apollonian circles"),
([0.5, 0.25], apollonian, "crossing Apollonian circles of different sizes"),
];
let mut report = String::new();
for (curvatures, model, setting) in settings {
for placement in placements {
for spread in [GradientSpread::Pad, GradientSpread::Repeat] {
let Some(line) = compare_across_gradient_with_cpu(curvatures, model, placement, spread, setting) else {
return;
};
let _ = writeln!(report, "{line}");
}
}
}
eprintln!("{report}");
}
/// Renders a black to white gradient read across its contours, with these curvatures and model, placed by `placement` and read with `spread`, into a
/// 200 by 200 view, and checks each pixel against the CPU's evaluation, returning a line describing how they compare, or `None` without a GPU.
fn compare_across_gradient_with_cpu(curvatures: [f64; 2], model: GradientModel, placement: DAffine2, spread: GradientSpread, setting: &str) -> Option<String> {
use core_types::list::{ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_SPREAD};
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::GradientShape;
use rendering::{Render, RenderParams};
let size = UVec2::new(200, 200);
let graphic = match curved_black_to_white_gradient(placement, Some(curvatures), model) {
graphic_types::Graphic::Gradient(item) => {
graphic_types::Graphic::Gradient(item.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across).with_attribute(ATTR_GRADIENT_SPREAD, spread))
}
graphic => graphic,
};
let pixels = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?;
// The CPU's level at a point on the screen, or `None` where it's unpainted, which the spread repeats only where the position doesn't wind
let GradientShape::Across(across) = GradientShape::new(curvatures[0], curvatures[1], model, GradientDirection::Across, placement) else {
panic!("{setting} should be read across its contours");
};
let to_gradient = placement.inverse();
let level_at = |point: DVec2| {
let v = across.chart.v(to_gradient.transform_point2(point))?;
let position = match spread {
_ if across.chart.winds() => v,
GradientSpread::Repeat => v - v.floor(),
_ => v.clamp(0., 1.),
};
Some((position * 255.).round() as i32)
};
let expected = |x: i32, y: i32| level_at(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
// Each pixel takes the level at its center, except within two pixels of a seam where the position wraps, a step, or an edge of the painted area, which only rounding and antialiasing tell apart
let (mut worst, mut beside_steps, mut disagreements) = (0, 0, 0);
for y in 2..size.y as i32 - 2 {
for x in 2..size.x as i32 - 2 {
let neighborhood: Vec<Option<i32>> = (-2..=2).flat_map(|dy| (-2..=2).map(move |dx| (x + dx, y + dy))).map(|(x, y)| expected(x, y)).collect();
let painted_neighbors = neighborhood.iter().filter(|level| level.is_some()).count();
let levels = neighborhood.iter().flatten();
let (lowest, highest) = (*levels.clone().min().unwrap_or(&0), *levels.max().unwrap_or(&255));
let [red, _, _, alpha] = pixel(&pixels, size, x as u32, y as u32);
match (alpha, expected(x, y)) {
(0, None) => {}
(255, Some(level)) if painted_neighbors == 25 && highest - lowest <= 64 => worst = worst.max((red as i32 - level).abs()),
(255, Some(_)) => beside_steps += 1,
_ if painted_neighbors != 0 && painted_neighbors != 25 => {}
_ => disagreements += 1,
}
}
}
let context = format!("{setting} {curvatures:?}, {spread:?}, placed by {placement:?}");
assert!(worst <= 3, "{context}: up to {worst} levels from the CPU");
assert_eq!(disagreements, 0, "{context}: pixels disagreeing with the CPU on being painted");
Some(format!("{context}: within {worst} levels, {beside_steps} pixels beside seams and steps"))
}
#[test] #[test]
fn one_stop_curved_gradients_leave_their_gaps_unpainted() { fn one_stop_curved_gradients_leave_their_gaps_unpainted() {
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, Item}; use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, Item};
+8
View File
@@ -1952,6 +1952,14 @@ fn gradient_model(_: impl Ctx, gradient: Item<Gradient>, model: Item<vector_type
gradient gradient
} }
/// Sets which way the colors of each gradient in the input list run: Along, from the start contour to the end contour, or Across, around each contour.
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"))]
fn gradient_direction(_: impl Ctx, gradient: Item<Gradient>, direction: Item<vector_types::GradientDirection>) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_DIRECTION, *direction.element());
gradient
}
/// Sets how each gradient in the input list extends past its endpoints: Pad, Reflect, Repeat, or Clear. /// Sets how each gradient in the input list extends past its endpoints: Pad, Reflect, Repeat, or Clear.
#[node_macro::node(category("Gradient"), icon("NodeGradientSpread"))] #[node_macro::node(category("Gradient"), icon("NodeGradientSpread"))]
fn gradient_spread(_: impl Ctx, gradient: Item<Gradient>, gradient_spread: Item<vector_types::GradientSpread>) -> Item<Gradient> { fn gradient_spread(_: impl Ctx, gradient: Item<Gradient>, gradient_spread: Item<vector_types::GradientSpread>) -> Item<Gradient> {
+78 -5
View File
@@ -10,8 +10,8 @@ use core_types::math::spread::spread_factors;
use core_types::transform::{Footprint, Transform}; use core_types::transform::{Footprint, Transform};
use core_types::uuid::NodeId; use core_types::uuid::NodeId;
use core_types::{ use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE,
ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx, ExtractAll, InjectFootprint, OwnedContextImpl, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx, ExtractAll, InjectFootprint, OwnedContextImpl,
}; };
use core_types::{Interrupt, NodeError}; use core_types::{Interrupt, NodeError};
use glam::{DAffine2, DMat2, DVec2}; use glam::{DAffine2, DMat2, DVec2};
@@ -24,7 +24,7 @@ use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArcle
use rand::{RngExt, SeedableRng}; use rand::{RngExt, SeedableRng};
use std::collections::hash_map::DefaultHasher; use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use vector_types::gradient::{build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box}; use vector_types::gradient::{GradientDirection, GradientModel, build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box};
use vector_types::vector::SetVectorPaths; use vector_types::vector::SetVectorPaths;
use vector_types::vector::algorithms::bezpath_algorithms::{ use vector_types::vector::algorithms::bezpath_algorithms::{
self, PoissonDiskError, PoissonDiskSampler, SampleCountError, TValue, bezpath_area_centroid_and_area, bezpath_length_centroid_and_length, eval_pathseg_euclidean, evaluate_bezpath, split_bezpath, self, PoissonDiskError, PoissonDiskSampler, SampleCountError, TValue, bezpath_area_centroid_and_area, bezpath_length_centroid_and_length, eval_pathseg_euclidean, evaluate_bezpath, split_bezpath,
@@ -408,7 +408,7 @@ fn vary_cover_colors<T: VectorListIterMut>(
} }
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry. /// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
#[node_macro::node(category("Vector: Style"), icon("NodeFill"), path(graphene_core::vector), inspector("fill_inspector"), version(2))] #[node_macro::node(category("Vector: Style"), icon("NodeFill"), path(graphene_core::vector), inspector("fill_inspector"), version(3))]
fn fill<V>( fn fill<V>(
_: impl Ctx, _: impl Ctx,
/// The content with vector paths to apply the fill style to. /// The content with vector paths to apply the fill style to.
@@ -421,19 +421,22 @@ fn fill<V>(
_end_curvature: Item<f64>, _end_curvature: Item<f64>,
_has_transform: Item<bool>, _has_transform: Item<bool>,
_transform: Item<DAffine2>, _transform: Item<DAffine2>,
_model: Item<GradientModel>,
_direction: Item<GradientDirection>,
) -> Item<V> ) -> Item<V>
where where
Item<V>: VectorItemMut + Send, Item<V>: VectorItemMut + Send,
{ {
let (_start_curvature, _end_curvature) = (_start_curvature.into_element(), _end_curvature.into_element()); let (_start_curvature, _end_curvature) = (_start_curvature.into_element(), _end_curvature.into_element());
let (_has_transform, _transform) = (_has_transform.into_element(), *_transform.element()); let (_has_transform, _transform) = (_has_transform.into_element(), *_transform.element());
let (_model, _direction) = (_model.into_element(), _direction.into_element());
let mut content = content; let mut content = content;
// Keeping the wire envelope's attributes would nest the paint as a group, changing how it renders, so only its effects carry over // Keeping the wire envelope's attributes would nest the paint as a group, changing how it renders, so only its effects carry over
let mut paint = paint_with_envelope_effects(paint); let mut paint = paint_with_envelope_effects(paint);
// Stamp the gradient styling inputs onto any gradient paint missing them, whether the paint arrived as a picker value or a wire // Stamp the gradient styling inputs onto any gradient paint missing them, whether the paint arrived as a picker value or a wire
// TODO: Stop reading whether the gradient has curvatures or a transform, since an absent attribute should mean the same as its default. // TODO: Stop reading whether the gradient has curvatures, a model, a direction, or a transform, since an absent attribute should mean the same as its default.
// These reads tell a gradient picked in a widget, which needs styling and placing, from a wired one carrying its own, until paint inputs can tell those apart by type. // These reads tell a gradient picked in a widget, which needs styling and placing, from a wired one carrying its own, until paint inputs can tell those apart by type.
let (needs_curvatures, needs_transform) = match &paint { let (needs_curvatures, needs_transform) = match &paint {
Graphic::Gradient(item) => ( Graphic::Gradient(item) => (
@@ -446,6 +449,18 @@ where
), ),
_ => (false, false), _ => (false, false),
}; };
// The model and direction are stamped only when they differ from the default an absent attribute already reads as
let (needs_model, needs_direction) = match &paint {
Graphic::Gradient(item) => (
_model != GradientModel::default() && item.attribute::<GradientModel>(ATTR_GRADIENT_MODEL).is_none(),
_direction != GradientDirection::default() && item.attribute::<GradientDirection>(ATTR_GRADIENT_DIRECTION).is_none(),
),
Graphic::GradientList(list) => (
_model != GradientModel::default() && list.iter_attribute_values::<GradientModel>(ATTR_GRADIENT_MODEL).is_none(),
_direction != GradientDirection::default() && list.iter_attribute_values::<GradientDirection>(ATTR_GRADIENT_DIRECTION).is_none(),
),
_ => (false, false),
};
let stamped_transform = needs_transform.then(|| { let stamped_transform = needs_transform.then(|| {
// Without an explicit placement, derive one covering the paint target's bounding box (the CSS `auto` behavior) // Without an explicit placement, derive one covering the paint target's bounding box (the CSS `auto` behavior)
@@ -483,6 +498,12 @@ where
if let Some(transform) = stamped_transform { if let Some(transform) = stamped_transform {
item.set_attribute(ATTR_TRANSFORM, transform); item.set_attribute(ATTR_TRANSFORM, transform);
} }
if needs_model {
item.set_attribute(ATTR_GRADIENT_MODEL, _model);
}
if needs_direction {
item.set_attribute(ATTR_GRADIENT_DIRECTION, _direction);
}
} }
Graphic::GradientList(list) => { Graphic::GradientList(list) => {
if needs_curvatures { if needs_curvatures {
@@ -497,6 +518,13 @@ where
*value = transform; *value = transform;
} }
} }
if needs_model {
list.iter_attribute_values_mut_or_default::<GradientModel>(ATTR_GRADIENT_MODEL).for_each(|value| *value = _model);
}
if needs_direction {
list.iter_attribute_values_mut_or_default::<GradientDirection>(ATTR_GRADIENT_DIRECTION)
.for_each(|value| *value = _direction);
}
} }
_ => {} _ => {}
} }
@@ -4944,6 +4972,51 @@ mod test {
assert!(appearance.has_painted_cover(Cover::Fill), "the fill of a rank-0 vector should be styled like a list element"); assert!(appearance.has_painted_cover(Cover::Fill), "the fill of a rank-0 vector should be styled like a list element");
} }
// Fill gives a gradient it paints its model and direction where the gradient lacks them, unless they're the defaults an absent one reads as
#[test]
fn fill_stamps_a_gradients_model_and_direction_only_where_missing() {
let filled = |gradient: Item<Gradient>, model: GradientModel, direction: GradientDirection| {
let square = create_vector_item(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY), DAffine2::IDENTITY);
let filled = super::fill(
Footprint::default(),
square,
item(Graphic::Gradient(gradient)),
item(Color::BLACK),
item(Gradient::default()),
item(0.),
item(0.),
item(false),
item(DAffine2::IDENTITY),
item(model),
item(direction),
);
let appearance = filled.attribute::<Appearance>(ATTR_APPEARANCE).expect("the fill should give the square an appearance");
let Some(Graphic::Gradient(gradient)) = appearance.first_paint_of(Cover::Fill) else {
panic!("the fill should paint the gradient")
};
(
gradient.attribute::<GradientModel>(ATTR_GRADIENT_MODEL).copied(),
gradient.attribute::<GradientDirection>(ATTR_GRADIENT_DIRECTION).copied(),
)
};
let plain = item(Gradient::from(vec![Color::BLACK, Color::WHITE]));
assert_eq!(filled(plain.clone(), GradientModel::Standard, GradientDirection::Along), (None, None));
assert_eq!(
filled(plain.clone(), GradientModel::Apollonian, GradientDirection::Across),
(Some(GradientModel::Apollonian), Some(GradientDirection::Across))
);
// A gradient's own model and direction stay, even at their defaults
let own = plain
.with_attribute(ATTR_GRADIENT_MODEL, GradientModel::Standard)
.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Along);
assert_eq!(
filled(own, GradientModel::Apollonian, GradientDirection::Across),
(Some(GradientModel::Standard), Some(GradientDirection::Along))
);
}
// Fill's automatic gradient placement measures rank-0 vector content instead of falling back to the unit box // Fill's automatic gradient placement measures rank-0 vector content instead of falling back to the unit box
#[test] #[test]
fn vector_item_mut_reaches_a_rank_0_vector_graphic() { fn vector_item_mut_reaches_a_rank_0_vector_graphic() {