mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
865b6be603 | ||
|
|
de786aa381 |
No files matched your search
@@ -5,4 +5,5 @@ mod passthrough_from_read_attribute_gradient_form_node;
|
|||||||
mod passthrough_from_footprint_value;
|
mod passthrough_from_footprint_value;
|
||||||
mod passthrough_from_upload_texture_node;
|
mod passthrough_from_upload_texture_node;
|
||||||
mod renames;
|
mod renames;
|
||||||
|
mod stroke_v1;
|
||||||
mod vary_colors_from_assign_colors;
|
mod vary_colors_from_assign_colors;
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
use migration_core::{Inputs, literal, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
PaintMapping(PaintMapping),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum PaintMapping {
|
||||||
|
Plane,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 'Stroke' gained Paint Mapping after its dash offset, set to Plane to keep placing the paint in the canvas as it was.
|
||||||
|
#[migration("graphene_core::vector::StrokeNode"@1 => @2)]
|
||||||
|
pub fn stroke_v1(inputs: &mut Inputs) {
|
||||||
|
inputs.push(literal(Tagged::PaintMapping(PaintMapping::Plane)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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(9, |random, _slot| literal(random.below(10) as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&StrokeV1, &contract());
|
||||||
|
check_undo(&StrokeV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_the_inputs_and_appends_the_plane_paint_mapping() {
|
||||||
|
let inputs: Vec<_> = (0..9).map(|index| literal(index as f64)).collect();
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&StrokeV1);
|
||||||
|
let stroke = fixture.add(decl!("graphene_core::vector::StrokeNode"@1), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&StrokeV1).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(fixture.declaration_of(&migrated, stroke), Some(decl!("graphene_core::vector::StrokeNode"@2)));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, stroke), [inputs, vec![literal(Tagged::PaintMapping(PaintMapping::Plane))]].concat());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, PaintMapping, 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::{
|
||||||
@@ -419,6 +419,7 @@ macro_rules! inspectable_types {
|
|||||||
List<StrokeJoin>,
|
List<StrokeJoin>,
|
||||||
List<StrokeAlign>,
|
List<StrokeAlign>,
|
||||||
List<StrokeCap>,
|
List<StrokeCap>,
|
||||||
|
List<PaintMapping>,
|
||||||
List<WeldMethod>,
|
List<WeldMethod>,
|
||||||
List<UnweldMethod>,
|
List<UnweldMethod>,
|
||||||
List<ExtrudeJoiningAlgorithm>,
|
List<ExtrudeJoiningAlgorithm>,
|
||||||
@@ -480,6 +481,7 @@ macro_rules! inspectable_types {
|
|||||||
Item<StrokeJoin>,
|
Item<StrokeJoin>,
|
||||||
Item<StrokeAlign>,
|
Item<StrokeAlign>,
|
||||||
Item<StrokeCap>,
|
Item<StrokeCap>,
|
||||||
|
Item<PaintMapping>,
|
||||||
Item<WeldMethod>,
|
Item<WeldMethod>,
|
||||||
Item<UnweldMethod>,
|
Item<UnweldMethod>,
|
||||||
Item<ExtrudeJoiningAlgorithm>,
|
Item<ExtrudeJoiningAlgorithm>,
|
||||||
@@ -1295,6 +1297,7 @@ impl_table_item_layout_for_choice_enum!(
|
|||||||
StrokeJoin,
|
StrokeJoin,
|
||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
|
PaintMapping,
|
||||||
WeldMethod,
|
WeldMethod,
|
||||||
UnweldMethod,
|
UnweldMethod,
|
||||||
ExtrudeJoiningAlgorithm,
|
ExtrudeJoiningAlgorithm,
|
||||||
@@ -1491,6 +1494,7 @@ macro_rules! known_item_types {
|
|||||||
StrokeJoin,
|
StrokeJoin,
|
||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
|
PaintMapping,
|
||||||
WeldMethod,
|
WeldMethod,
|
||||||
UnweldMethod,
|
UnweldMethod,
|
||||||
ExtrudeJoiningAlgorithm,
|
ExtrudeJoiningAlgorithm,
|
||||||
|
|||||||
+2
-1
@@ -14,7 +14,7 @@ use graph_craft::document::{NodeId, NodeInput};
|
|||||||
use graph_craft::list;
|
use graph_craft::list;
|
||||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||||
use graphene_std::text::{Font, TypesettingConfig};
|
use graphene_std::text::{Font, TypesettingConfig};
|
||||||
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, PaintMapping, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use graphene_std::{Artboard, Color};
|
use graphene_std::{Artboard, Color};
|
||||||
|
|
||||||
#[derive(ExtractField)]
|
#[derive(ExtractField)]
|
||||||
@@ -991,6 +991,7 @@ fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsCont
|
|||||||
},
|
},
|
||||||
join_miter_limit: stroke.miterlimit().get() as f64,
|
join_miter_limit: stroke.miterlimit().get() as f64,
|
||||||
align: StrokeAlign::Center,
|
align: StrokeAlign::Center,
|
||||||
|
paint_mapping: PaintMapping::Plane,
|
||||||
transform,
|
transform,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -904,6 +904,8 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
|
||||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
|
||||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
|
||||||
|
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintMappingInput);
|
||||||
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintMapping(stroke.paint_mapping), false), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
|
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
|
||||||
|
|||||||
@@ -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, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, PaintMapping,
|
||||||
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};
|
||||||
@@ -459,6 +459,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).inspector_row(),
|
||||||
|
Some(x) if id_is::<PaintMapping>(x) => enum_choice::<PaintMapping>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).inspector_row(),
|
||||||
@@ -3859,6 +3860,9 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
|
|||||||
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
|
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
|
||||||
let number_input = disabled_number_input;
|
let number_input = disabled_number_input;
|
||||||
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
|
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
|
||||||
|
let paint_mapping = enum_choice::<PaintMapping>()
|
||||||
|
.for_socket(ParameterWidgetsInfo::new(node_id, PaintMappingInput, true, context))
|
||||||
|
.inspector_row();
|
||||||
|
|
||||||
vec![
|
vec![
|
||||||
color,
|
color,
|
||||||
@@ -3869,6 +3873,7 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
|
|||||||
LayoutGroup::row(miter_limit),
|
LayoutGroup::row(miter_limit),
|
||||||
LayoutGroup::row(dash_lengths),
|
LayoutGroup::row(dash_lengths),
|
||||||
LayoutGroup::row(dash_offset),
|
LayoutGroup::row(dash_offset),
|
||||||
|
paint_mapping,
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2861,9 +2861,14 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
inputs_count = 9;
|
inputs_count = 9;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The modern Stroke also has 10 inputs, so the Paint Order era is told apart by its paint order at 7 or its dash offset at 9,
|
||||||
|
// either of which may be wired, where the modern shape holds its dash pattern and paint mapping
|
||||||
|
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
|
||||||
|
let is_paint_order_stroke = inputs_count == 10 && (matches!(value_at(7), Some(TaggedValue::PaintOrder(_))) || matches!(value_at(9), Some(TaggedValue::Number(_))));
|
||||||
|
|
||||||
// The Stroke node's "Paint Order" input was retired in favor of the relative order of the Fill and Stroke
|
// The Stroke node's "Paint Order" input was retired in favor of the relative order of the Fill and Stroke
|
||||||
// nodes in the chain, so the stored value becomes a topology rewrite that reorders the two nodes.
|
// nodes in the chain, so the stored value becomes a topology rewrite that reorders the two nodes.
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 10 {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && is_paint_order_stroke {
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
|
||||||
@@ -4798,6 +4803,7 @@ mod tests {
|
|||||||
.find(|node_id| document.network_interface.reference(node_id, &[]).as_ref() == Some(&stroke_reference))
|
.find(|node_id| document.network_interface.reference(node_id, &[]).as_ref() == Some(&stroke_reference))
|
||||||
.expect("a fresh shape should have a Stroke node in its chain");
|
.expect("a fresh shape should have a Stroke node in its chain");
|
||||||
let mut inputs = document.network_interface.document_node(&stroke_node_id, &[]).unwrap().inputs.clone();
|
let mut inputs = document.network_interface.document_node(&stroke_node_id, &[]).unwrap().inputs.clone();
|
||||||
|
inputs.truncate(graphene_std::vector::stroke::PaintMappingInput::INDEX);
|
||||||
inputs.insert(7, NodeInput::value(TaggedValue::PaintOrder(PaintOrder::StrokeBelow), false));
|
inputs.insert(7, NodeInput::value(TaggedValue::PaintOrder(PaintOrder::StrokeBelow), false));
|
||||||
let mut legacy_stroke = NodeTemplate { inputs, ..Default::default() };
|
let mut legacy_stroke = NodeTemplate { inputs, ..Default::default() };
|
||||||
legacy_stroke.normalize_input_metadata();
|
legacy_stroke.normalize_input_metadata();
|
||||||
@@ -4819,6 +4825,50 @@ mod tests {
|
|||||||
assert_eq!(chain_layout(&opened, layer), expected, "the migration should leave the layer's chain intact");
|
assert_eq!(chain_layout(&opened, layer), expected, "the migration should leave the layer's chain intact");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The modern Stroke also has 10 inputs, which must not be mistaken for the retired "Paint Order" layout
|
||||||
|
#[tokio::test]
|
||||||
|
async fn opening_a_ten_input_stroke_keeps_its_inputs_and_paint_order() {
|
||||||
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
use crate::messages::tool::common_functionality::graph_modification_utils::get_stroke_paint_order;
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||||
|
use graphene_std::vector::stroke::{DashPatternInput, PaintMappingInput};
|
||||||
|
use graphene_std::vector::style::PaintMapping;
|
||||||
|
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
|
||||||
|
let document = editor.active_document_mut();
|
||||||
|
let layer = document.metadata().all_layers().next().unwrap().to_node();
|
||||||
|
|
||||||
|
let stroke_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
|
||||||
|
let stroke_node_id = document
|
||||||
|
.network_interface
|
||||||
|
.layer_chain_nodes(layer, &[])
|
||||||
|
.into_iter()
|
||||||
|
.find(|node_id| document.network_interface.reference(node_id, &[]).as_ref() == Some(&stroke_reference))
|
||||||
|
.expect("a fresh shape should have a Stroke node in its chain");
|
||||||
|
|
||||||
|
// A dashed stroke mapped along its path, whose dash pattern and paint mapping sit where the retired layout kept its paint order and dash offset
|
||||||
|
let dashed_along_path = [
|
||||||
|
(DashPatternInput::INDEX, TaggedValue::DashPattern(vec![4., 2.])),
|
||||||
|
(PaintMappingInput::INDEX, TaggedValue::PaintMapping(PaintMapping::Path)),
|
||||||
|
];
|
||||||
|
for (index, value) in dashed_along_path {
|
||||||
|
document
|
||||||
|
.network_interface
|
||||||
|
.set_input(&InputConnector::node_at_index(stroke_node_id, index), NodeInput::value(value, false), &[]);
|
||||||
|
}
|
||||||
|
let inputs = document.network_interface.document_node(&stroke_node_id, &[]).unwrap().inputs.clone();
|
||||||
|
assert_eq!(inputs.len(), 10, "the modern Stroke should have 10 inputs");
|
||||||
|
|
||||||
|
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||||
|
|
||||||
|
let reopened = opened.network_interface.document_node(&stroke_node_id, &[]).expect("the Stroke node should still exist");
|
||||||
|
assert_eq!(reopened.inputs, inputs, "the Stroke node should keep its inputs");
|
||||||
|
assert_eq!(get_stroke_paint_order(LayerNodeIdentifier::new_unchecked(layer), &opened.network_interface), PaintOrder::StrokeAbove);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn opening_a_canvas_rasterize_network_upgrades_it_to_the_vello_node() {
|
async fn opening_a_canvas_rasterize_network_upgrades_it_to_the_vello_node() {
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkTemplate;
|
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkTemplate;
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
|
|||||||
use crate::messages::tool::utility_types::DocumentToolData;
|
use crate::messages::tool::utility_types::DocumentToolData;
|
||||||
use graphene_std::Color;
|
use graphene_std::Color;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphene_std::vector::style::{FillChoice, PaintMapping, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
|
|
||||||
/// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar.
|
/// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar.
|
||||||
pub struct ToolColorOptions {
|
pub struct ToolColorOptions {
|
||||||
@@ -242,6 +242,7 @@ impl DrawingToolState {
|
|||||||
join_miter_limit: self.miter_limit.unwrap_or(defaults.miter_limit),
|
join_miter_limit: self.miter_limit.unwrap_or(defaults.miter_limit),
|
||||||
dash_lengths: self.dash_lengths.clone().unwrap_or_else(|| defaults.dash_lengths.clone()),
|
dash_lengths: self.dash_lengths.clone().unwrap_or_else(|| defaults.dash_lengths.clone()),
|
||||||
dash_offset: self.dash_offset.unwrap_or(defaults.dash_offset),
|
dash_offset: self.dash_offset.unwrap_or(defaults.dash_offset),
|
||||||
|
paint_mapping: PaintMapping::default(),
|
||||||
transform: glam::DAffine2::IDENTITY,
|
transform: glam::DAffine2::IDENTITY,
|
||||||
};
|
};
|
||||||
responses.add(GraphOperationMessage::StrokeSet { layer, color: Some(color), stroke });
|
responses.add(GraphOperationMessage::StrokeSet { layer, color: Some(color), stroke });
|
||||||
|
|||||||
@@ -574,6 +574,7 @@ tagged_value! {
|
|||||||
#[serde(alias = "LineJoin")]
|
#[serde(alias = "LineJoin")]
|
||||||
StrokeJoin(vector::style::StrokeJoin),
|
StrokeJoin(vector::style::StrokeJoin),
|
||||||
StrokeAlign(vector::style::StrokeAlign),
|
StrokeAlign(vector::style::StrokeAlign),
|
||||||
|
PaintMapping(vector::style::PaintMapping),
|
||||||
#[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),
|
||||||
|
|||||||
@@ -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, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, PaintMapping, 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};
|
||||||
@@ -268,6 +270,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
StrokeJoin,
|
StrokeJoin,
|
||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
|
PaintMapping,
|
||||||
GradientForm,
|
GradientForm,
|
||||||
GradientModel,
|
GradientModel,
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
|
|||||||
@@ -107,6 +107,8 @@ pub const ATTR_JOIN: &str = "join";
|
|||||||
pub const ATTR_JOIN_MITER_LIMIT: &str = "join_miter_limit";
|
pub const ATTR_JOIN_MITER_LIMIT: &str = "join_miter_limit";
|
||||||
/// Stroke coverage's `StrokeAlign` (implicit default `Center`), on the `Item<Cover>` inside a `Coverage`.
|
/// Stroke coverage's `StrokeAlign` (implicit default `Center`), on the `Item<Cover>` inside a `Coverage`.
|
||||||
pub const ATTR_ALIGN: &str = "align";
|
pub const ATTR_ALIGN: &str = "align";
|
||||||
|
/// Stroke coverage's `PaintMapping` (implicit default `Plane`), on the `Item<Cover>` inside a `Coverage`.
|
||||||
|
pub const ATTR_PAINT_MAPPING: &str = "paint_mapping";
|
||||||
/// Brush stroke item's `Color` its strokes are painted with.
|
/// Brush stroke item's `Color` its strokes are painted with.
|
||||||
pub const ATTR_COLOR: &str = "color";
|
pub const ATTR_COLOR: &str = "color";
|
||||||
/// Brush stroke item's tip diameter in document-space units (`f64`).
|
/// Brush stroke item's tip diameter in document-space units (`f64`).
|
||||||
|
|||||||
@@ -5,7 +5,9 @@
|
|||||||
use crate::effects::{rebased_stamped_transform, stamped_transform};
|
use crate::effects::{rebased_stamped_transform, stamped_transform};
|
||||||
use crate::graphic::Graphic;
|
use crate::graphic::Graphic;
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use core_types::list::{ATTR_ALIGN, ATTR_APPEARANCE, ATTR_CAP, ATTR_DASH_OFFSET, ATTR_DASH_PATTERN, ATTR_JOIN, ATTR_JOIN_MITER_LIMIT, ATTR_PAINT, ATTR_TRANSFORM, ATTR_WEIGHT, Item, List};
|
use core_types::list::{
|
||||||
|
ATTR_ALIGN, ATTR_APPEARANCE, ATTR_CAP, ATTR_DASH_OFFSET, ATTR_DASH_PATTERN, ATTR_JOIN, ATTR_JOIN_MITER_LIMIT, ATTR_PAINT, ATTR_PAINT_MAPPING, ATTR_TRANSFORM, ATTR_WEIGHT, Item, List,
|
||||||
|
};
|
||||||
use glam::DAffine2;
|
use glam::DAffine2;
|
||||||
use vector_types::vector::style::{DashPattern, Stroke};
|
use vector_types::vector::style::{DashPattern, Stroke};
|
||||||
|
|
||||||
@@ -82,6 +84,9 @@ impl Coverage {
|
|||||||
if stroke.align != defaults.align {
|
if stroke.align != defaults.align {
|
||||||
item.set_attribute(ATTR_ALIGN, stroke.align);
|
item.set_attribute(ATTR_ALIGN, stroke.align);
|
||||||
}
|
}
|
||||||
|
if stroke.paint_mapping != defaults.paint_mapping {
|
||||||
|
item.set_attribute(ATTR_PAINT_MAPPING, stroke.paint_mapping);
|
||||||
|
}
|
||||||
|
|
||||||
Self(item)
|
Self(item)
|
||||||
}
|
}
|
||||||
@@ -105,6 +110,7 @@ impl Coverage {
|
|||||||
ATTR_JOIN => stroke.join = value.downcast_ref().copied().unwrap_or(stroke.join),
|
ATTR_JOIN => stroke.join = value.downcast_ref().copied().unwrap_or(stroke.join),
|
||||||
ATTR_JOIN_MITER_LIMIT => stroke.join_miter_limit = value.downcast_ref().copied().unwrap_or(stroke.join_miter_limit),
|
ATTR_JOIN_MITER_LIMIT => stroke.join_miter_limit = value.downcast_ref().copied().unwrap_or(stroke.join_miter_limit),
|
||||||
ATTR_ALIGN => stroke.align = value.downcast_ref().copied().unwrap_or(stroke.align),
|
ATTR_ALIGN => stroke.align = value.downcast_ref().copied().unwrap_or(stroke.align),
|
||||||
|
ATTR_PAINT_MAPPING => stroke.paint_mapping = value.downcast_ref().copied().unwrap_or(stroke.paint_mapping),
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -305,7 +311,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use vector_types::vector::style::{StrokeAlign, StrokeCap, StrokeJoin};
|
use vector_types::vector::style::{PaintMapping, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
|
|
||||||
fn solid_paint(color: Color) -> Graphic {
|
fn solid_paint(color: Color) -> Graphic {
|
||||||
Graphic::ColorList(List::new_from_element(color))
|
Graphic::ColorList(List::new_from_element(color))
|
||||||
@@ -327,6 +333,7 @@ mod tests {
|
|||||||
join: StrokeJoin::Bevel,
|
join: StrokeJoin::Bevel,
|
||||||
join_miter_limit: 7.,
|
join_miter_limit: 7.,
|
||||||
align: StrokeAlign::Inside,
|
align: StrokeAlign::Inside,
|
||||||
|
paint_mapping: PaintMapping::Path,
|
||||||
transform: DAffine2::IDENTITY,
|
transform: DAffine2::IDENTITY,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -341,6 +348,7 @@ mod tests {
|
|||||||
assert_eq!(extracted.join, StrokeJoin::Bevel);
|
assert_eq!(extracted.join, StrokeJoin::Bevel);
|
||||||
assert_eq!(extracted.join_miter_limit, 7.);
|
assert_eq!(extracted.join_miter_limit, 7.);
|
||||||
assert_eq!(extracted.align, StrokeAlign::Inside);
|
assert_eq!(extracted.align, StrokeAlign::Inside);
|
||||||
|
assert_eq!(extracted.paint_mapping, PaintMapping::Path);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -404,6 +412,14 @@ mod tests {
|
|||||||
let keys: Vec<_> = coverage.0.attributes().keys().collect();
|
let keys: Vec<_> = coverage.0.attributes().keys().collect();
|
||||||
assert_eq!(keys, vec![ATTR_WEIGHT], "only the non-default weight should be stamped");
|
assert_eq!(keys, vec![ATTR_WEIGHT], "only the non-default weight should be stamped");
|
||||||
assert_eq!(coverage.stroke_params().weight, 2.);
|
assert_eq!(coverage.stroke_params().weight, 2.);
|
||||||
|
|
||||||
|
let coverage = Coverage::new_stroke(&Stroke {
|
||||||
|
paint_mapping: PaintMapping::Path,
|
||||||
|
..Stroke::default()
|
||||||
|
});
|
||||||
|
let keys: Vec<_> = coverage.0.attributes().keys().collect();
|
||||||
|
assert_eq!(keys, vec![ATTR_PAINT_MAPPING], "only the non-default paint mapping should be stamped");
|
||||||
|
assert_eq!(coverage.stroke_params().paint_mapping, PaintMapping::Path);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ mod geometry;
|
|||||||
mod geometry_cache;
|
mod geometry_cache;
|
||||||
pub mod misc;
|
pub mod misc;
|
||||||
mod path;
|
mod path;
|
||||||
|
mod path_chart;
|
||||||
pub mod reference_point;
|
pub mod reference_point;
|
||||||
pub mod style;
|
pub mod style;
|
||||||
mod vector_attributes;
|
mod vector_attributes;
|
||||||
@@ -21,6 +22,7 @@ pub use flatten::{WorkingVector, vector_from_legacy_parts};
|
|||||||
pub use geometry::VectorGeometry;
|
pub use geometry::VectorGeometry;
|
||||||
pub use geometry_cache::{GeometryCache, PlacedContours, SetVectorPaths, set_paths_at};
|
pub use geometry_cache::{GeometryCache, PlacedContours, SetVectorPaths, set_paths_at};
|
||||||
pub use path::*;
|
pub use path::*;
|
||||||
|
pub use path_chart::PathChart;
|
||||||
pub use reference_point::*;
|
pub use reference_point::*;
|
||||||
pub use vector_attributes::*;
|
pub use vector_attributes::*;
|
||||||
pub use vector_modification::*;
|
pub use vector_modification::*;
|
||||||
|
|||||||
@@ -0,0 +1,677 @@
|
|||||||
|
//! The chart a paint mapped along a stroke's paths reads its position from: arc length along each contour, and offset across the stroke's width.
|
||||||
|
|
||||||
|
use super::misc::{dvec2_to_point, point_to_dvec2};
|
||||||
|
use super::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
|
use glam::DVec2;
|
||||||
|
use kurbo::{BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, QuadBez, Shape};
|
||||||
|
use std::ops::Range;
|
||||||
|
|
||||||
|
/// Accuracy of each path segment's arc length, the same kurbo measures dashes with, so the chart's dashes line up with the drawn ones.
|
||||||
|
const ARC_LENGTH_ACCURACY: f64 = 1e-6;
|
||||||
|
|
||||||
|
/// Maps points around a stroke to `(u, v)` coordinates. `u` runs from 0 to 1 along the arc length of each contour from its start point,
|
||||||
|
/// extending past open ends through their caps. `v` runs from 0 on the stroke's left edge to 1 on its right edge, relative to the contour's direction.
|
||||||
|
///
|
||||||
|
/// The path is flattened into straight pieces, and each piece is charted on its own, as a GPU pass reading the same pieces would chart it.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct PathChart {
|
||||||
|
pieces: Vec<ChartPiece>,
|
||||||
|
contours: Vec<ChartContour>,
|
||||||
|
/// The stroke's weight, across which `v` spans 0 to 1.
|
||||||
|
width: f64,
|
||||||
|
/// How far a cap reaches along the path past the end of an open contour or a dash.
|
||||||
|
cap_reach: f64,
|
||||||
|
/// -1 where the stroke space mirrors the path's own space, so the right side stays the path's own right side.
|
||||||
|
side_sign: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One straight piece of a flattened contour.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
struct ChartPiece {
|
||||||
|
start: DVec2,
|
||||||
|
end: DVec2,
|
||||||
|
/// Arc length along the contour where the piece starts.
|
||||||
|
arc_start: f64,
|
||||||
|
/// Arc length the piece spans, scaled so a curve's pieces add up to the curve's exact arc length.
|
||||||
|
arc_span: f64,
|
||||||
|
contour: usize,
|
||||||
|
/// Whether the piece begins an open contour, so the chart extends backward past its start through the cap.
|
||||||
|
extends_backward: bool,
|
||||||
|
/// Whether the piece ends an open contour, so the chart extends forward past its end through the cap.
|
||||||
|
extends_forward: bool,
|
||||||
|
/// The corner where the piece meets the next piece of its contour.
|
||||||
|
join: Option<ChartJoin>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
struct ChartJoin {
|
||||||
|
/// Unit direction of the next piece.
|
||||||
|
next_direction: DVec2,
|
||||||
|
/// Whether the corner's outer wedge is measured by distance from the corner, rather than from the two pieces' lines like a miter.
|
||||||
|
round: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct ChartContour {
|
||||||
|
start: DVec2,
|
||||||
|
length: f64,
|
||||||
|
closed: bool,
|
||||||
|
/// Offset toward the right side where `v` is 0.
|
||||||
|
band_start: f64,
|
||||||
|
pieces: Range<usize>,
|
||||||
|
/// The sorted arc length intervals the stroke draws, or `None` when it draws all of a closed contour.
|
||||||
|
drawn: Option<Vec<(f64, f64)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A contour flattened into straight pieces, before the chart's rules are attached to them.
|
||||||
|
struct FlatContour {
|
||||||
|
start: DVec2,
|
||||||
|
closed: bool,
|
||||||
|
pieces: Vec<FlatPiece>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FlatPiece {
|
||||||
|
start: DVec2,
|
||||||
|
end: DVec2,
|
||||||
|
arc_span: f64,
|
||||||
|
/// Whether the piece ends one of the path's segments, rather than ending inside a flattened curve.
|
||||||
|
ends_segment: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PathChart {
|
||||||
|
/// Charts `path`, which lies in the stroke's space as placed by `stroke.transform`, flattening its curves to within `tolerance`.
|
||||||
|
pub fn new(path: &BezPath, stroke: &Stroke, tolerance: f64) -> Self {
|
||||||
|
let side_sign = if stroke.transform.matrix2.determinant() < 0. { -1. } else { 1. };
|
||||||
|
let flat_contours = flatten_contours(path, tolerance.max(1e-9));
|
||||||
|
|
||||||
|
// Like the renderer, alignment only applies when every contour is closed, and then draws the stroke at twice its weight with one side masked away
|
||||||
|
let aligned = stroke.align != StrokeAlign::Center && flat_contours.iter().all(|contour| contour.closed);
|
||||||
|
let width = stroke.weight;
|
||||||
|
let drawn_half_width = if aligned { width } else { width / 2. };
|
||||||
|
let cap_reach = if stroke.cap == StrokeCap::Butt { 0. } else { drawn_half_width };
|
||||||
|
let dash_lengths: Vec<f64> = stroke.dash_lengths.iter().map(|length| length.max(0.)).collect();
|
||||||
|
|
||||||
|
let mut chart = Self {
|
||||||
|
pieces: Vec::new(),
|
||||||
|
contours: Vec::with_capacity(flat_contours.len()),
|
||||||
|
width,
|
||||||
|
cap_reach,
|
||||||
|
side_sign,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (contour_index, flat_contour) in flat_contours.iter().enumerate() {
|
||||||
|
let first_piece = chart.pieces.len();
|
||||||
|
let piece_count = flat_contour.pieces.len();
|
||||||
|
|
||||||
|
// Lay the pieces end to end along the contour's arc length
|
||||||
|
let mut arc_start = 0.;
|
||||||
|
for (index, piece) in flat_contour.pieces.iter().enumerate() {
|
||||||
|
let is_last = index + 1 == piece_count;
|
||||||
|
let next = if is_last && flat_contour.closed {
|
||||||
|
flat_contour.pieces.first()
|
||||||
|
} else {
|
||||||
|
flat_contour.pieces.get(index + 1)
|
||||||
|
};
|
||||||
|
let join = next.map(|next| ChartJoin {
|
||||||
|
next_direction: (next.end - next.start).normalize(),
|
||||||
|
round: !piece.ends_segment || stroke.join == StrokeJoin::Round,
|
||||||
|
});
|
||||||
|
|
||||||
|
chart.pieces.push(ChartPiece {
|
||||||
|
start: piece.start,
|
||||||
|
end: piece.end,
|
||||||
|
arc_start,
|
||||||
|
arc_span: piece.arc_span,
|
||||||
|
contour: contour_index,
|
||||||
|
extends_backward: index == 0 && !flat_contour.closed,
|
||||||
|
extends_forward: is_last && !flat_contour.closed,
|
||||||
|
join,
|
||||||
|
});
|
||||||
|
arc_start += piece.arc_span;
|
||||||
|
}
|
||||||
|
let length = arc_start;
|
||||||
|
|
||||||
|
// The band covers the stroke's width about the contour, or for an aligned stroke, the side the fill keeps
|
||||||
|
let band_start = match stroke.align {
|
||||||
|
_ if !aligned => -width / 2.,
|
||||||
|
StrokeAlign::Inside if right_side_is_filled(path, flat_contour, side_sign) => 0.,
|
||||||
|
StrokeAlign::Outside if !right_side_is_filled(path, flat_contour, side_sign) => 0.,
|
||||||
|
_ => -width,
|
||||||
|
};
|
||||||
|
|
||||||
|
let drawn = match dash_intervals(&dash_lengths, stroke.dash_offset, length) {
|
||||||
|
Some(intervals) => Some(intervals),
|
||||||
|
None if flat_contour.closed => None,
|
||||||
|
None => Some(vec![(0., length)]),
|
||||||
|
};
|
||||||
|
|
||||||
|
chart.contours.push(ChartContour {
|
||||||
|
start: flat_contour.start,
|
||||||
|
length,
|
||||||
|
closed: flat_contour.closed,
|
||||||
|
band_start,
|
||||||
|
pieces: first_piece..chart.pieces.len(),
|
||||||
|
drawn,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
chart
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `(u, v)` coordinates of `point`, given in stroke space, from the latest piece in path order that draws over it, or else from the nearest piece,
|
||||||
|
/// for points such as antialiased fringes that no piece draws over. `None` when there is no stroke to chart. O(pieces).
|
||||||
|
pub fn chart_at(&self, point: DVec2) -> Option<(f64, f64)> {
|
||||||
|
if self.width <= 0. || !self.width.is_finite() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut charted = None;
|
||||||
|
for piece in &self.pieces {
|
||||||
|
let contour = &self.contours[piece.contour];
|
||||||
|
if let Some(coordinates) = self.body_coordinates(piece, contour, point) {
|
||||||
|
charted = Some(coordinates);
|
||||||
|
}
|
||||||
|
if let Some(coordinates) = self.join_coordinates(piece, contour, point) {
|
||||||
|
charted = Some(coordinates);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
charted.or_else(|| self.nearest_coordinates(point))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The point in stroke space at `u` (clamped to 0 to 1) along the contour at the given index.
|
||||||
|
pub fn point_at(&self, contour: usize, u: f64) -> Option<DVec2> {
|
||||||
|
let contour = self.contours.get(contour)?;
|
||||||
|
let pieces = &self.pieces[contour.pieces.clone()];
|
||||||
|
if pieces.is_empty() {
|
||||||
|
return Some(contour.start);
|
||||||
|
}
|
||||||
|
|
||||||
|
let arc = u.clamp(0., 1.) * contour.length;
|
||||||
|
let index = pieces.partition_point(|piece| piece.arc_start + piece.arc_span < arc).min(pieces.len() - 1);
|
||||||
|
let piece = &pieces[index];
|
||||||
|
let along = ((arc - piece.arc_start) / piece.arc_span).clamp(0., 1.);
|
||||||
|
Some(piece.start.lerp(piece.end, along))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body of the stroke around the piece, extended past an open contour's ends through its caps.
|
||||||
|
fn body_coordinates(&self, piece: &ChartPiece, contour: &ChartContour, point: DVec2) -> Option<(f64, f64)> {
|
||||||
|
let chord = piece.end - piece.start;
|
||||||
|
let offset = point - piece.start;
|
||||||
|
let along = offset.dot(chord) / chord.length_squared();
|
||||||
|
if (along < 0. && !piece.extends_backward) || (along > 1. && !piece.extends_forward) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let across = offset.dot(self.right_normal(chord.normalize()));
|
||||||
|
let arc = piece.arc_start + along * piece.arc_span;
|
||||||
|
if !self.in_band(contour, across) || !contour.draws(arc, self.cap_reach) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(self.coordinates(contour, arc, across))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wedge on the outer side of the corner at the piece's end, between where its body ends and the next piece's body begins.
|
||||||
|
/// The whole wedge takes the corner's arc length, so colors fan around it.
|
||||||
|
fn join_coordinates(&self, piece: &ChartPiece, contour: &ChartContour, point: DVec2) -> Option<(f64, f64)> {
|
||||||
|
let join = piece.join?;
|
||||||
|
let incoming = (piece.end - piece.start).normalize();
|
||||||
|
let outgoing = join.next_direction;
|
||||||
|
|
||||||
|
let offset = point - piece.end;
|
||||||
|
if offset.dot(incoming) <= 0. || offset.dot(outgoing) >= 0. {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The outer side is opposite the turn, except at a full reversal, where both sides are outer
|
||||||
|
let across_incoming = offset.dot(self.right_normal(incoming));
|
||||||
|
let across_outgoing = offset.dot(self.right_normal(outgoing));
|
||||||
|
let turn = outgoing.dot(self.right_normal(incoming));
|
||||||
|
let outer_side = if turn != 0. {
|
||||||
|
-turn.signum()
|
||||||
|
} else if across_incoming < 0. {
|
||||||
|
-1.
|
||||||
|
} else {
|
||||||
|
1.
|
||||||
|
};
|
||||||
|
|
||||||
|
// A miter measures the larger distance from the two pieces' lines, which stays within the band all the way to its tip
|
||||||
|
let distance = if join.round {
|
||||||
|
offset.length()
|
||||||
|
} else {
|
||||||
|
(outer_side * across_incoming).max(outer_side * across_outgoing)
|
||||||
|
};
|
||||||
|
let across = outer_side * distance;
|
||||||
|
|
||||||
|
let arc = piece.arc_start + piece.arc_span;
|
||||||
|
if !self.in_band(contour, across) || !contour.draws(arc, self.cap_reach) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(self.coordinates(contour, arc, across))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The coordinates from the nearest point on any piece, measured across that piece's line. O(pieces).
|
||||||
|
fn nearest_coordinates(&self, point: DVec2) -> Option<(f64, f64)> {
|
||||||
|
let mut nearest: Option<(f64, &ChartPiece, f64)> = None;
|
||||||
|
for piece in &self.pieces {
|
||||||
|
let chord = piece.end - piece.start;
|
||||||
|
let along = ((point - piece.start).dot(chord) / chord.length_squared()).clamp(0., 1.);
|
||||||
|
let distance_squared = point.distance_squared(piece.start + chord * along);
|
||||||
|
|
||||||
|
// Ties go to the later piece, as overlaps do
|
||||||
|
if nearest.is_none_or(|(nearest_distance_squared, ..)| distance_squared <= nearest_distance_squared) {
|
||||||
|
nearest = Some((distance_squared, piece, along));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let (_, piece, along) = nearest?;
|
||||||
|
let contour = &self.contours[piece.contour];
|
||||||
|
let across = (point - piece.start).dot(self.right_normal((piece.end - piece.start).normalize()));
|
||||||
|
Some(self.coordinates(contour, piece.arc_start + along * piece.arc_span, across))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn coordinates(&self, contour: &ChartContour, arc: f64, across: f64) -> (f64, f64) {
|
||||||
|
(arc / contour.length, (across - contour.band_start) / self.width)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn in_band(&self, contour: &ChartContour, across: f64) -> bool {
|
||||||
|
(contour.band_start..=contour.band_start + self.width).contains(&across)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The unit normal toward the right side of a piece running in `direction`.
|
||||||
|
fn right_normal(&self, direction: DVec2) -> DVec2 {
|
||||||
|
self.side_sign * direction.perp()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ChartContour {
|
||||||
|
/// Whether the stroke draws at `arc` along the contour, counting caps that reach `cap_reach` past the ends of what it draws.
|
||||||
|
fn draws(&self, arc: f64, cap_reach: f64) -> bool {
|
||||||
|
let Some(intervals) = &self.drawn else { return true };
|
||||||
|
|
||||||
|
// The last interval starting within reach reaches the furthest, since the intervals are sorted and disjoint
|
||||||
|
let draws_at = |arc: f64| {
|
||||||
|
let count = intervals.partition_point(|&(start, _)| start <= arc + cap_reach);
|
||||||
|
count > 0 && intervals[count - 1].1 + cap_reach >= arc
|
||||||
|
};
|
||||||
|
|
||||||
|
// A closed contour's dashes continue across its start point
|
||||||
|
draws_at(arc) || (self.closed && (draws_at(arc - self.length) || draws_at(arc + self.length)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits the path into its contours, each flattened into straight pieces whose arc lengths add up to each segment's exact arc length.
|
||||||
|
fn flatten_contours(path: &BezPath, tolerance: f64) -> Vec<FlatContour> {
|
||||||
|
let mut contours: Vec<FlatContour> = Vec::new();
|
||||||
|
let mut last_point = DVec2::ZERO;
|
||||||
|
|
||||||
|
for element in path.elements() {
|
||||||
|
let end = match *element {
|
||||||
|
PathEl::MoveTo(point) => {
|
||||||
|
last_point = point_to_dvec2(point);
|
||||||
|
contours.push(FlatContour {
|
||||||
|
start: last_point,
|
||||||
|
closed: false,
|
||||||
|
pieces: Vec::new(),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
PathEl::ClosePath => {
|
||||||
|
let Some(contour) = contours.last_mut() else { continue };
|
||||||
|
if !contour.closed {
|
||||||
|
push_segment(contour, PathSeg::Line(Line::new(dvec2_to_point(last_point), dvec2_to_point(contour.start))), tolerance);
|
||||||
|
contour.closed = true;
|
||||||
|
last_point = contour.start;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
PathEl::LineTo(p1) => p1,
|
||||||
|
PathEl::QuadTo(_, p2) => p2,
|
||||||
|
PathEl::CurveTo(_, _, p3) => p3,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Drawing after a contour closes, without moving first, begins another contour where the closed one started
|
||||||
|
if contours.last().is_none_or(|contour| contour.closed) {
|
||||||
|
contours.push(FlatContour {
|
||||||
|
start: last_point,
|
||||||
|
closed: false,
|
||||||
|
pieces: Vec::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let Some(contour) = contours.last_mut() else { continue };
|
||||||
|
|
||||||
|
let p0 = dvec2_to_point(last_point);
|
||||||
|
let segment = match *element {
|
||||||
|
PathEl::QuadTo(p1, p2) => PathSeg::Quad(QuadBez::new(p0, p1, p2)),
|
||||||
|
PathEl::CurveTo(p1, p2, p3) => PathSeg::Cubic(CubicBez::new(p0, p1, p2, p3)),
|
||||||
|
_ => PathSeg::Line(Line::new(p0, end)),
|
||||||
|
};
|
||||||
|
push_segment(contour, segment, tolerance);
|
||||||
|
last_point = point_to_dvec2(end);
|
||||||
|
}
|
||||||
|
|
||||||
|
contours
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends a path segment's flattened pieces, scaling their chord lengths to add up to its arc length so `u` reaches exactly 1 at the contour's end.
|
||||||
|
/// Segments of no length are skipped, as the stroker skips them.
|
||||||
|
fn push_segment(contour: &mut FlatContour, segment: PathSeg, tolerance: f64) {
|
||||||
|
let arc_length = segment.arclen(ARC_LENGTH_ACCURACY);
|
||||||
|
if arc_length <= 0. || !arc_length.is_finite() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut points = Vec::new();
|
||||||
|
kurbo::flatten([PathEl::MoveTo(segment.start()), segment.as_path_el()], tolerance, |element| {
|
||||||
|
if let PathEl::MoveTo(point) | PathEl::LineTo(point) = element {
|
||||||
|
points.push(point_to_dvec2(point));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let chord_length: f64 = points.windows(2).map(|pair| pair[0].distance(pair[1])).sum();
|
||||||
|
if chord_length <= 0. || !chord_length.is_finite() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let scale = arc_length / chord_length;
|
||||||
|
|
||||||
|
let first_new_piece = contour.pieces.len();
|
||||||
|
for pair in points.windows(2) {
|
||||||
|
let length = pair[0].distance(pair[1]);
|
||||||
|
if length > 0. {
|
||||||
|
contour.pieces.push(FlatPiece {
|
||||||
|
start: pair[0],
|
||||||
|
end: pair[1],
|
||||||
|
arc_span: length * scale,
|
||||||
|
ends_segment: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if contour.pieces.len() > first_new_piece
|
||||||
|
&& let Some(last) = contour.pieces.last_mut()
|
||||||
|
{
|
||||||
|
last.ends_segment = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the fill (nonzero) lies on the contour's right side, probed just beside the middle of its longest piece.
|
||||||
|
fn right_side_is_filled(path: &BezPath, contour: &FlatContour, side_sign: f64) -> bool {
|
||||||
|
let Some(piece) = contour.pieces.iter().max_by(|a, b| a.start.distance_squared(a.end).total_cmp(&b.start.distance_squared(b.end))) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
let chord = piece.end - piece.start;
|
||||||
|
let right = side_sign * chord.normalize().perp();
|
||||||
|
let probe = piece.start.lerp(piece.end, 0.5) + right * chord.length() * 1e-4;
|
||||||
|
path.winding(dvec2_to_point(probe)) != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The arc length intervals kurbo draws as dashes along a contour of the given `length`, with the pattern restarting at its start,
|
||||||
|
/// or `None` when the pattern draws a solid line.
|
||||||
|
fn dash_intervals(lengths: &[f64], offset: f64, length: f64) -> Option<Vec<(f64, f64)>> {
|
||||||
|
// An odd-length pattern repeats with the dash and gap roles swapped, so its phase comes back around after two repetitions
|
||||||
|
let pattern_length: f64 = lengths.iter().sum();
|
||||||
|
let period = if lengths.len() % 2 == 1 { 2. * pattern_length } else { pattern_length };
|
||||||
|
let phase = offset.rem_euclid(period);
|
||||||
|
if lengths.is_empty() || period <= 0. || !phase.is_finite() || !length.is_finite() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find where the offset lands in the pattern
|
||||||
|
let mut index = 0;
|
||||||
|
let mut remaining = lengths[0] - phase;
|
||||||
|
let mut drawing = true;
|
||||||
|
while remaining < 0. {
|
||||||
|
index = (index + 1) % lengths.len();
|
||||||
|
remaining += lengths[index];
|
||||||
|
drawing = !drawing;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Walk the pattern along the contour, alternating between dashes and gaps
|
||||||
|
let mut intervals = Vec::new();
|
||||||
|
let mut position = 0.;
|
||||||
|
loop {
|
||||||
|
let end = position + remaining;
|
||||||
|
if drawing {
|
||||||
|
intervals.push((position, end.min(length)));
|
||||||
|
}
|
||||||
|
if end >= length {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
position = end;
|
||||||
|
index = (index + 1) % lengths.len();
|
||||||
|
remaining = lengths[index];
|
||||||
|
drawing = !drawing;
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(intervals)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use glam::DAffine2;
|
||||||
|
|
||||||
|
const TOLERANCE: f64 = 0.01;
|
||||||
|
|
||||||
|
fn polyline(points: &[(f64, f64)], closed: bool) -> BezPath {
|
||||||
|
let mut path = BezPath::new();
|
||||||
|
for (index, &(x, y)) in points.iter().enumerate() {
|
||||||
|
if index == 0 {
|
||||||
|
path.move_to((x, y));
|
||||||
|
} else {
|
||||||
|
path.line_to((x, y));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if closed {
|
||||||
|
path.close_path();
|
||||||
|
}
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
fn assert_chart(chart: &PathChart, point: (f64, f64), expected: (f64, f64)) {
|
||||||
|
let Some((u, v)) = chart.chart_at(DVec2::new(point.0, point.1)) else {
|
||||||
|
panic!("{point:?} should be charted");
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
(u - expected.0).abs() < 1e-9 && (v - expected.1).abs() < 1e-9,
|
||||||
|
"{point:?} charted at {:?}, expected {expected:?}",
|
||||||
|
(u, v)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_straight_line_runs_u_along_it_and_v_from_its_left_edge_to_its_right() {
|
||||||
|
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.)], false), &Stroke::new(10.), TOLERANCE);
|
||||||
|
|
||||||
|
// Heading along +X with +Y down, the right side is +Y
|
||||||
|
assert_chart(&chart, (25., -5.), (0.25, 0.));
|
||||||
|
assert_chart(&chart, (50., 0.), (0.5, 0.5));
|
||||||
|
assert_chart(&chart, (75., 5.), (0.75, 1.));
|
||||||
|
assert_chart(&chart, (100., 2.5), (1., 0.75));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closed_contours_each_span_zero_to_one_from_their_start_points() {
|
||||||
|
let mut path = polyline(&[(0., 0.), (10., 0.), (10., 10.), (0., 10.)], true);
|
||||||
|
path.extend(polyline(&[(120., 0.), (120., 10.), (110., 10.), (110., 0.)], true));
|
||||||
|
let chart = PathChart::new(&path, &Stroke::new(2.), TOLERANCE);
|
||||||
|
|
||||||
|
assert_chart(&chart, (5., 0.), (5. / 40., 0.5));
|
||||||
|
assert_chart(&chart, (0., 5.), (35. / 40., 0.5));
|
||||||
|
assert_chart(&chart, (120., 5.), (5. / 40., 0.5));
|
||||||
|
assert_chart(&chart, (115., 0.), (35. / 40., 0.5));
|
||||||
|
|
||||||
|
assert_eq!(chart.point_at(0, 0.5), Some(DVec2::new(10., 10.)));
|
||||||
|
assert_eq!(chart.point_at(1, 0.), Some(DVec2::new(120., 0.)));
|
||||||
|
assert_eq!(chart.point_at(1, 0.25), Some(DVec2::new(120., 10.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_round_joins_wedge_keeps_the_arc_length_of_its_corner() {
|
||||||
|
let stroke = Stroke {
|
||||||
|
join: StrokeJoin::Round,
|
||||||
|
..Stroke::new(20.)
|
||||||
|
};
|
||||||
|
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.), (100., 100.)], false), &stroke, TOLERANCE);
|
||||||
|
|
||||||
|
// Turning right at the corner, its wedge lies on the left, where `v` falls from 0.5 at the corner to 0 at the round edge
|
||||||
|
for (x, y) in [(105., -5.), (107., -2.), (101., -9.), (100.5, -0.5)] {
|
||||||
|
let distance = DVec2::new(x - 100., y).length();
|
||||||
|
assert_chart(&chart, (x, y), (0.5, 0.5 - distance / 20.));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_miters_tip_keeps_v_within_zero_to_one() {
|
||||||
|
let stroke = Stroke {
|
||||||
|
join_miter_limit: 100.,
|
||||||
|
..Stroke::new(10.)
|
||||||
|
};
|
||||||
|
let points = [(0., 0.), (100., 0.), (0., 50.)];
|
||||||
|
let chart = PathChart::new(&polyline(&points, false), &stroke, TOLERANCE);
|
||||||
|
|
||||||
|
let corner = DVec2::new(100., 0.);
|
||||||
|
let incoming = DVec2::X;
|
||||||
|
let outgoing = (DVec2::new(0., 50.) - corner).normalize();
|
||||||
|
let corner_u = 100. / (100. + DVec2::new(100., 50.).length());
|
||||||
|
|
||||||
|
// The sharp right turn's miter points along the bisector of the two left normals, reaching the stroke's left edge at its tip
|
||||||
|
let left_normals = [-incoming.perp(), -outgoing.perp()];
|
||||||
|
let bisector = (left_normals[0] + left_normals[1]).normalize();
|
||||||
|
let tip_distance = 5. / bisector.dot(left_normals[0]);
|
||||||
|
for fraction in [0.1, 0.5, 0.9, 0.999] {
|
||||||
|
let point = corner + bisector * tip_distance * fraction;
|
||||||
|
assert_chart(&chart, (point.x, point.y), (corner_u, 0.5 * (1. - fraction)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn caps_extend_u_below_zero_and_above_one_linearly() {
|
||||||
|
let path = polyline(&[(0., 0.), (100., 0.)], false);
|
||||||
|
for cap in [StrokeCap::Square, StrokeCap::Round] {
|
||||||
|
let chart = PathChart::new(&path, &Stroke { cap, ..Stroke::new(10.) }, TOLERANCE);
|
||||||
|
assert_chart(&chart, (-3., 1.), (-0.03, 0.6));
|
||||||
|
assert_chart(&chart, (104., -2.), (1.04, 0.3));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Past a butt cap, nothing draws, so the fringe takes the nearest point on the path
|
||||||
|
let chart = PathChart::new(
|
||||||
|
&path,
|
||||||
|
&Stroke {
|
||||||
|
cap: StrokeCap::Butt,
|
||||||
|
..Stroke::new(10.)
|
||||||
|
},
|
||||||
|
TOLERANCE,
|
||||||
|
);
|
||||||
|
assert_chart(&chart, (-3., 1.), (0., 0.6));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dashes_chart_like_the_solid_stroke_and_a_gap_never_wins_over_a_dash() {
|
||||||
|
let line = polyline(&[(0., 0.), (100., 0.)], false);
|
||||||
|
let dashed = Stroke {
|
||||||
|
dash_lengths: vec![10., 10.],
|
||||||
|
..Stroke::new(4.)
|
||||||
|
};
|
||||||
|
let solid_chart = PathChart::new(&line, &Stroke::new(4.), TOLERANCE);
|
||||||
|
let dashed_chart = PathChart::new(&line, &dashed, TOLERANCE);
|
||||||
|
for x in [5., 15., 25., 92.] {
|
||||||
|
let point = DVec2::new(x, 1.);
|
||||||
|
assert_eq!(dashed_chart.chart_at(point), solid_chart.chart_at(point), "the dashed stroke should chart like the solid one at {x}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each vertical line crosses the horizontal one 45 or 55 units along itself, where its own dash pattern draws or skips
|
||||||
|
let crossing_u = |crossing_x: f64, vertical_start_y: f64| {
|
||||||
|
let mut path = line.clone();
|
||||||
|
path.extend(polyline(&[(crossing_x, vertical_start_y), (crossing_x, vertical_start_y + 100.)], false));
|
||||||
|
let chart = PathChart::new(&path, &dashed, TOLERANCE);
|
||||||
|
chart.chart_at(DVec2::new(crossing_x, 0.)).map(|(u, _)| u)
|
||||||
|
};
|
||||||
|
|
||||||
|
// The later line's gap leaves the earlier line's dash showing
|
||||||
|
assert_eq!(crossing_u(5., -55.), Some(0.05));
|
||||||
|
// The later line's dash covers the earlier line's gap
|
||||||
|
assert_eq!(crossing_u(15., -45.), Some(0.45));
|
||||||
|
// Where both draw, the later line is on top
|
||||||
|
assert_eq!(crossing_u(25., -45.), Some(0.45));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_figure_eights_later_pass_wins_with_the_fold_on_its_bands_edge() {
|
||||||
|
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 100.), (100., 0.), (0., 100.)], true), &Stroke::new(10.), TOLERANCE);
|
||||||
|
let diagonal = 100. * 2_f64.sqrt();
|
||||||
|
let length = 2. * diagonal + 200.;
|
||||||
|
|
||||||
|
// The crossing belongs to the second diagonal, which comes later
|
||||||
|
let Some((u, _)) = chart.chart_at(DVec2::new(50., 50.)) else {
|
||||||
|
panic!("the crossing should be charted")
|
||||||
|
};
|
||||||
|
assert!((u - (diagonal + 100. + diagonal / 2.) / length).abs() < 1e-9);
|
||||||
|
|
||||||
|
// Along the first diagonal, the fold lies at the edge of the second one's band, where x and y pass 50 + 5 / √2 ≈ 53.54
|
||||||
|
let Some((inside_u, _)) = chart.chart_at(DVec2::splat(53.4)) else {
|
||||||
|
panic!("the fold should be charted")
|
||||||
|
};
|
||||||
|
let Some((outside_u, _)) = chart.chart_at(DVec2::splat(53.7)) else {
|
||||||
|
panic!("past the fold should be charted")
|
||||||
|
};
|
||||||
|
assert!(inside_u > 0.5, "within the later band, the later pass should win");
|
||||||
|
assert!((outside_u - 53.7 * 2_f64.sqrt() / length).abs() < 1e-9, "past the later band, the earlier pass should show");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_curves_end_reaches_u_of_one() {
|
||||||
|
let mut path = BezPath::new();
|
||||||
|
path.move_to((0., 0.));
|
||||||
|
path.curve_to((30., 80.), (70., -80.), (100., 0.));
|
||||||
|
let chart = PathChart::new(&path, &Stroke::new(2.), TOLERANCE);
|
||||||
|
|
||||||
|
let Some((u, v)) = chart.chart_at(DVec2::new(100., 0.)) else {
|
||||||
|
panic!("the end should be charted")
|
||||||
|
};
|
||||||
|
assert!((u - 1.).abs() < 1e-9, "the end should chart at u = 1, not {u}");
|
||||||
|
assert!((v - 0.5).abs() < 1e-9);
|
||||||
|
|
||||||
|
let Some(end) = chart.point_at(0, 1.) else { panic!("the contour should exist") };
|
||||||
|
assert!(end.abs_diff_eq(DVec2::new(100., 0.), 1e-9));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inside_and_outside_bands_lie_on_their_side_of_the_fill() {
|
||||||
|
let clockwise = polyline(&[(0., 0.), (100., 0.), (100., 100.), (0., 100.)], true);
|
||||||
|
let counterclockwise = polyline(&[(0., 0.), (0., 100.), (100., 100.), (100., 0.)], true);
|
||||||
|
let aligned = |align| Stroke { align, ..Stroke::new(10.) };
|
||||||
|
|
||||||
|
// Clockwise on screen, the right side is inside, so the inside band runs from the path (left edge) inward
|
||||||
|
let chart = PathChart::new(&clockwise, &aligned(StrokeAlign::Inside), TOLERANCE);
|
||||||
|
assert_chart(&chart, (50., 2.), (0.125, 0.2));
|
||||||
|
let chart = PathChart::new(&clockwise, &aligned(StrokeAlign::Outside), TOLERANCE);
|
||||||
|
assert_chart(&chart, (50., -2.), (0.125, 0.8));
|
||||||
|
|
||||||
|
// Counterclockwise, the right side is outside, so the inside band runs inward to the path (right edge)
|
||||||
|
let chart = PathChart::new(&counterclockwise, &aligned(StrokeAlign::Inside), TOLERANCE);
|
||||||
|
assert_chart(&chart, (2., 50.), (0.125, 0.8));
|
||||||
|
let chart = PathChart::new(&counterclockwise, &aligned(StrokeAlign::Outside), TOLERANCE);
|
||||||
|
assert_chart(&chart, (-2., 50.), (0.125, 0.2));
|
||||||
|
|
||||||
|
// An open path isn't aligned, so its band stays centered
|
||||||
|
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.)], false), &aligned(StrokeAlign::Inside), TOLERANCE);
|
||||||
|
assert_chart(&chart, (50., 0.), (0.5, 0.5));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_mirrored_stroke_transform_flips_v() {
|
||||||
|
let mirrored = Stroke {
|
||||||
|
transform: DAffine2::from_scale(DVec2::new(1., -1.)),
|
||||||
|
..Stroke::new(10.)
|
||||||
|
};
|
||||||
|
let chart = PathChart::new(&polyline(&[(0., 0.), (100., 0.)], false), &mirrored, TOLERANCE);
|
||||||
|
|
||||||
|
assert_chart(&chart, (25., -5.), (0.25, 1.));
|
||||||
|
assert_chart(&chart, (75., 5.), (0.75, 0.));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -138,6 +138,20 @@ impl StrokeAlign {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Where a stroke's paint is placed: in the plane, or along the stroke's paths.
|
||||||
|
#[repr(C)]
|
||||||
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[widget(Radio)]
|
||||||
|
pub enum PaintMapping {
|
||||||
|
/// The paint is placed in the canvas as usual.
|
||||||
|
#[default]
|
||||||
|
Plane,
|
||||||
|
/// The paint follows the stroke, its Along direction running the length of each path and Across running from the left edge to the right.
|
||||||
|
Path,
|
||||||
|
}
|
||||||
|
|
||||||
// Backs the control bar's stroke popover radio and legacy document parsing: the relative order
|
// Backs the control bar's stroke popover radio and legacy document parsing: the relative order
|
||||||
// of the Fill and Stroke nodes in the chain is what actually determines the paint order
|
// of the Fill and Stroke nodes in the chain is what actually determines the paint order
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
@@ -220,6 +234,8 @@ pub struct Stroke {
|
|||||||
pub join_miter_limit: f64,
|
pub join_miter_limit: f64,
|
||||||
#[cfg_attr(feature = "serde", serde(default))]
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
pub align: StrokeAlign,
|
pub align: StrokeAlign,
|
||||||
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
|
pub paint_mapping: PaintMapping,
|
||||||
#[cfg_attr(feature = "serde", serde(default = "daffine2_identity"))]
|
#[cfg_attr(feature = "serde", serde(default = "daffine2_identity"))]
|
||||||
pub transform: DAffine2,
|
pub transform: DAffine2,
|
||||||
}
|
}
|
||||||
@@ -234,6 +250,7 @@ impl Stroke {
|
|||||||
join: StrokeJoin::Miter,
|
join: StrokeJoin::Miter,
|
||||||
join_miter_limit: 4.,
|
join_miter_limit: 4.,
|
||||||
align: StrokeAlign::Center,
|
align: StrokeAlign::Center,
|
||||||
|
paint_mapping: PaintMapping::Plane,
|
||||||
transform: DAffine2::IDENTITY,
|
transform: DAffine2::IDENTITY,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -247,6 +264,7 @@ impl Stroke {
|
|||||||
join: if time < 0.5 { self.join } else { other.join },
|
join: if time < 0.5 { self.join } else { other.join },
|
||||||
join_miter_limit: self.join_miter_limit + (other.join_miter_limit - self.join_miter_limit) * time,
|
join_miter_limit: self.join_miter_limit + (other.join_miter_limit - self.join_miter_limit) * time,
|
||||||
align: if time < 0.5 { self.align } else { other.align },
|
align: if time < 0.5 { self.align } else { other.align },
|
||||||
|
paint_mapping: if time < 0.5 { self.paint_mapping } else { other.paint_mapping },
|
||||||
transform: {
|
transform: {
|
||||||
// Decompose into scale/rotation/skew and interpolate each component separately.
|
// Decompose into scale/rotation/skew and interpolate each component separately.
|
||||||
// We do this instead of linear matrix interpolation because that passes through a zero matrix
|
// We do this instead of linear matrix interpolation because that passes through a zero matrix
|
||||||
@@ -351,6 +369,7 @@ impl Default for Stroke {
|
|||||||
join: StrokeJoin::Miter,
|
join: StrokeJoin::Miter,
|
||||||
join_miter_limit: 4.,
|
join_miter_limit: 4.,
|
||||||
align: StrokeAlign::Center,
|
align: StrokeAlign::Center,
|
||||||
|
paint_mapping: PaintMapping::Plane,
|
||||||
transform: DAffine2::IDENTITY,
|
transform: DAffine2::IDENTITY,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ use vector_types::vector::misc::{
|
|||||||
BezierHandles, CentroidType, ExtrudeJoiningAlgorithm, InterpolationDistribution, ManipulatorGroup, PointSpacingType, RowsOrColumns, Tangent, UnweldMethod, WeldMethod, dvec2_to_point,
|
BezierHandles, CentroidType, ExtrudeJoiningAlgorithm, InterpolationDistribution, ManipulatorGroup, PointSpacingType, RowsOrColumns, Tangent, UnweldMethod, WeldMethod, dvec2_to_point,
|
||||||
handles_to_segment, is_linear, point_to_dvec2, segment_to_handles,
|
handles_to_segment, is_linear, point_to_dvec2, segment_to_handles,
|
||||||
};
|
};
|
||||||
use vector_types::vector::style::{DashPattern, Gradient, GradientSettings, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
use vector_types::vector::style::{DashPattern, Gradient, GradientSettings, PaintMapping, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use vector_types::vector::{
|
use vector_types::vector::{
|
||||||
CurveType, IdCollisionSet, Path, PointId, SegmentId, WorkingVector, curve_type_at, edit_item_geometry, edit_item_points, handle_point, no_paths, paths_from_item_attributes,
|
CurveType, IdCollisionSet, Path, PointId, SegmentId, WorkingVector, curve_type_at, edit_item_geometry, edit_item_points, handle_point, no_paths, paths_from_item_attributes,
|
||||||
paths_from_list_row_attributes, push_path, push_paths, reverse_path_flows, shared_paths_from_item_attributes, span_endpoints, spans,
|
paths_from_list_row_attributes, push_path, push_paths, reverse_path_flows, shared_paths_from_item_attributes, span_endpoints, spans,
|
||||||
@@ -507,7 +507,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
|
/// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry.
|
||||||
#[node_macro::node(category("Vector: Style"), icon("NodeStroke"), path(graphene_core::vector), inspector("stroke_inspector"))]
|
#[node_macro::node(category("Vector: Style"), icon("NodeStroke"), path(graphene_core::vector), inspector("stroke_inspector"), version(2))]
|
||||||
fn stroke<V>(
|
fn stroke<V>(
|
||||||
_: impl Ctx,
|
_: impl Ctx,
|
||||||
/// The content with vector paths to apply the stroke style to.
|
/// The content with vector paths to apply the stroke style to.
|
||||||
@@ -536,18 +536,21 @@ fn stroke<V>(
|
|||||||
/// The phase offset distance from the starting point of the dash pattern.
|
/// The phase offset distance from the starting point of the dash pattern.
|
||||||
#[unit(" px")]
|
#[unit(" px")]
|
||||||
dash_offset: Item<f64>,
|
dash_offset: Item<f64>,
|
||||||
|
/// Where the paint is placed: in the canvas like a fill's, or along the stroke's paths.
|
||||||
|
paint_mapping: Item<PaintMapping>,
|
||||||
) -> Item<V>
|
) -> Item<V>
|
||||||
where
|
where
|
||||||
Item<V>: VectorItemMut + Send,
|
Item<V>: VectorItemMut + Send,
|
||||||
{
|
{
|
||||||
let mut content = content;
|
let mut content = content;
|
||||||
let (weight, align, cap, join, miter_limit, dash_offset) = (
|
let (weight, align, cap, join, miter_limit, dash_offset, paint_mapping) = (
|
||||||
weight.into_element(),
|
weight.into_element(),
|
||||||
align.into_element(),
|
align.into_element(),
|
||||||
cap.into_element(),
|
cap.into_element(),
|
||||||
join.into_element(),
|
join.into_element(),
|
||||||
miter_limit.into_element(),
|
miter_limit.into_element(),
|
||||||
dash_offset.into_element(),
|
dash_offset.into_element(),
|
||||||
|
paint_mapping.into_element(),
|
||||||
);
|
);
|
||||||
let dash_lengths = dash_pattern.into_element().clamped_lengths();
|
let dash_lengths = dash_pattern.into_element().clamped_lengths();
|
||||||
|
|
||||||
@@ -559,6 +562,7 @@ where
|
|||||||
join,
|
join,
|
||||||
join_miter_limit: miter_limit,
|
join_miter_limit: miter_limit,
|
||||||
align,
|
align,
|
||||||
|
paint_mapping,
|
||||||
transform: DAffine2::IDENTITY,
|
transform: DAffine2::IDENTITY,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user