Files
Keavon Chambers 1335e9a0f8 Make effect paints fit gradients like Fill and draw images where they're placed (#5047)
* Make effect paints draw images where they're placed rather than stretched

* Make effect paints fit gradients like Fill, including across text
2026-11-30 19:22:13 -08:00

5434 lines
228 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use crate::voronoi::PointDiagramError;
use core::cmp::Ordering;
use core::convert::Infallible;
use core::f64::consts::{PI, TAU};
use core::hash::{Hash, Hasher};
use core_types::blending::BlendMode;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{ATTR_APPEARANCE, ATTR_ID, ATTR_PATHS, Item, ItemAttributeValues, List, ListDyn, NodeIdPath};
use core_types::math::spread::spread_factors;
use core_types::transform::{Footprint, Transform};
use core_types::uuid::NodeId;
use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_FORM, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx,
ExtractAll, InjectFootprint, OwnedContextImpl,
};
use core_types::{Interrupt, NodeError};
use glam::{DAffine2, DMat2, DVec2};
use graphic_types::Vector;
use graphic_types::graphic::{bake_transform_into_attributes, is_paint_present};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Appearance, Cover, CoverPlacement, Coverage, Graphic, IntoGraphicList, paint_with_envelope_effects, stamp_coverage, stamped_transform};
use kurbo::simplify::{SimplifyOptions, simplify_bezpath};
use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Shape};
use rand::{RngExt, SeedableRng};
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
use vector_types::GradientForm;
use vector_types::gradient::{build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box};
use vector_types::vector::SetVectorPaths;
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,
tangent_on_bezpath,
};
use vector_types::vector::algorithms::concave_hull::concave_hull_of_geometry;
use vector_types::vector::algorithms::offset_bezpath::{OffsetPathError, offset_bezpath};
use vector_types::vector::algorithms::spline::{solve_spline_first_handle_closed, solve_spline_first_handle_open};
use vector_types::vector::algorithms::weld::WeldExt;
use vector_types::vector::misc::{
BezierHandles, CentroidType, ExtrudeJoiningAlgorithm, InterpolationDistribution, ManipulatorGroup, PointSpacingType, RowsOrColumns, Tangent, UnweldMethod, WeldMethod, dvec2_to_point,
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::{
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,
};
/// Appends one point to the working form, returning the index that names it.
pub(crate) fn push_working_point(working: &mut WorkingVector, id: PointId, position: DVec2) -> usize {
let index = working.point_ids.len();
working.point_ids.push(id);
working.point_positions.push(position);
index
}
/// Appends one segment to the working form, running between two of its point indices.
pub(crate) fn push_working_segment(working: &mut WorkingVector, id: SegmentId, start: usize, end: usize, handles: BezierHandles) {
working.segment_ids.push(id);
working.segment_start.push(start);
working.segment_end.push(end);
working.segment_handles.push(handles);
}
/// The ID continuing the working form's point sequence.
fn next_working_point_id(working: &WorkingVector) -> PointId {
working
.point_ids
.iter()
.copied()
.filter(|&id| id != PointId::UNNAMED)
.max()
.map(|mut id| id.next_id())
.unwrap_or(PointId::ZERO)
}
/// The ID continuing the working form's segment sequence.
fn next_working_segment_id(working: &WorkingVector) -> SegmentId {
working.segment_ids.iter().copied().max().map(|mut id| id.next_id()).unwrap_or(SegmentId::ZERO)
}
/// Implemented for `List` types that contain vector items reachable via mutable access.
/// Used by the whole-collection Vary Fill Colors and Vary Stroke Colors nodes so they can apply to either `List<Graphic>` or `List<Vector>`.
trait VectorListIterMut {
fn for_each_vector_list_mut(&mut self, f: impl FnMut(&mut List<Vector>));
fn vector_count(&self) -> usize;
}
impl VectorListIterMut for List<Graphic> {
fn for_each_vector_list_mut(&mut self, mut f: impl FnMut(&mut List<Vector>)) {
for graphic in self.iter_element_values_mut() {
match graphic {
// A lone vector is lifted into a one-item list for the duration of the call, so the shared per-list logic reaches it
Graphic::Vector(item) => {
let mut lifted = List::new_from_item(std::mem::take(&mut **item));
f(&mut lifted);
if let Some(updated) = lifted.into_iter().next() {
**item = updated;
}
}
graphic => {
if let Some(vector_list) = graphic.as_vector_list_mut() {
f(vector_list);
}
}
}
}
}
fn vector_count(&self) -> usize {
self.iter_element_values()
.map(|element| match element {
Graphic::Vector(_) => 1,
element => element.as_vector_list().map_or(0, List::len),
})
.sum()
}
}
impl VectorListIterMut for List<Vector> {
fn for_each_vector_list_mut(&mut self, mut f: impl FnMut(&mut List<Vector>)) {
f(self);
}
fn vector_count(&self) -> usize {
self.len()
}
}
/// Element-level analog of [`VectorListIterMut`] for the element-wise fill and stroke nodes, operating on a
/// single `Item<Vector>` or `Item<Graphic>`.
trait VectorItemMut {
fn for_each_vector_mut(&mut self, f: impl FnMut(&mut Vector, &List<Path>, DAffine2));
}
impl VectorItemMut for Item<Vector> {
fn for_each_vector_mut(&mut self, mut f: impl FnMut(&mut Vector, &List<Path>, DAffine2)) {
let paths = shared_paths_from_item_attributes(self);
let transform = self.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
f(self.element_mut(), &paths, transform);
}
}
impl VectorItemMut for Item<Graphic> {
fn for_each_vector_mut(&mut self, mut f: impl FnMut(&mut Vector, &List<Path>, DAffine2)) {
match self.element_mut() {
Graphic::Vector(item) => {
let paths = shared_paths_from_item_attributes(item);
let transform = item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
f(item.element_mut(), &paths, transform);
}
element => {
let Some(vector_list) = element.as_vector_list_mut() else { return };
for index in 0..vector_list.len() {
let paths = paths_from_list_row_attributes(vector_list, index).cloned().unwrap_or_default();
let transform = vector_list.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index);
let Some(vector) = vector_list.element_mut(index) else { continue };
f(vector, &paths, transform);
}
}
}
}
}
/// Geometry counterpart to [`VectorItemMut`] for the element-wise modifier nodes, running a per-item transformation over
/// every vector reachable from the content. Geometry is never inherited, so this recurses into nested groups.
trait MapVectorItems: Sized {
fn map_vector_items(content: Item<Self>, mut f: impl FnMut(Item<Vector>) -> Item<Vector>) -> Item<Self> {
let Ok(content) = Self::try_map_vector_items(content, |item| Ok::<_, Infallible>(f(item)));
content
}
/// Runs `f` on every vector item reachable from the content, stopping at the first error.
fn try_map_vector_items<E>(content: Item<Self>, f: impl FnMut(Item<Vector>) -> Result<Item<Vector>, E>) -> Result<Item<Self>, E>;
/// Mutable access to each reachable vector at once, each paired with a copy of its paths, for callers that must await between elements.
fn vector_elements_mut(content: &mut Item<Self>) -> Vec<(&mut Vector, List<Path>)>;
}
impl MapVectorItems for Vector {
fn try_map_vector_items<E>(content: Item<Vector>, mut f: impl FnMut(Item<Vector>) -> Result<Item<Vector>, E>) -> Result<Item<Vector>, E> {
f(content)
}
fn vector_elements_mut(content: &mut Item<Vector>) -> Vec<(&mut Vector, List<Path>)> {
let paths = paths_from_item_attributes(content).cloned().unwrap_or_default();
vec![(content.element_mut(), paths)]
}
}
impl MapVectorItems for Graphic {
fn try_map_vector_items<E>(content: Item<Graphic>, mut f: impl FnMut(Item<Vector>) -> Result<Item<Vector>, E>) -> Result<Item<Graphic>, E> {
fn map_nested<E>(graphic: &mut Graphic, f: &mut impl FnMut(Item<Vector>) -> Result<Item<Vector>, E>) -> Result<(), E> {
match graphic {
// Collecting from zero items would drop the attribute columns, so an empty list is left alone
Graphic::VectorList(list) if !list.is_empty() => *list = std::mem::take(list).into_iter().map(&mut *f).collect::<Result<_, E>>()?,
Graphic::GraphicList(list) => list.iter_element_values_mut().try_for_each(|nested| map_nested(nested, f))?,
Graphic::Vector(item) => **item = f(std::mem::take(&mut **item))?,
Graphic::Graphic(item) => map_nested(item.element_mut(), f)?,
_ => {}
}
Ok(())
}
let mut content = content;
map_nested(content.element_mut(), &mut f)?;
Ok(content)
}
fn vector_elements_mut(content: &mut Item<Graphic>) -> Vec<(&mut Vector, List<Path>)> {
fn collect<'a>(graphic: &'a mut Graphic, elements: &mut Vec<(&'a mut Vector, List<Path>)>) {
match graphic {
Graphic::VectorList(list) => {
let paths: Vec<List<Path>> = (0..list.len()).map(|index| paths_from_list_row_attributes(list, index).cloned().unwrap_or_default()).collect();
elements.extend(list.iter_element_values_mut().zip(paths));
}
Graphic::GraphicList(list) => list.iter_element_values_mut().for_each(|nested| collect(nested, elements)),
Graphic::Vector(item) => {
let paths = paths_from_item_attributes(&**item).cloned().unwrap_or_default();
elements.push((item.element_mut(), paths));
}
Graphic::Graphic(item) => collect(item.element_mut(), elements),
_ => {}
}
}
let mut elements = Vec::new();
collect(content.element_mut(), &mut elements);
elements
}
}
/// Counterpart to [`MapVectorItems`] for modifiers whose per-item result is a whole list rather than one item.
trait ExpandVectorItems: Sized {
fn expand_vector_items(content: Item<Self>, f: impl FnMut(Item<Vector>) -> List<Vector>) -> List<Self>;
}
impl ExpandVectorItems for Vector {
fn expand_vector_items(content: Item<Vector>, mut f: impl FnMut(Item<Vector>) -> List<Vector>) -> List<Vector> {
f(content)
}
}
impl ExpandVectorItems for Graphic {
fn expand_vector_items(content: Item<Graphic>, mut f: impl FnMut(Item<Vector>) -> List<Vector>) -> List<Graphic> {
fn expand_nested(graphic: &mut Graphic, f: &mut impl FnMut(Item<Vector>) -> List<Vector>) {
match graphic {
// Collecting from zero items would drop the attribute columns, so an empty list is left alone
Graphic::VectorList(list) if !list.is_empty() => {
let mut expanded = List::with_capacity(list.len());
for item in std::mem::take(list) {
expanded.extend(f(item));
}
*list = expanded;
}
Graphic::GraphicList(list) => list.iter_element_values_mut().for_each(|nested| expand_nested(nested, f)),
// One item expanding into many is a rank raise, so the leaf becomes the list it grew into
Graphic::Vector(item) => {
let expanded = f(std::mem::take(&mut **item));
*graphic = Graphic::VectorList(expanded);
}
Graphic::Graphic(item) => expand_nested(item.element_mut(), f),
_ => {}
}
}
let mut content = content;
expand_nested(content.element_mut(), &mut f);
List::new_from_item(content)
}
}
#[derive(Debug, thiserror::Error)]
pub enum VaryColorsError {
#[error("The gradient has no colors to assign")]
EmptyGradient,
}
/// Uniquely recolors the fill of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), icon("NodeVaryFillColors"), path(graphene_core::vector), version(2), footprint_invariant)]
fn vary_fill_colors<T>(
_: impl Ctx,
/// The content with vector paths to apply the fill style to.
#[implementations(List<Graphic>, List<Vector>)]
#[widget(ParsedWidgetOverride::Hidden)]
content: T,
/// The range of colors to select from.
#[default(Color::BLACK, Color::WHITE)]
#[widget(ParsedWidgetOverride::Custom = "vary_fill_colors_gradient")]
gradient: Item<Gradient>,
/// Whether to reverse the gradient.
reverse: Item<bool>,
/// Whether to randomize the color selection for each element from throughout the gradient.
randomize: Item<bool>,
/// Seed to determine unique variations on the randomized color selection.
#[widget(ParsedWidgetOverride::Custom = "vary_fill_colors_seed")]
#[hard(0..)]
seed: Item<i64>,
/// The number of elements to span across the gradient before repeating. A 0 value will span the entire gradient once.
#[widget(ParsedWidgetOverride::Custom = "vary_fill_colors_repeat_every")]
#[hard(0..)]
repeat_every: Item<i64>,
) -> Result<T, VaryColorsError>
where
T: VectorListIterMut + Send,
{
vary_cover_colors(content, Cover::Fill, gradient, reverse, randomize, seed, repeat_every)
}
/// Uniquely recolors the stroke of every vector element to individual colors sampled along a chosen gradient.
#[node_macro::node(category("Vector: Style"), icon("NodeVaryStrokeColors"), path(graphene_core::vector), footprint_invariant)]
fn vary_stroke_colors<T>(
_: impl Ctx,
/// The content with vector paths to apply the stroke style to.
#[implementations(List<Graphic>, List<Vector>)]
#[widget(ParsedWidgetOverride::Hidden)]
content: T,
/// The range of colors to select from.
#[default(Color::BLACK, Color::WHITE)]
#[widget(ParsedWidgetOverride::Custom = "vary_stroke_colors_gradient")]
gradient: Item<Gradient>,
/// Whether to reverse the gradient.
reverse: Item<bool>,
/// Whether to randomize the color selection for each element from throughout the gradient.
randomize: Item<bool>,
/// Seed to determine unique variations on the randomized color selection.
#[widget(ParsedWidgetOverride::Custom = "vary_stroke_colors_seed")]
#[hard(0..)]
seed: Item<i64>,
/// The number of elements to span across the gradient before repeating. A 0 value will span the entire gradient once.
#[widget(ParsedWidgetOverride::Custom = "vary_stroke_colors_repeat_every")]
#[hard(0..)]
repeat_every: Item<i64>,
) -> Result<T, VaryColorsError>
where
T: VectorListIterMut + Send,
{
vary_cover_colors(content, Cover::Stroke, gradient, reverse, randomize, seed, repeat_every)
}
/// Paints the fill or stroke of each vector element with its own color from along the gradient, for the Vary Fill Colors and Vary Stroke Colors nodes.
fn vary_cover_colors<T: VectorListIterMut>(
content: T,
cover: Cover,
gradient: Item<Gradient>,
reverse: Item<bool>,
randomize: Item<bool>,
seed: Item<i64>,
repeat_every: Item<i64>,
) -> Result<T, VaryColorsError> {
let (reverse, randomize, seed, repeat_every) = (reverse.into_element(), randomize.into_element(), seed.into_element(), repeat_every.into_element());
if gradient.element().is_empty() {
return Err(VaryColorsError::EmptyGradient);
}
let gradient = raster_kernels::evaluate_gradient_effects(gradient);
let mut content = content;
let length = content.vector_count();
// The factor spans 0..=1, so the spread deliberately stays Pad (Repeat would wrap the final element onto the first stop's color)
let settings = GradientSettings {
spread: Default::default(),
..GradientSettings::from(&gradient)
};
let element = gradient.into_element();
let gradient = if reverse { element.reversed(settings.cyclic) } else { element };
let evaluator = gradient.evaluator(settings);
let mut factors = spread_factors(length, randomize, seed as u64, repeat_every as u64);
content.for_each_vector_list_mut(|vector_list| {
for index in 0..vector_list.len() {
let factor = factors.next().unwrap_or_default();
let color = evaluator.evaluate(factor);
let color_paint = Graphic::ColorList(List::new_from_element(color));
match cover {
Cover::Fill => {
let transform = stamped_transform(vector_list.attribute_cloned_or_default(ATTR_TRANSFORM, index));
vector_list.with_attribute_mut_or_default::<Appearance, _, _>(ATTR_APPEARANCE, index, |appearance| {
if !appearance.set_paint_of(Cover::Fill, color_paint.clone()) {
appearance.replace_or_insert(Coverage::new_fill(), color_paint.clone(), transform, CoverPlacement::Below);
}
})
}
// The stroke recolor is gated on an existing stroke coverage, since restyling never adds a stroke
Cover::Stroke => {
if vector_list
.attribute::<Appearance>(ATTR_APPEARANCE, index)
.is_some_and(|appearance| appearance.has_cover(Cover::Stroke))
{
vector_list.with_attribute_mut_or_default::<Appearance, _, _>(ATTR_APPEARANCE, index, |appearance| {
appearance.set_paint_of(Cover::Stroke, color_paint.clone());
});
}
}
}
}
});
Ok(content)
}
/// 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"))]
fn fill<V>(
_: impl Ctx,
/// The content with vector paths to apply the fill style to.
#[implementations(Vector, Graphic)]
content: Item<V>,
#[default(Color::BLACK)] paint: Item<Graphic>,
_backup_color: Item<Color>,
#[default(Color::BLACK, Color::WHITE)] _backup_gradient: Item<Gradient>,
_gradient_form: Item<GradientForm>,
_has_transform: Item<bool>,
_transform: Item<DAffine2>,
) -> Item<V>
where
Item<V>: VectorItemMut + Send,
{
let _gradient_form = _gradient_form.into_element();
let (_has_transform, _transform) = (_has_transform.into_element(), *_transform.element());
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
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
// TODO: Stop reading whether the gradient has a form or 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.
let (needs_form, needs_transform) = match &paint {
Graphic::Gradient(item) => (item.attribute::<GradientForm>(ATTR_GRADIENT_FORM).is_none(), item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none()),
Graphic::GradientList(list) => (
list.iter_attribute_values::<GradientForm>(ATTR_GRADIENT_FORM).is_none(),
list.iter_attribute_values::<DAffine2>(ATTR_TRANSFORM).is_none(),
),
_ => (false, false),
};
let stamped_transform = needs_transform.then(|| {
// Without an explicit placement, derive one covering the paint target's bounding box (the CSS `auto` behavior)
if _has_transform {
return _transform;
}
let mut bounds: Option<[DVec2; 2]> = None;
content.for_each_vector_mut(|vector, vector_paths, _| {
if let Some([min, max]) = vector.bounding_box(vector_paths) {
bounds = Some(match bounds {
Some([bmin, bmax]) => [bmin.min(min), bmax.max(max)],
None => [min, max],
});
}
});
// Nudge a degenerate axis so the gradient transform stays invertible, matching the editor's `nonzero_bounding_box`
let [min, mut max] = bounds.unwrap_or([DVec2::ZERO, DVec2::ONE]);
if max.x - min.x < 1e-10 {
max.x = min.x + 1.;
}
if max.y - min.y < 1e-10 {
max.y = min.y + 1.;
}
initial_gradient_transform_for_bounding_box([min, max])
});
match &mut paint {
Graphic::Gradient(item) => {
if needs_form {
item.set_attribute(ATTR_GRADIENT_FORM, _gradient_form);
}
if let Some(transform) = stamped_transform {
item.set_attribute(ATTR_TRANSFORM, transform);
}
}
Graphic::GradientList(list) => {
if needs_form {
for value in list.iter_attribute_values_mut_or_default::<GradientForm>(ATTR_GRADIENT_FORM) {
*value = _gradient_form;
}
}
if let Some(transform) = stamped_transform {
for value in list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
*value = transform;
}
}
}
_ => {}
}
// Appending follows the painter's algorithm: the most downstream paint node in the chain paints on top
stamp_coverage(&mut content, Coverage::new_fill(), paint, CoverPlacement::Above);
content
}
/// 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"))]
fn stroke<V>(
_: impl Ctx,
/// The content with vector paths to apply the stroke style to.
#[implementations(Vector, Graphic)]
content: Item<V>,
/// The stroke paint.
#[default(Color::BLACK)]
paint: Item<Graphic>,
/// The stroke thickness.
#[unit(" px")]
#[hard(0..)]
#[default(2.)]
weight: Item<f64>,
/// The alignment of stroke to the path's centerline or (for closed shapes) the inside or outside of the shape.
align: Item<StrokeAlign>,
/// The shape of the stroke at open endpoints.
cap: Item<StrokeCap>,
/// The curvature of the bent stroke at sharp corners.
join: Item<StrokeJoin>,
/// The threshold for when a miter-joined stroke is converted to a bevel-joined stroke when a sharp angle becomes pointier than this ratio.
#[hard(0..)]
#[default(4.)]
miter_limit: Item<f64>,
/// The stroke dash pattern. Each length forms a distance in a pattern where the first length is a dash, the second is a gap, and so on. If the list is an odd length, the pattern repeats with solid-gap roles reversed.
dash_pattern: Item<DashPattern>,
/// The phase offset distance from the starting point of the dash pattern.
#[unit(" px")]
dash_offset: Item<f64>,
) -> Item<V>
where
Item<V>: VectorItemMut + Send,
{
let mut content = content;
let (weight, align, cap, join, miter_limit, dash_offset) = (
weight.into_element(),
align.into_element(),
cap.into_element(),
join.into_element(),
miter_limit.into_element(),
dash_offset.into_element(),
);
let dash_lengths = dash_pattern.into_element().clamped_lengths();
let stroke = Stroke {
weight,
dash_lengths,
dash_offset,
cap,
join,
join_miter_limit: miter_limit,
align,
transform: DAffine2::IDENTITY,
};
// The wire envelope is dropped for the same reason as in `fill` above
let paint = paint_with_envelope_effects(paint);
stamp_coverage(&mut content, Coverage::new_stroke(&stroke), paint, CoverPlacement::Above);
content
}
/// Builds a stroke dash pattern from a list of lengths that alternate between dash and gap, starting with a dash.
#[node_macro::node(category("Vector: Style"), icon("NodeDashPattern"), path(graphene_core::vector))]
fn dash_pattern(
_: impl Ctx,
/// The dash and gap lengths, alternating and starting with a dash.
lengths: List<f64>,
) -> Item<DashPattern> {
let lengths: Vec<f64> = lengths.iter_element_values().copied().collect();
Item::new_from_element(DashPattern::from(lengths))
}
#[node_macro::node(category("Vector: Path"), icon("NodeRoundCorners"), path(core_types::vector))]
fn round_corners<V: MapVectorItems + Send>(
_: impl Ctx,
#[implementations(Graphic, Vector)] source: Item<V>,
#[unit(" px")]
#[hard(0..)]
#[default(10.)]
radius: Item<f64>,
#[range]
#[hard(0..1)]
#[default(0.5)]
roundness: Item<f64>,
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
edge_length_limit: Item<f64>,
#[unit("°")]
#[range]
#[hard(0..180)]
#[default(5.)]
min_angle_threshold: Item<f64>,
) -> Item<V> {
V::map_vector_items(source, |source| {
let (radius, roundness, edge_length_limit, min_angle_threshold) = (*radius.element(), *roundness.element(), *edge_length_limit.element(), *min_angle_threshold.element());
let source_transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
if !source_transform.matrix2.determinant().is_normal() {
return source;
}
let source_transform_inverse = source_transform.inverse();
let source_paths = shared_paths_from_item_attributes(&source);
let (source, mut attributes) = source.into_parts();
// Flip the roundness to help with user intuition
let roundness = 1. - roundness;
// Convert 0-100 to 0-0.5
let edge_length_limit = edge_length_limit * 0.005;
let mut rounded_subpaths = Vec::new();
for bezpath in source.stroke_bezpath_iter(&source_paths) {
// The radius is measured after the transform, so scaling the layer doesn't scale its rounding
let mut document_bezpath = bezpath.clone();
document_bezpath.apply_affine(Affine::new(source_transform.to_cols_array()));
// A subpath without corners to round passes through as it was
let Some(mut rounded_subpath) = round_subpath_corners(&document_bezpath, radius, roundness, edge_length_limit, min_angle_threshold.to_radians()) else {
rounded_subpaths.push(bezpath);
continue;
};
rounded_subpath.apply_affine(Affine::new(source_transform_inverse.to_cols_array()));
rounded_subpaths.push(rounded_subpath);
}
let (mut result, mut result_paths) = (Vector::default(), List::new());
result.append_bezpaths(&mut result_paths, &rounded_subpaths);
attributes.set_paths(result_paths);
Item::from_parts(result, attributes)
})
}
///Rounds off the anchors where a subpath's direction turns, cutting back along both segments' curves, and leaves smooth joins as they are.
/// Returns `None` when there's no corner to round.
fn round_subpath_corners(subpath: &BezPath, radius: f64, roundness: f64, edge_length_limit: f64, min_angle_threshold: f64) -> Option<BezPath> {
let closed = matches!(subpath.elements().last(), Some(PathEl::ClosePath));
let segments: Vec<PathSeg> = subpath.segments().collect();
let count = segments.len();
// Anchor `i` joins segment `i - 1` to segment `i`, and a closed subpath's first anchor also ends its last segment
let anchor_count = if closed { count } else { count + 1 };
if anchor_count < 3 {
return None;
}
let previous_segment = |anchor: usize| (anchor + count - 1) % count;
let lengths: Vec<f64> = segments.iter().map(|segment| segment.arclen(DEFAULT_ACCURACY)).collect();
// How far back along both of its segments each anchor's corner is cut, or `None` where there's no corner to round
let cut_distances: Vec<Option<f64>> = (0..anchor_count)
.map(|anchor| {
if !closed && (anchor == 0 || anchor == count) {
return None;
}
let arriving = segments[previous_segment(anchor)].tangent_at_end().try_normalize()?;
let leaving = segments[anchor % count].tangent_at_start().try_normalize()?;
let theta = PI - arriving.angle_to(leaving).abs();
// Skip near-straight corners
if theta > PI - min_angle_threshold {
return None;
}
// Calculate the distance, with limits to avoid extreme values
let distance = radius / (theta / 2.).sin();
let shorter_length = lengths[previous_segment(anchor)].min(lengths[anchor % count]);
Some(distance.min(edge_length_limit * shorter_length).max(0.01))
})
.collect();
if cut_distances.iter().all(Option::is_none) {
return None;
}
// Trim each segment back from the corners at its ends, keeping the part between them with its curvature
let trimmed: Vec<PathSeg> = segments
.iter()
.zip(&lengths)
.enumerate()
.map(|(index, (&segment, &length))| {
let start_cut = cut_distances[index].unwrap_or_default();
let end_cut = cut_distances[(index + 1) % anchor_count].unwrap_or_default();
if start_cut == 0. && end_cut == 0. {
return segment;
}
let start_t = if start_cut > 0. {
eval_pathseg_euclidean(segment, start_cut / length, DEFAULT_ACCURACY)
} else {
0.
};
let end_t = if end_cut > 0. {
eval_pathseg_euclidean(segment, 1. - end_cut / length, DEFAULT_ACCURACY)
} else {
1.
};
segment.subsegment(start_t..end_t.max(start_t))
})
.collect();
// Joins the end of the trimmed segment arriving at a corner to the start of the one leaving it
let corner_curve = |rounded: &mut BezPath, arriving: PathSeg, leaving: PathSeg, cut_distance: f64| {
let (start, end) = (point_to_dvec2(arriving.end()), point_to_dvec2(leaving.start()));
let fallback = (end - start).normalize_or_zero();
let handle_length = cut_distance * (1. - roundness);
let start_handle = start + arriving.tangent_at_end().try_normalize().unwrap_or(fallback) * handle_length;
let end_handle = end - leaving.tangent_at_start().try_normalize().unwrap_or(fallback) * handle_length;
rounded.curve_to(dvec2_to_point(start_handle), dvec2_to_point(end_handle), dvec2_to_point(end));
};
// A closed subpath with a corner at its first anchor starts where that corner's rounding begins
let mut rounded = BezPath::new();
let corner_at_start = cut_distances[0];
rounded.move_to(if corner_at_start.is_some() { trimmed[count - 1].end() } else { trimmed[0].start() });
if let Some(cut_distance) = corner_at_start {
corner_curve(&mut rounded, trimmed[count - 1], trimmed[0], cut_distance);
}
for index in 0..count {
rounded.push(trimmed[index].as_path_el());
if index + 1 < count
&& let Some(cut_distance) = cut_distances[index + 1]
{
corner_curve(&mut rounded, trimmed[index], trimmed[index + 1], cut_distance);
}
}
if closed {
rounded.close_path();
}
Some(rounded)
}
/// Joins points lying within a distance of each other into one, connecting the paths they belong to.
#[node_macro::node(category("Vector: Path"), icon("NodeWeld"), path(core_types::vector))]
fn weld<V: MapVectorItems + Send + Sync + 'static>(
_: impl Ctx,
/// The vector with points to join.
#[implementations(Graphic, Vector)]
content: Item<V>,
/// How close points must be to join.
#[unit(" px")]
#[default(0.1)]
#[hard(0.0001..)]
distance: Item<f64>,
/// Which points may join: any within the distance, the two ends of each segment shorter than it, or only the ends of open path flows.
method: Item<WeldMethod>,
) -> Item<V> {
let (distance, method) = (*distance.element(), *method.element());
V::map_vector_items(content, |content| {
let mut content = content;
match method {
WeldMethod::All => {
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
edit_item_geometry(&mut content, |vector, paths| vector.weld_all(paths, transform, distance));
}
WeldMethod::Connected => edit_item_geometry(&mut content, |vector, paths| vector.weld_connected(paths, distance)),
WeldMethod::FlowEnds => {
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
edit_item_geometry(&mut content, |vector, paths| vector.weld_flow_ends(paths, transform, distance));
}
}
content
})
}
/// Separates path flows or segments where they meet, giving each its own copies of the points they share.
#[node_macro::node(category("Vector: Path"), icon("NodeUnweld"), path(core_types::vector))]
fn unweld<V: MapVectorItems + Send + Sync + 'static>(
_: impl Ctx,
/// The vector with path flows to separate.
#[implementations(Graphic, Vector)]
content: Item<V>,
/// Which points are split: every anchor so each segment stands alone, every point path flows share, or only those where a path flow ends.
method: Item<UnweldMethod>,
) -> Item<V> {
let method = *method.element();
V::map_vector_items(content, |content| {
let mut content = content;
edit_item_geometry(&mut content, |vector, paths| vector.unweld(paths, method));
content
})
}
/// Wraps the points and paths of the vector content in a closed path in the shape of a rubber band stretched around everything. A curvature above zero may be given to obtain the concave hull, letting the (closed, open, or mesh-like) path or paths press into indents of the content where a ball with that curvature would be able to reach.
#[node_macro::node(category("Vector: Point"), icon("NodeConvexHull"), path(core_types::vector), footprint_invariant)]
fn convex_hull<V: MapVectorItems + Send>(
_: impl Ctx,
/// The vector content to envelop in the hull, which may be points, paths, or both.
#[implementations(Graphic, Vector)]
content: Item<V>,
/// How tightly the hull follows indents in the content. Its reciprocal is the radius of the rolling ball used to form the hull. Zero curvature gives the convex hull.
#[unit("/px")]
#[hard(0..)]
#[soft(..0.1)]
#[range]
#[display_decimal_places(4)]
curvature: Item<f64>,
) -> Item<V> {
let curvature = *curvature.element();
V::map_vector_items(content, |content| {
let mut content = content;
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
let paths = shared_paths_from_item_attributes(&content);
let vector = content.element();
let segments: Vec<PathSeg> = vector.stroke_bezpath_iter(&paths).flat_map(|bezpath| bezpath.segments().collect::<Vec<_>>()).collect();
// Anchor points not connected to any segment still participate in the hull
let connectivity = vector.connectivity(&paths);
let loose_points: Vec<kurbo::Point> = (vector.positions().enumerate())
.filter(|&(index, _)| connectivity.spokes(index as u32) == 0 && !connectivity.is_handle(index as u32))
.map(|(_, position)| dvec2_to_point(position))
.collect();
let hull = concave_hull_in_transformed_space(&segments, &loose_points, curvature, transform);
let (hull, hull_paths) = Vector::from_bezpath_welded(&hull);
*content.element_mut() = hull;
content.set_paths(hull_paths);
content
})
}
/// The concave hull of geometry in an item's local space, with the ball sized in the space the item's transform places it in.
fn concave_hull_in_transformed_space(segments: &[PathSeg], loose_points: &[kurbo::Point], curvature: f64, transform: DAffine2) -> BezPath {
let (x_axis, y_axis) = (transform.matrix2.x_axis, transform.matrix2.y_axis);
let scale_squared = x_axis.length_squared().max(y_axis.length_squared());
let tolerance = scale_squared * 1e-9;
// Convex hulls are unaffected by any transform and a similarity only resizes the ball, so these stay in local space to
// avoid round-trip error (as does a transform too squashed to invert)
let uniform = x_axis.dot(y_axis).abs() <= tolerance && (x_axis.length_squared() - y_axis.length_squared()).abs() <= tolerance;
let invertible = transform.matrix2.determinant().abs() > tolerance;
if curvature <= 0. || uniform || !invertible {
return concave_hull_of_geometry(segments, loose_points, curvature * scale_squared.sqrt());
}
// Otherwise the ball would be an ellipse in local space, so the hull is found where the ball is round and brought back
let affine = Affine::new(transform.to_cols_array());
let segments: Vec<PathSeg> = segments.iter().map(|&segment| affine * segment).collect();
let loose_points: Vec<kurbo::Point> = loose_points.iter().map(|&point| affine * point).collect();
let mut hull = concave_hull_of_geometry(&segments, &loose_points, curvature);
hull.apply_affine(affine.inverse());
hull
}
pub mod extrude_algorithms {
use super::{next_working_point_id, next_working_segment_id, push_working_point, push_working_segment};
use core_types::list::List;
use glam::DVec2;
use kurbo::{ParamCurve, ParamCurveDeriv};
use vector_types::vector::misc::BezierHandles;
use vector_types::vector::misc::{ExtrudeJoiningAlgorithm, handles_to_segment};
use vector_types::vector::{Path, WorkingVector};
/// Convert [`kurbo::CubicBez`] to [`vector_types::vector::misc::BezierHandles`].
fn cubic_to_handles(cubic_bez: kurbo::CubicBez) -> BezierHandles {
BezierHandles::Cubic {
handle_start: DVec2::new(cubic_bez.p1.x, cubic_bez.p1.y),
handle_end: DVec2::new(cubic_bez.p2.x, cubic_bez.p2.y),
}
}
/// Find the `t` values to split (where the tangent changes to be on the other side of the direction).
fn find_splits(cubic_segment: kurbo::CubicBez, direction: DVec2) -> impl Iterator<Item = f64> {
let derivative = cubic_segment.deriv();
let convert = |x: kurbo::Point| DVec2::new(x.x, x.y);
let derivative_points = [derivative.p0, derivative.p1, derivative.p2].map(convert);
let t_squared = derivative_points[0] - 2. * derivative_points[1] + derivative_points[2];
let t_scalar = -2. * derivative_points[0] + 2. * derivative_points[1];
let constant = derivative_points[0];
kurbo::common::solve_quadratic(constant.perp_dot(direction), t_scalar.perp_dot(direction), t_squared.perp_dot(direction))
.into_iter()
.filter(|&t| t > 1e-6 && t < 1. - 1e-6)
}
/// Split so segments no longer have tangents on both sides of the direction vector.
fn split(working: &mut WorkingVector, direction: DVec2) {
let segment_count = working.segment_ids.len();
let mut next_point = next_working_point_id(working);
let mut next_segment = next_working_segment_id(working);
// Each segment's pieces take its place in order, so the path it belongs to stays whole and still begins where it did
let mut pieces = WorkingVector::default();
for segment_index in 0..segment_count {
let start = working.point_positions[working.segment_start[segment_index]];
let end = working.point_positions[working.segment_end[segment_index]];
let segment = handles_to_segment(start, working.segment_handles[segment_index], end);
let mut start_index = working.segment_start[segment_index];
let pathseg = segment.to_cubic();
let mut start_t = 0.;
let mut remaining_handles = working.segment_handles[segment_index];
let mut begins_path = working.segment_begins_path.get(segment_index).copied().unwrap_or(false);
for split_t in find_splits(pathseg, direction) {
let [first, second] = [pathseg.subsegment(start_t..split_t), pathseg.subsegment(split_t..1.)];
let [first_handles, second_handles] = [first, second].map(cubic_to_handles);
let middle_point = next_point.next_id();
let start_segment = next_segment.next_id();
let middle_point_index = push_working_point(working, middle_point, DVec2::new(first.end().x, first.end().y));
push_working_segment(&mut pieces, start_segment, start_index, middle_point_index, first_handles);
pieces.segment_begins_path.push(std::mem::take(&mut begins_path));
start_t = split_t;
start_index = middle_point_index;
remaining_handles = second_handles;
}
// The last piece keeps the segment's own ID
push_working_segment(&mut pieces, working.segment_ids[segment_index], start_index, working.segment_end[segment_index], remaining_handles);
pieces.segment_begins_path.push(begins_path);
}
working.segment_ids = pieces.segment_ids;
working.segment_start = pieces.segment_start;
working.segment_end = pieces.segment_end;
working.segment_handles = pieces.segment_handles;
working.segment_begins_path = pieces.segment_begins_path;
}
/// Copy all segments with the offset of `direction`.
fn offset_copy_all_segments(working: &mut WorkingVector, direction: DVec2) {
let points_count = working.point_ids.len();
let mut next_point = next_working_point_id(working);
for index in 0..points_count {
let position = working.point_positions[index] + direction;
push_working_point(working, next_point.next_id(), position);
}
let segment_count = working.segment_ids.len();
let mut next_segment = next_working_segment_id(working);
for index in 0..segment_count {
let (start, end) = (working.segment_start[index] + points_count, working.segment_end[index] + points_count);
let handles = working.segment_handles[index].apply_transformation(|x| x + direction);
push_working_segment(working, next_segment.next_id(), start, end, handles);
}
// The copies begin paths where the originals do
working.segment_begins_path.resize(segment_count, false);
working.segment_begins_path.extend_from_within(..segment_count);
}
/// Join points from the original to the copied that are on opposite sides of the direction.
fn join_extrema_edges(working: &mut WorkingVector, direction: DVec2) {
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Found {
#[default]
None,
Positive,
Negative,
Both,
Invalid,
}
impl Found {
fn update(&mut self, value: f64) {
*self = match (*self, value > 0.) {
(Found::None, true) => Found::Positive,
(Found::None, false) => Found::Negative,
(Found::Positive, true) | (Found::Negative, false) => Found::Both,
_ => Found::Invalid,
};
}
}
let first_half_points = working.point_ids.len() / 2;
let mut points = vec![Found::None; first_half_points];
let first_half_segments = working.segment_ids.len() / 2;
for segment_id in 0..first_half_segments {
let index = [working.segment_start[segment_id], working.segment_end[segment_id]];
let position = index.map(|index| working.point_positions[index]);
if position[0].abs_diff_eq(position[1], 1e-6) {
continue; // Skip zero length segments
}
points[index[0]].update(direction.perp_dot(position[1] - position[0]));
points[index[1]].update(direction.perp_dot(position[0] - position[1]));
}
let mut next_segment = next_working_segment_id(working);
for (index, &point) in points.iter().enumerate().take(first_half_points) {
// Extrema are single connected points or points with both positive and negative values
if !matches!(point, Found::Both | Found::Positive | Found::Negative) {
continue;
}
push_working_segment(working, next_segment.next_id(), index, index + first_half_points, BezierHandles::Linear);
}
}
/// Join all points from the original to the copied.
fn join_all(working: &mut WorkingVector) {
let mut next_segment = next_working_segment_id(working);
let first_half = working.point_ids.len() / 2;
for index in 0..first_half {
push_working_segment(working, next_segment.next_id(), index, index + first_half, BezierHandles::Linear);
}
}
pub fn extrude(vector: &mut graphic_types::Vector, paths: &mut List<Path>, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) {
let mut working = WorkingVector::flatten(vector, paths);
split(&mut working, direction);
offset_copy_all_segments(&mut working, direction);
match joining_algorithm {
ExtrudeJoiningAlgorithm::Extrema => join_extrema_edges(&mut working, direction),
ExtrudeJoiningAlgorithm::All => join_all(&mut working),
ExtrudeJoiningAlgorithm::None => {}
}
working.reweave(vector, paths);
}
#[cfg(test)]
mod extrude_tests {
use glam::DVec2;
use kurbo::{ParamCurve, ParamCurveDeriv};
#[test]
fn split_cubic() {
let l1 = kurbo::CubicBez::new((0., 0.), (100., 0.), (100., 100.), (0., 100.));
assert_eq!(super::find_splits(l1, DVec2::Y).collect::<Vec<f64>>(), vec![0.5]);
assert!(super::find_splits(l1, DVec2::X).collect::<Vec<f64>>().is_empty());
let l2 = kurbo::CubicBez::new((0., 0.), (0., 0.), (100., 0.), (100., 0.));
assert!(super::find_splits(l2, DVec2::X).collect::<Vec<f64>>().is_empty());
let l3 = kurbo::PathSeg::Line(kurbo::Line::new((0., 0.), (100., 0.)));
assert!(super::find_splits(l3.to_cubic(), DVec2::X).collect::<Vec<f64>>().is_empty());
let l4 = kurbo::CubicBez::new((0., 0.), (100., -10.), (100., 110.), (0., 100.));
let splits = super::find_splits(l4, DVec2::X).map(|t| l4.deriv().eval(t)).collect::<Vec<_>>();
assert_eq!(splits.len(), 2);
assert!(splits.iter().all(|&deriv| deriv.y.abs() < 1e-8), "{splits:?}");
}
#[test]
fn split_vector() {
let curve = kurbo::PathSeg::Cubic(kurbo::CubicBez::new((0., 0.), (100., -10.), (100., 110.), (0., 100.)));
let (vector, paths) = graphic_types::Vector::from_bezpath(&kurbo::BezPath::from_path_segments([curve].into_iter()));
let mut working = super::WorkingVector::flatten(&vector, &paths);
super::split(&mut working, DVec2::X);
assert_eq!(working.segment_ids.len(), 3);
assert_eq!(working.point_ids.len(), 4);
}
// A split curve's pieces stay in its place, so the path holding it stays one path
#[test]
fn split_keeps_the_path_whole() {
let mut bezpath = kurbo::BezPath::new();
bezpath.move_to((0., 0.));
bezpath.curve_to((100., -10.), (100., 110.), (0., 100.));
bezpath.curve_to((0., 130.), (0., 170.), (0., 200.));
let (mut vector, mut paths) = graphic_types::Vector::from_bezpath(&bezpath);
assert_eq!(paths.len(), 1);
let mut working = super::WorkingVector::flatten(&vector, &paths);
super::split(&mut working, DVec2::X);
assert_eq!(working.segment_ids.len(), 4);
working.reweave(&mut vector, &mut paths);
assert_eq!(paths.len(), 1);
}
}
}
#[node_macro::node(category("Vector: Deform"), icon("NodeExtrude"), path(core_types::vector))]
fn extrude<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, direction: Item<DVec2>, joining_algorithm: Item<ExtrudeJoiningAlgorithm>) -> Item<V> {
V::map_vector_items(source, |source| {
let mut source = source;
let (direction, joining_algorithm) = (*direction.element(), *joining_algorithm.element());
edit_item_geometry(&mut source, |vector, paths| extrude_algorithms::extrude(vector, paths, direction, joining_algorithm));
source
})
}
#[derive(Debug, thiserror::Error)]
pub enum BoxWarpError {
#[error("The rectangle to warp onto needs at least 4 points")]
TooFewCorners,
}
#[node_macro::node(category("Vector: Deform"), icon("NodeBoxWarp"), path(core_types::vector), footprint_invariant)]
fn box_warp<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>, #[expose] rectangle: Item<Vector>) -> Result<Item<V>, BoxWarpError> {
let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM);
let target_paths = shared_paths_from_item_attributes(&rectangle);
let target = rectangle.into_element();
// Extract first 4 points from target shape to form the quadrilateral
// Apply the target's transform to get points in world space
let target_points: Vec<DVec2> = target.anchor_positions(&target_paths).iter().map(|&p| target_transform.transform_point2(p)).take(4).collect();
let dst_corners = match target_points[..] {
[] => return Ok(content),
[top_left, top_right, bottom_right, bottom_left] => [top_left, top_right, bottom_right, bottom_left],
_ => return Err(BoxWarpError::TooFewCorners),
};
Ok(V::map_vector_items(content, |content| {
let mut row = content;
{
let transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
let paths = shared_paths_from_item_attributes(&row);
let vector = std::mem::take(row.element_mut());
// Get the bounding box of the source vector geometry, or of its points where no paths are drawn
let source_bbox = vector
.bounding_box_with_transform(&paths, transform)
.or_else(|| match BoundingBox::bounding_box(&vector, transform, false) {
RenderBoundingBox::Rectangle(bounds) => Some(bounds),
_ => None,
})
.unwrap_or([DVec2::ZERO, DVec2::ONE]);
// Apply the warp
let mut result = vector.clone();
// Precompute source bounding box size for normalization
let source_size = source_bbox[1] - source_bbox[0];
// Transform points, handles included since they are pool points too
for position in result.0.iter_element_values_mut() {
// Get the point in world space
let world_pos = transform.transform_point2(*position);
// Normalize coordinates within the source bounding box
let t = ((world_pos - source_bbox[0]) / source_size).clamp(DVec2::ZERO, DVec2::ONE);
// Apply bilinear interpolation
*position = bilinear_interpolate(t, &dst_corners);
}
// Reset the transform since we've applied it directly to the points
*row.element_mut() = result;
row.set_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY);
graphic_types::graphic::rebase_stamped_transforms(row.attributes_mut(), transform);
}
row
}))
}
// Interpolate within a quadrilateral using normalized coordinates (0-1)
fn bilinear_interpolate(t: DVec2, quad: &[DVec2; 4]) -> DVec2 {
let tl = quad[0]; // Top-left
let tr = quad[1]; // Top-right
let br = quad[2]; // Bottom-right
let bl = quad[3]; // Bottom-left
// Bilinear interpolation
tl * (1. - t.x) * (1. - t.y) + tr * t.x * (1. - t.y) + br * t.x * t.y + bl * (1. - t.x) * t.y
}
#[node_macro::node(category("Transform"), icon("NodePackStrips"), path(graphene_core::vector), footprint_invariant)]
fn pack_strips<T: Send + Clone>(
_: impl Ctx,
#[implementations(
List<Graphic>,
List<Vector>,
List<Raster<CPU>>,
List<Raster<GPU>>,
)]
elements: List<T>,
#[default(0.)]
#[unit(" px")]
separation: Item<f64>,
#[default(1000.)]
#[unit(" px")]
strip_max_length: Item<f64>,
strip_direction: Item<RowsOrColumns>,
) -> List<T>
where
Graphic: From<List<T>>,
List<T>: BoundingBox,
{
let (separation, strip_max_length, strip_direction) = (separation.into_element(), strip_max_length.into_element(), strip_direction.into_element());
// Packs shapes using bounds with Best-Fit Decreasing Height (BFDH) algorithm:
// - Sort shapes by cross-axis size (tallest first for rows, widest first for columns)
// - For each shape, find the existing strip with minimum remaining space that fits
// - Create new strip only if no existing strip can accommodate the shape
struct Strip {
along_position: f64,
cross_position: f64,
cross_extent: f64,
}
// Prepare the items to be sorted
let mut items: Vec<(f64, f64, DVec2, Item<T>)> = elements
.into_iter()
.map(|row| {
// Single-item `List` to query its bounding box
let single = List::new_from_item(row.clone());
let (w, h, top_left) = match single.bounding_box(DAffine2::IDENTITY, false) {
RenderBoundingBox::Rectangle([min, max]) => {
let size = max - min;
(size.x.max(0.), size.y.max(0.), min)
}
_ => (0., 0., DVec2::ZERO),
};
let (along, cross) = match strip_direction {
RowsOrColumns::Rows => (w, h),
RowsOrColumns::Columns => (h, w),
};
(along, cross, top_left, row)
})
.collect();
// Sort by cross-axis size, largest first
items.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(Ordering::Equal));
let mut result = List::new();
let mut strips: Vec<Strip> = Vec::new();
// This looks n^2 but it is just n*k where k is the number of strips, which is generally much smaller than n
for (along, cross, top_left, mut row) in items {
if along <= 0. {
result.push(row);
continue;
}
// Find a good strip, minimum remaining space that can fit this item ideally
let mut best_strip_index = None;
let mut min_remaining_space = f64::INFINITY;
for (index, strip) in strips.iter().enumerate() {
let remaining_space = strip_max_length - strip.along_position;
if remaining_space >= along && remaining_space < min_remaining_space {
min_remaining_space = remaining_space;
best_strip_index = Some(index);
}
}
if let Some(strip_index) = best_strip_index {
// Place on existing strip
let strip = &mut strips[strip_index];
// Update strip cross extent if needed
if cross > strip.cross_extent {
strip.cross_extent = cross;
}
let target_position = match strip_direction {
RowsOrColumns::Rows => DVec2::new(strip.along_position, strip.cross_position),
RowsOrColumns::Columns => DVec2::new(strip.cross_position, strip.along_position),
};
let row_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
row.set_attribute(ATTR_TRANSFORM, DAffine2::from_translation(target_position - top_left) * row_transform);
strip.along_position += along + separation;
} else {
// Create new strip
let new_cross = strips.last().map_or(0., |last| last.cross_position + last.cross_extent + separation);
let target_position = match strip_direction {
RowsOrColumns::Rows => DVec2::new(0., new_cross),
RowsOrColumns::Columns => DVec2::new(new_cross, 0.),
};
let row_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
row.set_attribute(ATTR_TRANSFORM, DAffine2::from_translation(target_position - top_left) * row_transform);
strips.push(Strip {
along_position: along + separation,
cross_position: new_cross,
cross_extent: cross,
});
}
result.push(row);
}
result
}
/// Automatically constructs tangents (Bézier handles) for anchor points in a vector path.
#[node_macro::node(category("Vector: Path"), icon("NodeSmoothAnchors"), path(core_types::vector))]
fn smooth_anchors<V: MapVectorItems + Send>(
_: impl Ctx,
#[implementations(Graphic, Vector)] source: Item<V>,
/// The amount of spread for the auto-tangents, from 0 (sharp corner) to 1 (full spread).
#[default(0.5)]
#[range]
#[soft(0..1)]
spread: Item<f64>,
/// If active, existing nonzero handles won't be affected.
#[default(true)]
preserve_existing: Item<bool>,
) -> Item<V> {
V::map_vector_items(source, |source| {
let (spread, preserve_existing) = (*spread.element(), *preserve_existing.element());
let mut source = source;
// Tangents are spread where the item is drawn, or in its own space if the transform is too squashed to bring them back
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
let transform = if transform.matrix2.determinant() != 0. { transform } else { DAffine2::IDENTITY };
let inverse = transform.inverse();
edit_item_geometry(&mut source, |vector, paths| {
let point_count = vector.point_count();
let runs: Vec<_> = vector.stroke_manipulator_groups_and_anchor_indices(paths).collect();
// The anchors stay the pool's own points, keeping their welds and attributes, while the handles are made anew
let mut kept_index = vec![None; point_count];
for (index, former) in vector.keep_only_anchors(paths).into_iter().enumerate() {
kept_index[former] = Some(index as u32);
}
let mut next_id = SegmentId::ZERO;
let mut smooth_anchors = Vec::new();
for (manipulators_list, anchor_indices, is_closed) in runs {
let Some(anchors) = anchor_indices.iter().map(|&anchor| kept_index.get(anchor as usize).copied().flatten()).collect::<Option<Vec<u32>>>() else {
log::error!("Smooth Anchors skipped a contour through an anchor that was not kept");
continue;
};
// Not enough points for softening or handle removal
if manipulators_list.len() < 2 {
push_contour(vector, paths, &anchors, &manipulators_list, is_closed, &mut next_id);
continue;
}
let drawn_anchors: Vec<DVec2> = manipulators_list.iter().map(|manipulator| transform.transform_point2(manipulator.anchor)).collect();
let mut new_manipulators_list = Vec::with_capacity(manipulators_list.len());
for i in 0..manipulators_list.len() {
let current = &manipulators_list[i];
let is_endpoint = !is_closed && (i == 0 || i == manipulators_list.len() - 1);
if preserve_existing {
// Check if this point has handles that are meaningfully different from the anchor
let has_handles = (current.in_handle.is_some() && !current.in_handle.unwrap().abs_diff_eq(current.anchor, 1e-5))
|| (current.out_handle.is_some() && !current.out_handle.unwrap().abs_diff_eq(current.anchor, 1e-5));
// If the point already has handles, keep it as is
if has_handles {
new_manipulators_list.push(*current);
continue;
}
}
// If spread is 0, remove handles for this point, making it a sharp corner, unless the existing handles are preserved
if spread == 0. {
new_manipulators_list.push(if preserve_existing {
*current
} else {
ManipulatorGroup {
anchor: current.anchor,
in_handle: None,
out_handle: None,
id: current.id,
}
});
continue;
}
// Endpoints of open paths get zero-length cubic handles so adjacent segments remain cubic (not quadratic)
if is_endpoint {
new_manipulators_list.push(ManipulatorGroup {
anchor: current.anchor,
in_handle: Some(current.anchor),
out_handle: Some(current.anchor),
id: current.id,
});
continue;
}
// Get previous and next points for auto-tangent calculation
let prev_index = if i == 0 { manipulators_list.len() - 1 } else { i - 1 };
let next_index = if i == manipulators_list.len() - 1 { 0 } else { i + 1 };
let current_position = drawn_anchors[i];
let delta_prev = drawn_anchors[prev_index] - current_position;
let delta_next = drawn_anchors[next_index] - current_position;
// Calculate normalized directions and distances to adjacent points
let distance_prev = delta_prev.length();
let distance_next = delta_next.length();
// Check if we have valid directions (e.g., points are not coincident)
if distance_prev < 1e-5 || distance_next < 1e-5 {
// Fallback: keep the original manipulator group (which has no active handles here)
new_manipulators_list.push(*current);
continue;
}
let direction_prev = delta_prev / distance_prev;
let direction_next = delta_next / distance_next;
// Calculate handle direction as the bisector of the two normalized directions.
// This ensures the in and out handles are colinear (180° apart) through the anchor.
let mut handle_direction = (direction_prev - direction_next).try_normalize().unwrap_or_else(|| direction_prev.perp());
// Ensure consistent orientation of the handle direction.
// This makes the `+ handle_direction` for in_handle and `- handle_direction` for out_handle consistent.
if direction_prev.dot(handle_direction) < 0. {
handle_direction = -handle_direction;
}
// Calculate handle lengths: 1/3 of distance to adjacent points, scaled by spread
let in_length = distance_prev / 3. * spread;
let out_length = distance_next / 3. * spread;
// Create new manipulator group with calculated auto-tangents
new_manipulators_list.push(ManipulatorGroup {
anchor: current.anchor,
in_handle: Some(inverse.transform_point2(current_position + handle_direction * in_length)),
out_handle: Some(inverse.transform_point2(current_position - handle_direction * out_length)),
id: current.id,
});
smooth_anchors.push(anchors[i]);
}
push_contour(vector, paths, &anchors, &new_manipulators_list, is_closed, &mut next_id);
}
vector.set_smooth_at_indices(paths, smooth_anchors, true);
});
source
})
}
/// Appends a contour running through the given pool anchors, each span a cubic, quadratic, or line by which of its facing handles exist.
/// The handles become new pool points, and spans of one curve type in a row share a path.
fn push_contour(vector: &mut Vector, paths: &mut List<Path>, anchors: &[u32], manipulators_list: &[ManipulatorGroup], closed: bool, next_id: &mut SegmentId) {
let span_count = if closed { anchors.len() } else { anchors.len().saturating_sub(1) };
let mut runs: Vec<(CurveType, Vec<u32>, Vec<SegmentId>)> = Vec::new();
for i in 0..span_count {
let next = (i + 1) % anchors.len();
let (curve_type, handles) = match (manipulators_list[i].out_handle, manipulators_list[next].in_handle) {
(Some(handle_start), Some(handle_end)) => (CurveType::Cubic, vec![handle_start, handle_end]),
(None, None) => (CurveType::Linear, Vec::new()),
(Some(handle), None) | (None, Some(handle)) => (CurveType::Quadratic, vec![handle]),
};
// A change of curve type carries the contour on in a new path from the anchor the previous one ended at
if runs.last().is_none_or(|(current, ..)| *current != curve_type) {
runs.push((curve_type, vec![anchors[i]], Vec::new()));
}
let Some((_, references, ids)) = runs.last_mut() else { continue };
for handle in handles {
references.push(vector.point_count() as u32);
vector.0.push(Item::new_from_element(handle).with_attribute(ATTR_ID, PointId::UNNAMED));
}
references.push(anchors[next]);
ids.push(next_id.next_id());
}
push_paths(paths, runs);
}
#[node_macro::node(category("Vector: Geometry"), icon("NodeBoundingBox"), path(core_types::vector), footprint_invariant)]
fn bounding_box<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>) -> Item<V> {
V::map_vector_items(content, |content| {
let mut content = content;
let paths = shared_paths_from_item_attributes(&content);
let (result, result_paths) = content
.element()
.bounding_box_rect(&paths)
.map(|bbox| Vector::from_bezpath(&bbox.to_path(DEFAULT_ACCURACY)))
.unwrap_or_default();
*content.element_mut() = result;
content.set_paths(result_paths);
content
})
}
#[node_macro::node(category("Vector: Measure"), icon("NodeDimensions"), path(core_types::vector), footprint_invariant)]
fn dimensions(_: impl Ctx, content: Item<Vector>) -> Item<DVec2> {
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
let dimensions = content
.element()
.bounding_box_with_transform(paths, content.attribute_cloned_or_default(ATTR_TRANSFORM))
.map(|[top_left, bottom_right]| bottom_right - top_left)
.unwrap_or_default();
Item::new_from_element(dimensions)
}
/// Type-asserts a value to be vector data.
#[node_macro::node(category("Data: Type Assertion"), icon("NodeAsVector"), path(core_types::vector))]
fn as_vector(_: impl Ctx, value: Item<Vector>) -> Item<Vector> {
value
}
/// Creates vector points at the given positions, as a point cloud with nothing connecting them. **Points to Polyline** can join them into a path.
#[node_macro::node(category("Vector: Point"), icon("NodePointsToVector"), name("Points to Vector"), path(core_types::vector), footprint_invariant)]
fn points_to_vector(
_: impl Ctx,
/// The positions to place the points at, in order.
points: List<DVec2>,
) -> Item<Vector> {
let mut vector = Vector::default();
let mut next_point = PointId::ZERO;
for &position in points.iter_element_values() {
vector.0.push(Item::new_from_element(position).with_attribute(ATTR_ID, next_point.next_id()));
}
Item::new_from_element(vector).with_paths(List::<Path>::new())
}
/// Lists the positions of the anchor points in the vector content, as placed by its transform. Wiring this into the **Translation** of a **Transform** node places a copy of its content at each point.
///
/// Each point keeps its attributes, so **Read Attribute** can read them alongside the positions.
#[node_macro::node(category("Vector: Point"), icon("NodeVectorToPoints"), name("Vector to Points"), path(core_types::vector))]
fn vector_to_points(
_: impl Ctx,
/// The vector content with anchor points to list the positions of.
content: Item<Vector>,
) -> List<DVec2> {
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
let paths = shared_paths_from_item_attributes(&content);
let vector = content.element();
vector.anchor_indices(&paths).into_iter().filter_map(|index| placed_point(vector, index, transform)).collect()
}
/// Lists the positions of the open ends in the vector content, where a path stops without meeting another, like the tips of a tree's branches.
///
/// Each point keeps its attributes, so **Read Attribute** can read them alongside the positions.
#[node_macro::node(category("Vector: Point"), icon("NodeOpenEnds"), path(core_types::vector))]
fn open_ends(
_: impl Ctx,
/// The vector content with paths to find the open ends of.
content: Item<Vector>,
) -> List<DVec2> {
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
let paths = shared_paths_from_item_attributes(&content);
let vector = content.element();
// An open end is the anchor of exactly one segment, unlike a point along a path or a junction
let connectivity = vector.connectivity(&paths);
(0..vector.point_count())
.filter(|&index| connectivity.spokes(index as u32) == 1)
.filter_map(|index| placed_point(vector, index, transform))
.collect()
}
/// The pool point at `index` with its attributes, placed by the transform.
fn placed_point(vector: &Vector, index: usize, transform: DAffine2) -> Option<Item<DVec2>> {
let (position, attributes) = vector.0.clone_item(index)?.into_parts();
Some(Item::from_parts(transform.transform_point2(position), attributes))
}
/// Creates a polyline from a series of vector points, replacing any existing segments that may already exist.
#[node_macro::node(category("Vector: Path"), icon("NodePointsToPolyline"), name("Points to Polyline"), path(core_types::vector))]
fn points_to_polyline<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] points: Item<V>, #[default(true)] closed: Item<bool>) -> Item<V> {
let closed = *closed.element();
V::map_vector_items(points, |points| {
let mut points = points;
edit_item_geometry(&mut points, |vector, paths| {
vector.keep_only_anchors(paths);
let points_count = vector.point_count();
if points_count < 2 {
return;
}
// A pair has nowhere to close back to, so its two anchors draw one segment either way
let closing = closed && points_count != 2;
let mut next_id = SegmentId::ZERO;
push_path(
paths,
CurveType::Linear,
(0..points_count as u32).chain(closing.then_some(0)),
std::iter::repeat_with(|| next_id.next_id()),
);
});
points
})
}
/// Evens out the distances between points by applying Lloyd's relaxation, moving every interior point toward the center of its Voronoi cell.
#[node_macro::node(category("Vector: Point"), icon("NodeRelaxPoints"), path(core_types::vector))]
fn relax_points<V: MapVectorItems + Send>(
_: impl Ctx,
/// A vector path or point cloud to relax.
#[implementations(Graphic, Vector)]
source: Item<V>,
/// The number of relaxation steps to apply. A fractional value runs the whole steps and then blends partway toward one more step, so the amount of relaxation can be animated smoothly.
#[default(1.)]
#[hard(0..1000)]
iterations: Item<f64>,
) -> Result<Item<V>, PointDiagramError> {
V::try_map_vector_items(source, |source| {
let mut source = source;
let iterations = *iterations.element();
edit_item_geometry(&mut source, |vector, paths| {
let indices = vector.anchor_indices(paths);
let sites: Vec<DVec2> = indices.iter().filter_map(|&index| vector.position(index)).collect();
for (&index, new_position) in indices.iter().zip(crate::voronoi::relax_sites(&sites, iterations)?) {
if let Some(position) = vector.0.element_mut(index) {
*position = new_position;
}
}
Ok(())
})?;
Ok(source)
})
}
/// Builds a Voronoi diagram from the anchor points. Each point claims the region of space closest to it, and those regions tessellate the plane. Cells around the outside are clipped to the convex hull of the points so the diagram stays finite.
///
/// When Connect Cells is off, every cell becomes its own closed, fillable subpath. When on, the cells share their common points and segments, forming a single connected mesh.
#[node_macro::node(category("Vector: Point"), icon("NodeVoronoiCells"), path(core_types::vector), footprint_invariant)]
fn voronoi_cells<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, connect_cells: Item<bool>) -> Result<Item<V>, PointDiagramError> {
V::try_map_vector_items(source, |source| {
let mut source = source;
let connect_cells = *connect_cells.element();
edit_item_geometry(&mut source, |vector, paths| {
let sites = vector.anchor_positions(paths);
let cells = crate::voronoi::voronoi_cells(&sites)?;
if !cells.is_empty() {
replace_with_polygons(vector, paths, cells, connect_cells);
}
Ok(())
})?;
Ok(source)
})
}
/// Builds a Delaunay triangulation connecting the anchor points. It is the geometric dual of the **Voronoi** node: a mesh of triangles in which no point lies inside any triangle's circumscribed circle.
///
/// When Connect Cells is off, every triangle becomes its own closed, fillable subpath. When on, the triangles share their common points and segments, forming a single connected mesh.
#[node_macro::node(category("Vector: Point"), icon("NodeTriangulate"), path(core_types::vector), footprint_invariant)]
fn triangulate<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, connect_cells: Item<bool>) -> Result<Item<V>, PointDiagramError> {
V::try_map_vector_items(source, |source| {
let mut source = source;
let connect_cells = *connect_cells.element();
edit_item_geometry(&mut source, |vector, paths| {
let sites = vector.anchor_positions(paths);
let triangles = crate::voronoi::delaunay_triangles(&sites)?;
if !triangles.is_empty() {
// `delaunator` emits triangle vertices clockwise; reverse to `[a, c, b]` so triangles wind counter-clockwise to
// match the Voronoi cells and the rest of the framework's fill winding.
let polygons = triangles.iter().map(|&[a, b, c]| vec![sites[a], sites[c], sites[b]]).collect();
replace_with_polygons(vector, paths, polygons, connect_cells);
}
Ok(())
})?;
Ok(source)
})
}
/// Replaces a vector's geometry (points and segments) with the given closed polygons, preserving its style.
///
/// Without `connect_cells`, each polygon becomes its own closed subpath.
/// With it, coincident vertices are welded and each shared edge is emitted once, producing a connected mesh.
pub(crate) fn replace_with_polygons(vector: &mut Vector, paths: &mut List<Path>, polygons: Vec<Vec<DVec2>>, connect_cells: bool) {
let mut working = WorkingVector::default();
let mut next_point = PointId::ZERO;
let mut next_segment = SegmentId::ZERO;
if !connect_cells {
for polygon in &polygons {
if polygon.len() < 3 {
continue;
}
let base = working.point_ids.len();
for &position in polygon {
push_working_point(&mut working, next_point.next_id(), position);
}
let count = polygon.len();
for i in 0..count {
push_working_segment(&mut working, next_segment.next_id(), base + i, base + (i + 1) % count, BezierHandles::Linear);
}
}
} else {
// Weld vertices that fall in the same quantization cell so adjacent polygons share points,
// and emit each undirected edge only once so adjacent polygons share segments.
let tolerance = mesh_weld_tolerance(&polygons);
let mut vertex_lookup: HashMap<(i64, i64), usize> = HashMap::new();
let mut seen_edges: HashSet<(usize, usize)> = HashSet::new();
for polygon in &polygons {
if polygon.len() < 2 {
continue;
}
let indices: Vec<usize> = polygon
.iter()
.map(|&position| {
let key = ((position.x / tolerance).round() as i64, (position.y / tolerance).round() as i64);
match vertex_lookup.get(&key) {
Some(&index) => index,
None => {
let index = push_working_point(&mut working, next_point.next_id(), position);
vertex_lookup.insert(key, index);
index
}
}
})
.collect();
let count = indices.len();
for i in 0..count {
let start = indices[i];
let end = indices[(i + 1) % count];
if start == end {
continue;
}
// Emit shared walls in index-canonical direction: a cycle can't be monotone in point index,
// so no cell's boundary can wind coherently and read as deliberate negative space
let edge = if start < end { (start, end) } else { (end, start) };
if seen_edges.insert(edge) {
push_working_segment(&mut working, next_segment.next_id(), edge.0, edge.1, BezierHandles::Linear);
}
}
}
}
working.reweave(vector, paths);
}
/// The distance below which two mesh vertices are welded into one, scaled to the diagram's size so it tracks coordinate magnitude.
fn mesh_weld_tolerance(polygons: &[Vec<DVec2>]) -> f64 {
let mut min = DVec2::splat(f64::MAX);
let mut max = DVec2::splat(f64::MIN);
for polygon in polygons {
for &position in polygon {
min = min.min(position);
max = max.max(position);
}
}
let diagonal = (max - min).length();
// Floor the tolerance so an extremely tiny diagram can't underflow `diagonal * 1e-6` to zero, which would divide by
// zero when quantizing vertices and weld everything into a single point.
if diagonal.is_finite() && diagonal > 0. { (diagonal * 1e-6).max(1e-12) } else { 1e-6 }
}
#[node_macro::node(category("Vector: Path"), icon("NodeOffsetPath"), path(core_types::vector), inspector("offset_path_inspector"))]
fn offset_path<V: MapVectorItems + Send>(
_: impl Ctx,
#[implementations(Graphic, Vector)] content: Item<V>,
distance: Item<f64>,
join: Item<StrokeJoin>,
#[hard(0..)]
#[default(4.)]
miter_limit: Item<f64>,
) -> Result<Item<V>, OffsetPathError> {
V::try_map_vector_items(content, |content| {
let mut content = content;
let (distance, join, miter_limit) = (*distance.element(), *join.element(), *miter_limit.element());
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
if !transform_attribute.matrix2.determinant().is_normal() {
return Ok(content);
}
let transform = Affine::new(transform_attribute.to_cols_array());
let source_paths = shared_paths_from_item_attributes(&content);
let vector = std::mem::take(content.element_mut());
let bezpaths = vector.stroke_bezpath_iter(&source_paths).collect::<Vec<_>>();
let mut offset_bezpaths = Vec::with_capacity(bezpaths.len());
// Perform operation on all subpaths in this shape.
for mut bezpath in bezpaths {
bezpath.apply_affine(transform);
// Taking the existing stroke data and passing it to Kurbo to generate new paths.
let mut bezpath_out = offset_bezpath(
&bezpath,
-distance,
match join {
StrokeJoin::Miter => kurbo::Join::Miter,
StrokeJoin::Bevel => kurbo::Join::Bevel,
StrokeJoin::Round => kurbo::Join::Round,
},
Some(miter_limit),
)?;
bezpath_out.apply_affine(transform.inverse());
// One closed subpath, open path.
offset_bezpaths.push(bezpath_out);
}
let (mut result, mut result_paths) = (Vector::default(), List::new());
result.append_bezpaths(&mut result_paths, &offset_bezpaths);
*content.element_mut() = result;
content.set_paths(result_paths);
Ok(content)
})
}
/// Element-level dispatch for the Solidify Stroke node, which changes how many vector items its content holds.
/// Implementors rebuild their vector content in place so the structure it arrived in survives.
trait SolidifyStroke: Sized {
fn solidify_strokes(content: Item<Self>) -> List<Self>;
}
impl SolidifyStroke for Vector {
fn solidify_strokes(content: Item<Vector>) -> List<Vector> {
solidify_stroke_list_with_snapshot(List::new_from_item(content))
}
}
impl SolidifyStroke for Graphic {
fn solidify_strokes(content: Item<Graphic>) -> List<Graphic> {
fn solidify_nested(graphic: &mut Graphic) {
match graphic {
Graphic::VectorList(list) if !list.is_empty() => *list = solidify_stroke_list_with_snapshot(std::mem::take(list)),
Graphic::GraphicList(list) => list.iter_element_values_mut().for_each(solidify_nested),
// Solidifying can split one path into separate fill and stroke items, so the leaf becomes a list
Graphic::Vector(item) => {
let solidified = solidify_stroke_list_with_snapshot(List::new_from_item(std::mem::take(&mut **item)));
*graphic = Graphic::VectorList(solidified);
}
Graphic::Graphic(item) => solidify_nested(item.element_mut()),
_ => {}
}
}
let mut content = content;
solidify_nested(content.element_mut());
List::new_from_item(content)
}
}
/// Solidifies the list, stashing the original as a merged-layers snapshot since outlining discards the editable path.
fn solidify_stroke_list_with_snapshot(source: List<Vector>) -> List<Vector> {
let mut output = solidify_stroke_list(source.clone());
if !output.is_empty() {
// Pre-compensate by item 0's inverse so the renderer's `upstream_footprint *= item_0_transform`
// recursion cancels out and leaves the snapshot's original transforms intact
let mut snapshot = source.into_graphic_list();
let item_0_transform: DAffine2 = output.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
if item_0_transform.matrix2.determinant().abs() > f64::EPSILON {
let inverse = item_0_transform.inverse();
for transform in snapshot.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
*transform = inverse * *transform;
}
}
output.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, snapshot);
}
output
}
/// Replaces each item's stroke with filled outline geometry, emitting a separate fill item beside it when the
/// original carried a fill. Grows the item count by up to 2x. An item without a stroke to outline passes through as it was.
fn solidify_stroke_list(content: List<Vector>) -> List<Vector> {
// A fill exists when its coverage carries paint that draws something
let has_fills: Vec<bool> = (0..content.len())
.map(|index| {
content
.attribute::<Appearance>(ATTR_APPEARANCE, index)
.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill))
})
.collect();
content
.into_iter()
.zip(has_fills)
.flat_map(|(row, has_fill)| {
let (vector, attributes) = row.into_parts();
let appearance = attributes.get::<Appearance>(ATTR_APPEARANCE).cloned().unwrap_or_default();
let Some(stroke) = appearance.first_stroke_params().filter(|stroke| stroke.weight != 0.) else {
return vec![Item::from_parts(vector, attributes)];
};
// List order is paint order: a stroke coverage before the first fill coverage paints below it
let stroke_below = appearance
.first_index_of(Cover::Stroke)
.zip(appearance.first_index_of(Cover::Fill))
.is_some_and(|(stroke_index, fill_index)| stroke_index < fill_index);
let paths = attributes.get::<List<Path>>(ATTR_PATHS).unwrap_or_else(|| no_paths());
let bezpaths = vector.stroke_bezpath_iter(paths).collect::<Vec<_>>();
let (mut solidified_stroke, mut solidified_stroke_paths) = (Vector::default(), List::new());
// Taking the existing stroke data and passing it to kurbo::stroke to generate new fill paths.
let join = match stroke.join {
StrokeJoin::Miter => kurbo::Join::Miter,
StrokeJoin::Bevel => kurbo::Join::Bevel,
StrokeJoin::Round => kurbo::Join::Round,
};
let cap = match stroke.cap {
StrokeCap::Butt => kurbo::Cap::Butt,
StrokeCap::Round => kurbo::Cap::Round,
StrokeCap::Square => kurbo::Cap::Square,
};
let dash_offset = stroke.dash_offset;
let dash_pattern = stroke.dash_lengths.clone();
let miter_limit = stroke.join_miter_limit;
let stroke_style = kurbo::Stroke::new(stroke.weight)
.with_caps(cap)
.with_join(join)
.with_dashes(dash_offset, dash_pattern)
.with_miter_limit(miter_limit);
// Pick `stable_dash_order` per subpath: closed subpaths use the default merge so the seam-spanning dash matches Vello/SVG renderers, while open subpaths use stable order so dashes are emitted in path-length sequence
let stroke_options_default = kurbo::StrokeOpts::default();
let stroke_options_stable = kurbo::StrokeOpts::default().stable_dash_order(true);
// 0.25 is balanced between performance and accuracy of the curve.
const STROKE_TOLERANCE: f64 = 0.25;
let solidified_bezpaths = bezpaths.into_iter().map(|mut path| {
path.apply_affine(Affine::new(stroke.transform.to_cols_array()));
let is_closed = matches!(path.elements().last(), Some(kurbo::PathEl::ClosePath));
let stroke_options = if is_closed { &stroke_options_default } else { &stroke_options_stable };
let mut solidified = kurbo::stroke(path, &stroke_style, stroke_options, STROKE_TOLERANCE);
if stroke.transform.matrix2.determinant() != 0. {
solidified.apply_affine(Affine::new(stroke.transform.inverse().to_cols_array()));
}
solidified
});
solidified_stroke.append_bezpaths(&mut solidified_stroke_paths, solidified_bezpaths);
// If the original vector has a fill, preserve it as a separate item with the stroke coverages dropped
let fill_row = has_fill.then(|| {
let mut fill_attributes = attributes.clone();
if let Some(mut appearance) = fill_attributes.remove::<Appearance>(ATTR_APPEARANCE) {
appearance.retain_cover(Cover::Fill);
fill_attributes.insert(ATTR_APPEARANCE, appearance);
}
Item::from_parts(vector, fill_attributes)
});
// The outlined stroke geometry becomes a fill painted with the original stroke's paint
let mut stroke_attributes = attributes;
if stroke_attributes.remove::<Appearance>(ATTR_APPEARANCE).is_some() {
let stroke_paint = appearance.first_index_of(Cover::Stroke).and_then(|index| appearance.paint_at(index).cloned()).unwrap_or_default();
stroke_attributes.insert(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), stroke_paint));
}
stroke_attributes.set_paths(solidified_stroke_paths);
let stroke_row = Item::from_parts(solidified_stroke, stroke_attributes);
// The first item in the `List` is rendered below the second
match stroke_below {
false => fill_row.into_iter().chain(std::iter::once(stroke_row)).collect::<Vec<_>>(),
true => std::iter::once(stroke_row).chain(fill_row).collect::<Vec<_>>(),
}
})
.collect()
}
#[node_macro::node(category("Vector: Path"), icon("NodeSolidifyStroke"), path(core_types::vector))]
fn solidify_stroke<V: SolidifyStroke + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>) -> List<V> {
// TODO: Make this node support stroke align, which it currently ignores
V::solidify_strokes(content)
}
/// Splits the vector into separate items, one per path.
#[node_macro::node(category("Vector: Path"), icon("NodeSeparatePaths"), path(core_types::vector))]
fn separate_paths<V: ExpandVectorItems + Send>(
_: impl Ctx,
/// The vector with paths to separate.
#[implementations(Graphic, Vector)]
content: Item<V>,
) -> List<V> {
V::expand_vector_items(content, |content| {
let content_paths = shared_paths_from_item_attributes(&content);
let bezpaths = content.element().stroke_bezpath_iter(&content_paths).collect::<Vec<_>>();
// Pass the original element through unchanged when it has no paths, so its attributes
// (such as the layer transform) survive downstream rather than being dropped along with the empty list.
if bezpaths.is_empty() {
return List::new_from_item(content);
}
let (_, attributes) = content.into_parts();
bezpaths
.into_iter()
.map(|bezpath| {
let (vector, paths) = Vector::from_bezpath(&bezpath);
let mut attributes = attributes.clone();
attributes.set_paths(paths);
Item::from_parts(vector, attributes)
})
.collect()
})
}
/// Determines if the subpath at the given index is closed, meaning its ends are connected together forming a loop.
#[node_macro::node(name("Path is Closed"), category("Vector: Measure"), icon("NodePathIsClosed"), path(core_types::vector))]
fn path_is_closed(
_: impl Ctx,
/// The vector content whose subpaths are inspected.
content: Item<Vector>,
/// The index of the subpath to check, counting across the element's subpaths.
#[hard(0..)]
index: Item<i64>,
) -> Item<bool> {
let index = usize::try_from(index.into_element()).unwrap_or(usize::MAX);
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
let closed = content.element().stroke_manipulator_groups(paths).map(|(_, closed)| closed).nth(index).unwrap_or(false);
Item::new_from_element(closed)
}
#[node_macro::node(category("Vector: Point"), icon("NodeMapPoints"), path(graphene_core::vector))]
fn map_points<V: MapVectorItems + Send>(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
#[implementations(Graphic, Vector)] content: Item<V>,
mapped: impl Node<Context<'static>, Output = Item<DVec2>>,
) -> Result<Item<V>, Interrupt> {
let mut content = content;
// Handles keep their own positions, so the mapping walks anchors alone, indexed in anchor order
for (vector, paths) in V::vector_elements_mut(&mut content) {
for (index, pool_index) in vector.anchor_indices(&paths).into_iter().enumerate() {
let Some(position) = vector.position(pool_index) else { continue };
let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(position);
let mapped_position = mapped.eval(&owned_ctx.into_context())?.into_element();
if let Some(slot) = vector.0.element_mut(pool_index) {
*slot = mapped_position;
}
}
}
Ok(content)
}
/// Combines every vector path across the input into a single compound path.
#[node_macro::node(category("Vector: Path"), icon("NodeCombinePaths"), path(graphene_core::vector))]
pub fn combine_paths(_: impl Ctx, content: List<Graphic>) -> Item<Vector> {
let graphic_list = content.clone();
let flattened = content.into_flattened_list::<Vector>();
let mut primary_source = None;
let mut output = Vector::default();
let mut output_paths = List::new();
let mut taken_ids = IdCollisionSet::default();
// Concatenate every vector element's subpaths into the single output compound path
for index in 0..flattened.len() {
let Some(element) = flattened.element(index) else { continue };
let element_paths = paths_from_list_row_attributes(&flattened, index).cloned().unwrap_or_default();
let layer_path: List<NodeId> = flattened.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, index).0;
let node_id = layer_path.iter_element_values().next_back().map(|node_id| node_id.0).unwrap_or_default();
let mut hasher = DefaultHasher::new();
// Hash as u32 to avoid platform differences
(index as u32, node_id).hash(&mut hasher);
let collision_hash_seed = hasher.finish();
let source_transform = flattened.attribute_cloned_or_default(ATTR_TRANSFORM, index);
output.concat(&mut output_paths, element, &element_paths, source_transform, collision_hash_seed, &mut taken_ids);
primary_source = Some((index, source_transform));
}
let mut attributes = ItemAttributeValues::new();
if let Some((primary, source_transform)) = primary_source {
let source_attributes = flattened.clone_item_attributes(primary);
attributes.insert_cloned_from(&source_attributes, ATTR_APPEARANCE);
// Adopt the last input item's layer (if any) so the editor can also bucket clicks under a contributing child layer
attributes.insert_cloned_from(&source_attributes, ATTR_EDITOR_LAYER_PATH);
bake_transform_into_attributes(&mut attributes, source_transform);
}
attributes.set_paths(output_paths);
// Preserve a reference to the original upstream `List<Graphic>` so the renderer can recurse into it
// when collecting metadata, exposing the original child layers' click targets to editor tools.
// This is the same mechanism Boolean Operation uses to keep its inputs editable after the merge.
attributes.insert(ATTR_EDITOR_MERGED_LAYERS, graphic_list);
Item::from_parts(output, attributes)
}
/// Convert vector geometry into a polyline composed of evenly spaced points.
#[node_macro::node(category("Vector: Path"), icon("NodeSamplePolyline"), path(core_types::vector), inspector("sample_polyline_inspector"), memoize)]
fn sample_polyline<V: MapVectorItems + Send>(
_: impl Ctx,
#[implementations(Graphic, Vector)] content: Item<V>,
spacing: Item<PointSpacingType>,
#[default(100.)]
#[hard(0..)]
#[unit(" px")]
separation: Item<f64>,
#[default(100)]
#[hard(2..)]
quantity: Item<i64>,
#[hard(0..)]
#[unit(" px")]
start_offset: Item<f64>,
#[hard(0..)]
#[unit(" px")]
stop_offset: Item<f64>,
adaptive_spacing: Item<bool>,
) -> Result<Item<V>, SampleCountError> {
V::try_map_vector_items(content, |content| {
let mut content = content;
let (spacing, separation, quantity) = (*spacing.element(), *separation.element(), *quantity.element());
let (start_offset, stop_offset, adaptive_spacing) = (*start_offset.element(), *stop_offset.element(), *adaptive_spacing.element());
let pathseg_perimeter = |segment: PathSeg| {
if is_linear(segment) {
Line::new(segment.start(), segment.end()).perimeter(DEFAULT_ACCURACY)
} else {
segment.perimeter(DEFAULT_ACCURACY)
}
};
let mut sample_bezpaths = Vec::new();
let content_paths = shared_paths_from_item_attributes(&content);
for local_bezpath in content.element().stroke_bezpath_iter(&content_paths).collect::<Vec<_>>() {
// Apply the transform to compute sample locations in world space (for correct distance-based spacing)
let mut world_bezpath = local_bezpath.clone();
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
world_bezpath.apply_affine(Affine::new(transform_attribute.to_cols_array()));
// A subpath with non-finite coordinates has no lengths to space the samples by, so it passes through
if !world_bezpath.is_finite() {
sample_bezpaths.push(local_bezpath);
continue;
}
// Per-segment perimeter lengths (transform-baked) for distance-based spacing
let segment_lengths: Vec<f64> = world_bezpath.segments().map(pathseg_perimeter).collect();
let amount = match spacing {
PointSpacingType::Separation => separation,
PointSpacingType::Quantity => quantity as f64,
};
// Compute sample locations using world-space distances, then evaluate positions on the untransformed bezpath.
// This avoids needing to invert the transform (which fails when the transform is singular, e.g. zero scale).
let Some((locations, was_closed)) = bezpath_algorithms::compute_sample_locations(&world_bezpath, spacing, amount, start_offset, stop_offset, adaptive_spacing, &segment_lengths)? else {
continue;
};
// Evaluate the sample locations on the untransformed bezpath and append the result
let mut sample_bezpath = BezPath::new();
for &(segment_index, t) in &locations {
let segment = local_bezpath.get_seg(segment_index + 1).unwrap();
let point = segment.eval(t);
if sample_bezpath.elements().is_empty() {
sample_bezpath.move_to(point);
} else {
sample_bezpath.line_to(point);
}
}
if was_closed {
sample_bezpath.close_path();
}
sample_bezpaths.push(sample_bezpath);
}
let (mut result, mut result_paths) = (Vector::default(), List::new());
result.append_bezpaths(&mut result_paths, &sample_bezpaths);
*content.element_mut() = result;
content.set_paths(result_paths);
Ok(content)
})
}
/// The finest tolerance worth honoring on a path. Finer ones make no visible difference but take unbounded time and memory to reach,
/// and float precision runs out sooner the farther the coordinates are from the origin.
fn tolerance_floor(bezpath: &BezPath) -> f64 {
let bounds = bezpath.bounding_box();
let magnitude = bounds.x0.abs().max(bounds.x1.abs()).max(bounds.y0.abs()).max(bounds.y1.abs());
(magnitude * 1e-12).max(1e-6)
}
/// Simplifies vector paths by reducing the number of curve segments while preserving the overall shape within the given tolerance.
#[node_macro::node(category("Vector: Path"), icon("NodeSimplify"), path(core_types::vector))]
fn simplify<V: MapVectorItems + Send>(
_: impl Ctx,
/// The vector paths to simplify.
#[implementations(Graphic, Vector)]
content: Item<V>,
/// The maximum distance the simplified path may deviate from the original.
#[unit(" px")]
#[hard(0..)]
#[default(5.)]
tolerance: Item<f64>,
) -> Item<V> {
let tolerance = *tolerance.element();
if tolerance <= 0. {
return content;
}
let options = SimplifyOptions::default();
V::map_vector_items(content, |mut item| {
let transform_attribute: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
if !transform_attribute.matrix2.determinant().is_normal() {
return item;
}
let transform = Affine::new(transform_attribute.to_cols_array());
let inverse_transform = transform.inverse();
let item_paths = shared_paths_from_item_attributes(&item);
let simplified_bezpaths = item.element().stroke_bezpath_iter(&item_paths).map(|bezpath| {
let mut document_bezpath = bezpath.clone();
document_bezpath.apply_affine(transform);
// Kurbo's curve fitting never converges on non-finite coordinates, and drops a subpath whose segments all have zero length
if !document_bezpath.is_finite() || document_bezpath.segments().all(|segment| segment.bounding_box().size() == kurbo::Size::ZERO) {
return bezpath;
}
let tolerance = tolerance.max(tolerance_floor(&document_bezpath));
let mut simplified = simplify_bezpath(document_bezpath, tolerance, &options);
simplified.apply_affine(inverse_transform);
simplified
});
let (mut result, mut result_paths) = (Vector::default(), List::new());
result.append_bezpaths(&mut result_paths, simplified_bezpaths);
*item.element_mut() = result;
item.set_paths(result_paths);
item
})
}
/// Decimates vector paths into polylines by sampling any curves into line segments, then removing points that don't significantly contribute to the shape using the Ramer-Douglas-Peucker algorithm.
#[node_macro::node(category("Vector: Path"), icon("NodeDecimate"), path(core_types::vector))]
fn decimate<V: MapVectorItems + Send>(
_: impl Ctx,
/// The vector paths to decimate.
#[implementations(Graphic, Vector)]
content: Item<V>,
/// The maximum distance a point can deviate from the simplified path before it is kept.
#[unit(" px")]
#[hard(0..)]
#[default(5.)]
tolerance: Item<f64>,
) -> Item<V> {
V::map_vector_items(content, |content| {
let mut content = content;
let tolerance = *tolerance.element();
// Tolerance of 0 means no simplification is possible, so return immediately
if tolerance <= 0. {
return content;
}
// Below this squared length, a line segment is treated as a degenerate point and the distance
// falls back to a simple point-to-point measurement to avoid division by near-zero.
const NEAR_ZERO_LENGTH_SQUARED: f64 = 1e-20;
fn perpendicular_distance(point: DVec2, line_start: DVec2, line_end: DVec2) -> f64 {
let line_vector = line_end - line_start;
let line_length_squared = line_vector.length_squared();
if line_length_squared < NEAR_ZERO_LENGTH_SQUARED {
return point.distance(line_start);
}
(point - line_start).perp_dot(line_vector).abs() / line_length_squared.sqrt()
}
fn rdp_simplify(points: &[DVec2], tolerance: f64) -> Vec<DVec2> {
if points.len() < 3 {
return points.to_vec();
}
let mut keep = vec![false; points.len()];
keep[0] = true;
keep[points.len() - 1] = true;
let mut stack = vec![(0, points.len() - 1)];
while let Some((start_index, end_index)) = stack.pop() {
let start = points[start_index];
let end = points[end_index];
let mut max_distance = 0.;
let mut max_index = 0;
for (i, &point) in points.iter().enumerate().take(end_index).skip(start_index + 1) {
let distance = perpendicular_distance(point, start, end);
if distance > max_distance {
max_distance = distance;
max_index = i;
}
}
if max_distance > tolerance {
keep[max_index] = true;
if max_index - start_index > 1 {
stack.push((start_index, max_index));
}
if end_index - max_index > 1 {
stack.push((max_index, end_index));
}
}
}
points.iter().enumerate().filter(|(i, _)| keep[*i]).map(|(_, p)| *p).collect()
}
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
if !transform_attribute.matrix2.determinant().is_normal() {
return content;
}
let transform = Affine::new(transform_attribute.to_cols_array());
let inverse_transform = transform.inverse();
let mut decimated_bezpaths = Vec::new();
let content_paths = shared_paths_from_item_attributes(&content);
for local_bezpath in content.element().stroke_bezpath_iter(&content_paths).collect::<Vec<_>>() {
let mut bezpath = local_bezpath.clone();
bezpath.apply_affine(transform);
// The distance to a non-finite point can't be measured, so such a subpath passes through
if !bezpath.is_finite() {
decimated_bezpaths.push(local_bezpath);
continue;
}
let is_closed = matches!(bezpath.elements().last(), Some(PathEl::ClosePath));
// Flatten the bezpath into line segments, then collect the points
let flatten_tolerance = (tolerance * 0.5).max(tolerance_floor(&bezpath));
let mut points = Vec::new();
kurbo::flatten(bezpath, flatten_tolerance, |el| match el {
PathEl::MoveTo(p) | PathEl::LineTo(p) => {
points.push(DVec2::new(p.x, p.y));
}
_ => {}
});
// For closed paths, the last point duplicates the first, so remove it
if is_closed && points.len() > 1 && points.last() == points.first() {
points.pop();
}
// Apply RDP simplification
let simplified = rdp_simplify(&points, tolerance);
if simplified.is_empty() {
continue;
}
// Reconstruct as a polyline
let mut new_bezpath = BezPath::new();
new_bezpath.move_to((simplified[0].x, simplified[0].y));
for &point in &simplified[1..] {
new_bezpath.line_to((point.x, point.y));
}
if is_closed {
new_bezpath.close_path();
}
new_bezpath.apply_affine(inverse_transform);
decimated_bezpaths.push(new_bezpath);
}
let (mut result, mut result_paths) = (Vector::default(), List::new());
result.append_bezpaths(&mut result_paths, &decimated_bezpaths);
*content.element_mut() = result;
content.set_paths(result_paths);
content
})
}
#[derive(Debug, thiserror::Error)]
pub enum ProgressionError {
#[error("Progression is not a number")]
NotANumber,
}
/// Cuts a path at a given progression from 0 to 1 along the path, creating two new subpaths from the original one (if the path is initially open) or one open subpath (if the path is initially closed).
///
/// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it.
#[node_macro::node(category("Vector: Path"), icon("NodeCutPath"), path(graphene_core::vector))]
fn cut_path<V: MapVectorItems + Send>(
_: impl Ctx,
/// The path to insert a cut into.
#[implementations(Graphic, Vector)]
content: Item<V>,
/// The factor from the start to the end of the path, 0–1 for one subpath, 1–2 for a second subpath, and so on.
#[progression]
progression: Item<f64>,
/// Swap the direction of the path.
reverse: Item<bool>,
/// Traverse the path using each segment's Bézier curve parameterization instead of the Euclidean distance. Faster to compute but doesn't respect actual distances.
parameterized_distance: Item<bool>,
) -> Result<Item<V>, ProgressionError> {
if progression.element().is_nan() {
return Err(ProgressionError::NotANumber);
}
Ok(V::map_vector_items(content, |content| {
let mut content = content;
let (progression, reverse, parameterized_distance) = (*progression.element(), *reverse.element(), *parameterized_distance.element());
let euclidean = !parameterized_distance;
let content_paths = shared_paths_from_item_attributes(&content);
let bezpaths = content.element().stroke_bezpath_iter(&content_paths).collect::<Vec<_>>();
let bezpath_count = bezpaths.len() as f64;
let t_value = progression.clamp(0., bezpath_count);
let t_value = if reverse { bezpath_count - t_value } else { t_value };
let index = if t_value >= bezpath_count { (bezpath_count - 1.) as usize } else { t_value as usize };
if let Some(bezpath) = bezpaths.get(index).cloned() {
let t = if t_value == bezpath_count { 1. } else { t_value.fract() };
let t = if euclidean { TValue::Euclidean(t) } else { TValue::Parametric(t) };
// Every other bezpath comes first, then the two halves of the one being split, or all of it where it cannot be
let halves = split_bezpath(&bezpath, t);
let split = match &halves {
Some((first, second)) => vec![first, second],
None => vec![&bezpath],
};
let others = bezpaths.iter().enumerate().filter(|&(i, _)| i != index).map(|(_, bezpath)| bezpath);
let (mut result_vector, mut result_paths) = (Vector::default(), List::new());
result_vector.append_bezpaths(&mut result_paths, others.chain(split));
*content.element_mut() = result_vector;
content.set_paths(result_paths);
}
content
}))
}
/// The position, tangent direction, and normal direction at a point along a path, split into separate node outputs.
#[derive(Debug, Clone, PartialEq, dyn_any::DynAny, node_macro::Destructure)]
pub struct PathEvaluation {
/// The position of the point on the path.
#[primary]
pub position: Item<DVec2>,
/// The unit vector pointing along the path in its direction of travel.
pub tangent: Item<DVec2>,
/// The unit vector perpendicular to the path, pointing to the left of its direction of travel as seen in the viewport. That is outward from clockwise closed paths.
pub normal: Item<DVec2>,
}
#[derive(Debug, thiserror::Error)]
pub enum EvaluatePathError {
#[error(transparent)]
Progression(#[from] ProgressionError),
#[error("The content has no path to evaluate")]
NoPath,
}
/// Determines the position, tangent direction, and normal direction at a point on the path, given by its progression from 0 to 1 along the path.
///
/// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it.
#[node_macro::node(category("Vector: Measure"), icon("NodeEvaluatePath"), path(graphene_core::vector))]
fn evaluate_path(
_: impl Ctx,
/// The path to traverse.
content: Item<Vector>,
/// The factor from the start to the end of the path, 0–1 for one subpath, 1–2 for a second subpath, and so on.
#[progression]
progression: Item<f64>,
/// Swap the direction of the path.
reverse: Item<bool>,
/// Traverse the path using each segment's Bézier curve parameterization instead of the Euclidean distance. Faster to compute but doesn't respect actual distances.
parameterized_distance: Item<bool>,
) -> Result<PathEvaluation, EvaluatePathError> {
let (progression, reverse, parameterized_distance) = (progression.into_element(), reverse.into_element(), parameterized_distance.into_element());
let euclidean = !parameterized_distance;
if progression.is_nan() {
return Err(ProgressionError::NotANumber.into());
}
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut bezpaths: Vec<_> = content.element().stroke_bezpath_iter(paths).map(|bezpath| (bezpath, transform)).collect();
let bezpath_count = bezpaths.len() as f64;
let progression = progression.clamp(0., bezpath_count);
let progression = if reverse { bezpath_count - progression } else { progression };
let index = if progression >= bezpath_count { (bezpath_count - 1.) as usize } else { progression as usize };
let Some((bezpath, transform)) = bezpaths.get_mut(index) else {
return Err(EvaluatePathError::NoPath);
};
let t = if progression == bezpath_count { 1. } else { progression.fract() };
let t_value = |t: f64| if euclidean { TValue::Euclidean(t) } else { TValue::Parametric(t) };
// Apply the transform once so both the position and tangent are computed on the transformed path
bezpath.apply_affine(Affine::new(transform.to_cols_array()));
let position = point_to_dvec2(evaluate_bezpath(bezpath, t_value(t), None));
let mut tangent = point_to_dvec2(tangent_on_bezpath(bezpath, t_value(t), None));
if tangent == DVec2::ZERO {
let t = t + if t > 0.5 { -0.001 } else { 0.001 };
tangent = point_to_dvec2(tangent_on_bezpath(bezpath, t_value(t), None));
}
let tangent = if reverse { -tangent } else { tangent }.normalize_or_zero();
// Rotating a quarter turn counterclockwise as seen in the viewport, where the Y axis points down, matches the 'Offset Points' normal
let normal = -tangent.perp();
Ok(PathEvaluation {
position: Item::new_from_element(position),
tangent: Item::new_from_element(tangent),
normal: Item::new_from_element(normal),
})
}
#[node_macro::node(category("Vector: Point"), icon("NodeScatterPoints"), path(core_types::vector), version(2), memoize)]
fn scatter_points<V: MapVectorItems + Send>(
_: impl Ctx,
#[implementations(Graphic, Vector)] content: Item<V>,
#[unit(" px")]
#[default(10.)]
#[range]
#[hard(0.01..)]
#[soft(1..100)]
separation: Item<f64>,
#[hard(0..)] seed: Item<i64>,
) -> Result<Item<V>, PoissonDiskError> {
// One sampler for every vector in the content holds them all together to its limits on work
let mut sampler = PoissonDiskSampler::default();
V::try_map_vector_items(content, |content| {
let mut content = content;
let (separation, seed) = (*separation.element(), *seed.element());
let content_paths = shared_paths_from_item_attributes(&content);
let bezpaths: Vec<_> = content.element().stroke_bezpath_iter(&content_paths).collect();
// Each point's ID comes from the dart that placed it, so a point keeps its ID while edits elsewhere in the shape leave it in place
let cloud = sampler
.points(&bezpaths, separation, seed as u64)?
.into_iter()
.map(|(point, hash)| Item::new_from_element(point).with_attribute(ATTR_ID, PointId::ZERO.generate_from_hash(hash)))
.collect();
// The scattered points replace the source shape entirely, leaving no paths
drop(content_paths);
edit_item_geometry(&mut content, |vector, paths| {
*vector = Vector(cloud);
*paths = List::new();
});
Ok(content)
})
}
#[node_macro::node(name("Spline"), category("Vector: Path"), icon("NodeSpline"), path(core_types::vector))]
fn spline<V: MapVectorItems + Send>(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item<V>) -> Item<V> {
V::map_vector_items(content, |content| {
let mut content = content;
// Exit early if there are no points to generate splines from.
if content.element().point_count() == 0 {
return content;
}
edit_item_geometry(&mut content, |vector, paths| {
let manipulator_runs = vector.stroke_manipulator_groups(paths).collect::<Vec<_>>();
vector.keep_only_anchors(paths);
// An ID shared by several points resolves to the first of them
let mut anchor_index: HashMap<PointId, u32> = HashMap::new();
for index in 0..vector.point_count() as u32 {
if let Some(id) = vector.point_id_at(index) {
anchor_index.entry(id).or_insert(index);
}
}
let mut next_id = SegmentId::ZERO;
let mut smooth_anchors = Vec::new();
for (manipulator_groups, closed) in manipulator_runs {
let positions = manipulator_groups.iter().map(|manipulators| manipulators.anchor).collect::<Vec<_>>();
if positions.len() < 2 {
continue;
}
let closed = closed && positions.len() > 2;
let Some(anchors) = manipulator_groups.iter().map(|group| anchor_index.get(&group.id).copied()).collect::<Option<Vec<_>>>() else {
log::error!("Spline skipped a run with anchor IDs that name no point");
continue;
};
// The spline runs smoothly through every anchor with a segment on each side
let interior = if closed {
&manipulator_groups[..]
} else {
manipulator_groups.get(1..positions.len().saturating_sub(1)).unwrap_or_default()
};
smooth_anchors.extend(interior.iter().map(|manipulators| manipulators.id));
// Compute control point handles for Bezier spline.
let first_handles = if closed {
solve_spline_first_handle_closed(&positions)
} else {
solve_spline_first_handle_open(&positions)
};
// Weave the run as one cubic path, each span's two handles appended to the pool and referenced between its anchors
let span_count = positions.len() - if closed { 0 } else { 1 };
let (mut references, mut ids) = (Vec::with_capacity(span_count * 3 + 1), Vec::with_capacity(span_count));
for i in 0..span_count {
let next_index = (i + 1) % positions.len();
let handle_start = first_handles[i];
let handle_end = positions[next_index] * 2. - first_handles[next_index];
references.push(anchors[i]);
for handle in [handle_start, handle_end] {
references.push(vector.point_count() as u32);
vector.0.push(Item::new_from_element(handle).with_attribute(ATTR_ID, PointId::UNNAMED));
}
ids.push(next_id.next_id());
}
references.push(anchors[span_count % positions.len()]);
push_path(paths, CurveType::Cubic, references, ids);
}
vector.set_smooth_points(paths, smooth_anchors, true);
});
content
})
}
/// Computes the inverse of a transform's linear (matrix2) part, handling singular transforms
/// (e.g. zero scale on one axis) by replacing the collapsed axis with a unit perpendicular
/// so offsets still apply there (visible if the transform is later replaced).
fn inverse_linear_or_repair(linear: DMat2) -> DMat2 {
if linear.determinant() != 0. {
return linear.inverse();
}
let col0 = linear.col(0);
let col1 = linear.col(1);
let col0_exists = col0.length_squared() > (f64::EPSILON * 1e3).powi(2);
let col1_exists = col1.length_squared() > (f64::EPSILON * 1e3).powi(2);
// Scaled down first, since a column too long to square would normalize to zero
let unit_perpendicular = |column: DVec2| (column / column.abs().max_element()).perp().normalize();
let repaired = match (col0_exists, col1_exists) {
(true, _) => DMat2::from_cols(col0, unit_perpendicular(col0)),
(false, true) => DMat2::from_cols(unit_perpendicular(col1), col1),
(false, false) => DMat2::IDENTITY,
};
repaired.inverse()
}
/// Applies displacement deltas to the anchors at the given pool indices, moving the handles of their segments along with them.
fn apply_point_deltas(vector: &mut Vector, paths: &List<Path>, anchors: &[usize], deltas: &[DVec2]) {
let mut anchor_delta = vec![None; vector.point_count()];
for (&anchor, &delta) in anchors.iter().zip(deltas) {
anchor_delta[anchor] = Some(delta);
}
let mut delta_at: Vec<DVec2> = anchor_delta.iter().map(|delta| delta.unwrap_or_default()).collect();
let delta_of = |anchor: u32| anchor_delta.get(anchor as usize).copied().flatten().unwrap_or_default();
// A handle travels with the anchor on its own side of the segment, unless it is also an anchor with a delta of its own
for span in spans(paths) {
let Some((start, end)) = span_endpoints(paths, span) else { continue };
let (start_delta, end_delta) = (delta_of(start), delta_of(end));
let carried = match curve_type_at(paths, span.path as usize) {
CurveType::Linear => [(None, DVec2::ZERO); 2],
// A quadratic's lone handle answers to both anchors, so it splits the difference between them
CurveType::Quadratic => [(handle_point(paths, span, true), (start_delta + end_delta) / 2.), (None, DVec2::ZERO)],
CurveType::Cubic => [(handle_point(paths, span, true), start_delta), (handle_point(paths, span, false), end_delta)],
};
for (handle, delta) in carried {
if let Some(handle) = handle
&& anchor_delta.get(handle as usize).is_some_and(Option::is_none)
&& let Some(slot) = delta_at.get_mut(handle as usize)
{
*slot = delta;
}
}
}
for (position, delta) in vector.0.iter_element_values_mut().zip(delta_at) {
*position += delta;
}
}
/// Perturbs the positions of anchor points in vector geometry by random amounts and directions.
#[node_macro::node(category("Vector: Point"), icon("NodeJitterPoints"), path(core_types::vector))]
fn jitter_points<V: MapVectorItems + Send>(
_: impl Ctx,
/// The vector geometry with points to be jittered.
#[implementations(Graphic, Vector)]
content: Item<V>,
/// The maximum extent of the random distance each point can be offset.
#[unit(" px")]
#[default(5.)]
max_distance: Item<f64>,
/// Seed used to determine unique variations on all randomized offsets.
#[hard(0..)]
seed: Item<i64>,
/// Whether to offset anchor points along their normal direction (perpendicular to the path) or in a random direction. Free-floating and branching points have no normal direction, so they receive a random-angled offset regardless of this setting.
#[default(true)]
along_normals: Item<bool>,
) -> Item<V> {
V::map_vector_items(content, |content| {
let mut content = content;
let (max_distance, seed, along_normals) = (*max_distance.element(), *seed.element(), *along_normals.element());
let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64);
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
let inverse_linear = inverse_linear_or_repair(transform_attribute.matrix2);
edit_item_points(&mut content, |vector, paths| {
let tangents = if along_normals { vector.anchor_tangents(paths) } else { Vec::new() };
let anchors = vector.anchor_indices(paths);
let deltas: Vec<_> = anchors
.iter()
.map(|&point_index| {
let normal = tangents.get(point_index).copied().flatten().map(|tangent| -tangent.perp());
let offset = if let Some(normal) = normal {
normal * (rng.random::<f64>() * 2. - 1.)
} else {
DVec2::from_angle(rng.random::<f64>() * TAU) * rng.random::<f64>()
};
inverse_linear * offset * max_distance
})
.collect();
apply_point_deltas(vector, paths, &anchors, &deltas);
});
content
})
}
/// Displaces anchor points along their normal direction (perpendicular to the path) by a set distance.
/// Points with 0 or 3+ segment connections have no well-defined normal and are left in place.
#[node_macro::node(category("Vector: Point"), icon("NodeOffsetPoints"), path(core_types::vector))]
fn offset_points<V: MapVectorItems + Send>(
_: impl Ctx,
/// The vector geometry with points to be offset.
#[implementations(Graphic, Vector)]
content: Item<V>,
/// The distance to offset each anchor point along its normal. Positive values move outward, negative values move inward.
#[default(10.)]
#[unit(" px")]
distance: Item<f64>,
) -> Item<V> {
V::map_vector_items(content, |content| {
let mut content = content;
let distance = *distance.element();
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
let inverse_linear = inverse_linear_or_repair(transform_attribute.matrix2);
edit_item_points(&mut content, |vector, paths| {
let tangents = vector.anchor_tangents(paths);
let anchors = vector.anchor_indices(paths);
let deltas: Vec<_> = anchors
.iter()
.map(|&point_index| {
let Some(normal) = tangents.get(point_index).copied().flatten().map(|tangent| -tangent.perp()) else {
return DVec2::ZERO;
};
inverse_linear * normal * distance
})
.collect();
apply_point_deltas(vector, paths, &anchors, &deltas);
});
content
})
}
/// Interpolates the geometry, appearance, and transform between multiple vector layers, producing a single morphed vector shape.
///
/// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments.
#[node_macro::node(category("Vector: Deform"), icon("NodeMorph"), path(core_types::vector), footprint_invariant)]
fn morph(
_: impl Ctx,
/// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements.
content: List<Graphic>,
/// The fractional part `[0, 1)` traverses the morph uniformly along the path. If the control path has multiple subpaths, each added integer selects the next subpath.
#[progression]
progression: Item<f64>,
/// Swap the direction of the progression between objects or along the control path.
reverse: Item<bool>,
/// The parameter of change that influences the interpolation speed between each object. Equal slices in this parameter correspond to the rate of progression through the morph. This must be set to a parameter that changes.
///
/// "Objects" morphs through each group element at an equal rate. "Distances" keeps constant speed with time between objects proportional to their distances. "Angles" keeps constant rotational speed. "Sizes" keeps constant shrink/growth speed. "Slants" keeps constant shearing angle speed.
distribution: Item<InterpolationDistribution>,
/// An optional control path whose anchor points correspond to each object. Curved segments between points will shape the morph trajectory instead of traveling straight. If there is a break between path segments, the separate subpaths are selected by index from the integer part of the progression value. For example, `[1, 2)` morphs along the segments of the second subpath, and so on.
path: Item<Vector>,
) -> Result<Item<Vector>, ProgressionError> {
/// Promotes a segment's handle pair to cubic-equivalent Bézier control points.
/// For linear segments (both None), handles are placed at their respective anchors (zero-length)
/// so that interpolation against another zero-length cubic doesn't introduce unwanted curvature.
/// For quadratic segments (one handle), degree elevation is applied.
fn promote_handles_to_cubic(prev_anchor: DVec2, out_handle: Option<DVec2>, in_handle: Option<DVec2>, curr_anchor: DVec2) -> (DVec2, DVec2) {
match (out_handle, in_handle) {
(Some(handle_start), Some(handle_end)) => (handle_start, handle_end),
(None, None) => (prev_anchor, curr_anchor),
(Some(handle), None) | (None, Some(handle)) => {
let handle_start = prev_anchor + (handle - prev_anchor) * (2. / 3.);
let handle_end = curr_anchor + (handle - curr_anchor) * (2. / 3.);
(handle_start, handle_end)
}
}
}
/// Subdivides the last segment of a manipulator group list at its midpoint, adding one new manipulator.
/// For closed paths, the "last segment" is the closing segment from the last back to the first manipulator.
fn subdivide_last_manipulator_segment(manips: &mut Vec<ManipulatorGroup>, closed: bool) {
let len = manips.len();
// A closed loop through one anchor still has its closing segment, from the anchor back to itself
if len == 0 || (len == 1 && !closed) {
return;
}
let (prev_index, next_index) = if closed { (len - 1, 0) } else { (len - 2, len - 1) };
let prev_anchor = manips[prev_index].anchor;
let next_anchor = manips[next_index].anchor;
let (h1, h2) = promote_handles_to_cubic(prev_anchor, manips[prev_index].out_handle, manips[next_index].in_handle, next_anchor);
// De Casteljau subdivision at t=0.5
let m01 = prev_anchor.lerp(h1, 0.5);
let m12 = h1.lerp(h2, 0.5);
let m23 = h2.lerp(next_anchor, 0.5);
let m012 = m01.lerp(m12, 0.5);
let m123 = m12.lerp(m23, 0.5);
let mid = m012.lerp(m123, 0.5);
manips[prev_index].out_handle = Some(m01);
manips[next_index].in_handle = Some(m23);
let mid_manip = ManipulatorGroup {
anchor: mid,
in_handle: Some(m012),
out_handle: Some(m123),
id: PointId::ZERO,
};
if closed {
manips.push(mid_manip);
} else {
manips.insert(next_index, mid_manip);
}
}
/// Constructs BezierHandles from the out_handle of one manipulator and in_handle of the next.
fn handles_from_manips(out_handle: Option<DVec2>, in_handle: Option<DVec2>) -> BezierHandles {
match (out_handle, in_handle) {
(Some(handle_start), Some(handle_end)) => BezierHandles::Cubic { handle_start, handle_end },
(None, None) => BezierHandles::Linear,
(Some(handle), None) | (None, Some(handle)) => BezierHandles::Quadratic { handle },
}
}
/// Pushes a subpath (list of manipulators) directly into the working form's points and segments,
/// bypassing the BezPath intermediate representation used by `append_bezpath`.
fn push_manipulators_to_vector(working: &mut WorkingVector, manips: &[ManipulatorGroup], closed: bool, point_id: &mut PointId, segment_id: &mut SegmentId) {
let Some(first) = manips.first() else { return };
let first_point_index = push_working_point(working, point_id.next_id(), first.anchor);
let mut prev_point_index = first_point_index;
for manip_window in manips.windows(2) {
let point_index = push_working_point(working, point_id.next_id(), manip_window[1].anchor);
let handles = handles_from_manips(manip_window[0].out_handle, manip_window[1].in_handle);
push_working_segment(working, segment_id.next_id(), prev_point_index, point_index, handles);
prev_point_index = point_index;
}
if closed && manips.len() > 1 {
let handles = handles_from_manips(manips.last().unwrap().out_handle, manips[0].in_handle);
push_working_segment(working, segment_id.next_id(), prev_point_index, first_point_index, handles);
}
}
fn lerp_gradient_transform(gradient_list_a: &List<Gradient>, gradient_list_b: &List<Gradient>, time: f64) -> DAffine2 {
let transform_a = gradient_list_a.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0);
let transform_b = gradient_list_b.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0);
let start_a = transform_a.translation;
let end_a = transform_a.translation + transform_a.matrix2.x_axis;
let start_b = transform_b.translation;
let end_b = transform_b.translation + transform_b.matrix2.x_axis;
let start = start_a.lerp(start_b, time);
let end = end_a.lerp(end_b, time);
let metadata_source_transform = if time < 0.5 { transform_a } else { transform_b };
build_transform_with_y_preservation(metadata_source_transform, start, end)
}
/// The two paint kinds that can interpolate, read from either rank so the pairings below stay at four cases.
/// A gradient normalizes to the list form because the interpolation carries its placement attributes along.
enum InterpolablePaint<'a> {
Color(&'a Color),
Gradient(List<Gradient>),
}
impl<'a> InterpolablePaint<'a> {
fn from_graphic(graphic: &'a Graphic) -> Option<Self> {
match graphic {
Graphic::Color(item) => Some(InterpolablePaint::Color(item.element())),
Graphic::ColorList(list) => list.element(0).map(InterpolablePaint::Color),
Graphic::Gradient(item) => Some(InterpolablePaint::Gradient(List::new_from_item(item.clone()))),
Graphic::GradientList(list) => list.element(0).is_some().then(|| InterpolablePaint::Gradient(list.clone())),
_ => None,
}
}
}
// Lerp between two graphics. Solid color and gradient pairings interpolate; all other pairings step at the midpoint.
fn lerp_graphic(a: Option<&List<Graphic>>, b: Option<&List<Graphic>>, time: f64) -> Option<List<Graphic>> {
let transparent = List::new_from_element(Color::TRANSPARENT).into_graphic_list();
let a = a.filter(|graphic_list| is_paint_present(graphic_list));
let b = b.filter(|graphic_list| is_paint_present(graphic_list));
let (a, b) = match (a, b) {
(None, None) => return None,
(Some(a), None) => (a, &transparent),
(None, Some(b)) => (&transparent, b),
(Some(a), Some(b)) => (a, b),
};
// This keeps the gradient metadata attributes
let gradient_with_stops = |mut gradient_list: List<Gradient>, stops: Gradient| -> Graphic {
if let Some(target) = gradient_list.element_mut(0) {
*target = stops;
} else {
gradient_list.push(Item::new_from_element(stops));
}
Graphic::GradientList(gradient_list)
};
let graphic = match (a.element(0).and_then(InterpolablePaint::from_graphic), b.element(0).and_then(InterpolablePaint::from_graphic)) {
(Some(InterpolablePaint::Color(color_a)), Some(InterpolablePaint::Color(color_b))) => Some(Graphic::from(color_a.lerp(color_b, time as f32))),
(Some(InterpolablePaint::Color(color_a)), Some(InterpolablePaint::Gradient(gradient_list_b))) => gradient_list_b.element(0).cloned().map(|stops_b| {
let solid_to_gradient = stops_b.map_colors(|_| *color_a);
let stops = solid_to_gradient.lerp(&stops_b, time);
gradient_with_stops(gradient_list_b, stops)
}),
(Some(InterpolablePaint::Gradient(gradient_list_a)), Some(InterpolablePaint::Color(color_b))) => gradient_list_a.element(0).cloned().map(|stops_a| {
let gradient_to_solid = stops_a.map_colors(|_| *color_b);
let stops = stops_a.lerp(&gradient_to_solid, time);
gradient_with_stops(gradient_list_a, stops)
}),
(Some(InterpolablePaint::Gradient(gradient_list_a)), Some(InterpolablePaint::Gradient(gradient_list_b))) => gradient_list_a
.element(0)
.zip(gradient_list_b.element(0))
.map(|(stops_a, stops_b)| stops_a.lerp(stops_b, time))
.map(|stops| {
let transform = lerp_gradient_transform(&gradient_list_a, &gradient_list_b, time);
let mut gradient_list = if time < 0.5 { gradient_list_a } else { gradient_list_b };
gradient_list.set_attribute(ATTR_TRANSFORM, 0, transform);
gradient_with_stops(gradient_list, stops)
}),
// Pairings beyond solid colors and gradients (raster, vector, or mixed) can't be interpolated, so step at the midpoint
_ => return Some(if time < 0.5 { a.clone() } else { b.clone() }),
};
graphic.map(List::new_from_element)
}
// Lerp between two appearances, pairing coverages by cover so a fill and a stroke never interpolate into each other.
// Stroke parameter pairs interpolate; other coverage pairings and the paint order step at the midpoint.
fn lerp_appearance(a: Option<&Appearance>, b: Option<&Appearance>, time: f64) -> Option<Appearance> {
if a.is_none() && b.is_none() {
return None;
}
let empty = Appearance::default();
let (a, b) = (a.unwrap_or(&empty), b.unwrap_or(&empty));
// The side holding the paint order at this time leads, so covers only the other side has follow behind it
let (leading, trailing) = if time < 0.5 { (a, b) } else { (b, a) };
let mut covers: Vec<Cover> = Vec::new();
for cover in leading.covers().chain(trailing.covers()).map(Coverage::cover) {
if !covers.contains(&cover) {
covers.push(cover);
}
}
let mut result = Appearance::default();
for cover in covers {
let (source_index, target_index) = (a.first_index_of(cover), b.first_index_of(cover));
// An unmatched stroke steps out at the midpoint, matching the stroke geometry, while an unmatched fill persists and fades
let (source_transform, target_transform) = (source_index.map(|index| a.transform_at(index)), target_index.map(|index| b.transform_at(index)));
let (coverage, transform) = match (source_index.and_then(|index| a.cover_at(index)), target_index.and_then(|index| b.cover_at(index))) {
(Some(_), Some(_)) if cover == Cover::Stroke => {
let (Some(source), Some(target)) = (source_index.and_then(|index| a.stroke_params_at(index)), target_index.and_then(|index| b.stroke_params_at(index))) else {
continue;
};
let stroke = source.lerp(&target, time);
(Coverage::new_stroke(&stroke), stroke.transform)
}
(Some(source), Some(_)) if time < 0.5 => (source.clone(), source_transform.unwrap_or_default()),
(Some(_), Some(target)) => (target.clone(), target_transform.unwrap_or_default()),
(Some(_), None) if cover == Cover::Stroke && time >= 0.5 => continue,
(None, Some(_)) if cover == Cover::Stroke && time < 0.5 => continue,
(Some(source), None) => (source.clone(), source_transform.unwrap_or_default()),
(None, Some(target)) => (target.clone(), target_transform.unwrap_or_default()),
(None, None) => continue,
};
// An unmatched side falls to `None` here, which `lerp_graphic` fades against transparent
let source_paint = source_index.and_then(|index| a.paint_at(index)).map(|paint| List::new_from_element(paint.clone()));
let target_paint = target_index.and_then(|index| b.paint_at(index)).map(|paint| List::new_from_element(paint.clone()));
let paint = lerp_graphic(source_paint.as_ref(), target_paint.as_ref(), time)
.and_then(|list| list.into_iter().next())
.map(Item::into_element)
.unwrap_or_default();
result.replace_or_insert(coverage, paint, transform, CoverPlacement::Above);
}
Some(result)
}
let (progression, reverse, distribution) = (progression.into_element(), reverse.into_element(), distribution.into_element());
// Preserve original `List<Graphic>` as upstream data so this group layer's nested layers can be edited by the tools.
let mut graphic_list_content = content.clone();
// Only vector content can interpolate, so the rest is discarded by flattening.
let content = content.into_flattened_list::<Vector>();
// Not enough elements to interpolate between, so we return the input as-is
if content.len() <= 1 {
return Ok(content.into_iter().next().unwrap_or_default());
}
if progression.is_nan() {
return Err(ProgressionError::NotANumber);
}
// Build the control path for the morph trajectory.
// Collect all subpaths from the path input (applying transforms), or build a default polyline from element origins.
let default_polyline = || {
let mut default_path = BezPath::new();
for index in 0..content.len() {
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM, index);
let origin = transform_attribute.translation;
let point = kurbo::Point::new(origin.x, origin.y);
if index == 0 {
default_path.move_to(point);
} else {
default_path.line_to(point);
}
}
vec![default_path]
};
let control_bezpaths: Vec<BezPath> = {
// User-provided path: collect all subpaths with the path's transform applied
let path_transform: DAffine2 = path.attribute_cloned_or_default(ATTR_TRANSFORM);
let control_paths = paths_from_item_attributes(&path).unwrap_or_else(|| no_paths());
let paths: Vec<BezPath> = path
.element()
.stroke_bezpath_iter(control_paths)
.map(|mut bezpath| {
bezpath.apply_affine(Affine::new(path_transform.to_cols_array()));
bezpath
})
.collect();
// Fall back to default polyline if the provided path has no subpaths
if paths.is_empty() { default_polyline() } else { paths }
};
// Select which subpath to use based on the integer part of progression (like the 'Evaluate Path' node)
let progression = progression.max(0.);
let subpath_count = control_bezpaths.len() as f64;
let progression = if reverse { subpath_count - progression } else { progression };
let clamped_progression = progression.clamp(0., subpath_count);
let subpath_index = if clamped_progression >= subpath_count { subpath_count - 1. } else { clamped_progression } as usize;
let fractional_progression = if clamped_progression >= subpath_count { 1. } else { clamped_progression.fract() };
let control_bezpath = &control_bezpaths[subpath_index];
let segment_count = control_bezpath.segments().count();
// If the control path has no segments, return the first item
if segment_count == 0 {
return Ok(content.into_iter().next().unwrap_or_default());
}
// Determine if the selected subpath is closed (has a closing segment connecting its end back to its start)
let is_closed = control_bezpath.elements().last() == Some(&PathEl::ClosePath);
// Number of anchor points (content elements) per subpath: for closed subpaths, the closing
// segment doesn't add a new anchor, so anchors = segments. For open: anchors = segments + 1.
let anchor_count = |bp: &BezPath| -> usize {
let segs = bp.segments().count();
let closed = bp.elements().last() == Some(&PathEl::ClosePath);
if closed { segs } else { segs + 1 }
};
// Offset source_index by the number of content elements consumed by previous subpaths,
// so each subpath morphs through its own slice of content (not always starting from element 0).
let content_offset: usize = control_bezpaths[..subpath_index].iter().map(&anchor_count).sum();
let subpath_anchors = anchor_count(control_bezpath);
let max_content_index = content.len().saturating_sub(1);
// Map the fractional progression to a segment index and local blend time using the chosen weights.
let (local_source_index, time) = if fractional_progression >= 1. {
(segment_count - 1, 1.)
} else if matches!(distribution, InterpolationDistribution::Objects) {
// Fast path for uniform distribution: direct index calculation without allocation or iteration
let scaled = fractional_progression * segment_count as f64;
let index = (scaled.ceil() as usize).saturating_sub(1);
(index, scaled - index as f64)
} else {
// Compute segment weights based on the user's chosen spacing metric
let segment_weights: Vec<f64> = match distribution {
InterpolationDistribution::Objects => unreachable!(),
InterpolationDistribution::Distances => control_bezpath.segments().map(|seg| seg.perimeter(DEFAULT_ACCURACY)).collect(),
InterpolationDistribution::Angles | InterpolationDistribution::Sizes | InterpolationDistribution::Slants => (0..segment_count)
.map(|i| {
let source_index = (content_offset + i).min(max_content_index);
let target_index = if is_closed && i >= subpath_anchors - 1 {
content_offset
} else {
(content_offset + i + 1).min(max_content_index)
};
if content.element(source_index).is_none() || content.element(target_index).is_none() {
return 0.;
}
let source_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM, source_index);
let target_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM, target_index);
let (s_angle, s_scale, s_skew) = source_transform.decompose_rotation_scale_skew();
let (t_angle, t_scale, t_skew) = target_transform.decompose_rotation_scale_skew();
match distribution {
InterpolationDistribution::Angles => {
let mut diff = t_angle - s_angle;
if diff > PI {
diff -= TAU;
} else if diff < -PI {
diff += TAU;
}
diff.abs()
}
InterpolationDistribution::Sizes => (t_scale - s_scale).length(),
InterpolationDistribution::Slants => (t_skew.atan() - s_skew.atan()).abs(),
_ => unreachable!(),
}
})
.collect(),
};
let total_weight: f64 = segment_weights.iter().sum();
// When all weights are zero (all elements identical in the chosen metric), there's zero interval to traverse.
if total_weight <= f64::EPSILON {
(0, 0.)
} else {
let mut accumulator = 0.;
let mut found_index = segment_count - 1;
let mut found_t = 1.;
for (i, weight) in segment_weights.iter().enumerate() {
let ratio = weight / total_weight;
if fractional_progression <= accumulator + ratio {
found_index = i;
found_t = if ratio > f64::EPSILON { (fractional_progression - accumulator) / ratio } else { 0. };
break;
}
accumulator += ratio;
}
(found_index, found_t)
}
};
// Convert the blend time to a parametric t for evaluating spatial position on the control path
let path_segment_index = local_source_index;
let parametric_t = {
let segment_index = path_segment_index.min(segment_count - 1);
let segment = control_bezpath.get_seg(segment_index + 1).unwrap();
eval_pathseg_euclidean(segment, time, DEFAULT_ACCURACY)
};
let source_index = local_source_index + content_offset;
// For closed subpaths, the closing segment wraps target back to the first element of this subpath's slice.
// For open subpaths, target is simply the next element.
let target_index = if is_closed && local_source_index >= subpath_anchors - 1 {
content_offset // Wrap to first element of this subpath's slice
} else {
source_index + 1
};
// Clamp to valid content range
let source_index = source_index.min(max_content_index);
let target_index = target_index.min(max_content_index);
// Use indexed access to borrow only the two elements we need
let (Some(source_element), Some(target_element)) = (content.element(source_index), content.element(target_index)) else {
return Ok(Item::default());
};
// Lerp blending attributes: opacity/fill interpolate, blend_mode/clip step at the midpoint
let source_blend_mode: BlendMode = content.attribute_cloned_or_default(ATTR_BLEND_MODE, source_index);
let target_blend_mode: BlendMode = content.attribute_cloned_or_default(ATTR_BLEND_MODE, target_index);
let source_opacity: f64 = content.attribute_cloned_or(ATTR_OPACITY, source_index, 1.);
let target_opacity: f64 = content.attribute_cloned_or(ATTR_OPACITY, target_index, 1.);
let source_fill: f64 = content.attribute_cloned_or(ATTR_OPACITY_FILL, source_index, 1.);
let target_fill: f64 = content.attribute_cloned_or(ATTR_OPACITY_FILL, target_index, 1.);
let source_clip: bool = content.attribute_cloned_or_default(ATTR_CLIPPING_MASK, source_index);
let target_clip: bool = content.attribute_cloned_or_default(ATTR_CLIPPING_MASK, target_index);
let lerped_blend_mode = if time < 0.5 { source_blend_mode } else { target_blend_mode };
let lerped_opacity = source_opacity + (target_opacity - source_opacity) * time;
let lerped_fill = source_fill + (target_fill - source_fill) * time;
let lerped_clip = if time < 0.5 { source_clip } else { target_clip };
// Evaluate the spatial position on the control path for the translation component.
// When the segment has zero arc length (e.g., two objects at the same position), inv_arclen
// produces NaN (0/0), so we fall back to the segment start point to avoid NaN translation.
let path_position = {
let segment_index = path_segment_index.min(segment_count - 1);
let segment = control_bezpath.get_seg(segment_index + 1).unwrap();
let parametric_t = if segment.arclen(DEFAULT_ACCURACY) < f64::EPSILON { 0. } else { parametric_t };
let point = segment.eval(parametric_t);
DVec2::new(point.x, point.y)
};
// Interpolate rotation, scale, and skew between source and target, but use the path position for translation.
// This decomposition must match the one used in Stroke::lerp so the renderer's stroke_transform.inverse()
// correctly cancels the element transform, keeping the stroke uniform when Stroke is after Transform.
let lerped_transform = {
let source_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM, source_index);
let target_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM, target_index);
let (s_angle, s_scale, s_skew) = source_transform.decompose_rotation_scale_skew();
let (t_angle, t_scale, t_skew) = target_transform.decompose_rotation_scale_skew();
let lerp = |a: f64, b: f64| a + (b - a) * time;
// Shortest-arc rotation interpolation
let mut rotation_diff = t_angle - s_angle;
if rotation_diff > PI {
rotation_diff -= TAU;
} else if rotation_diff < -PI {
rotation_diff += TAU;
}
let lerped_angle = s_angle + rotation_diff * time;
let trs = DAffine2::from_scale_angle_translation(s_scale.lerp(t_scale, time), lerped_angle, path_position);
let skew = DAffine2::from_cols_array(&[1., 0., lerp(s_skew, t_skew), 1., 0., 0.]);
trs * skew
};
// Pre-compensate merged_layers transforms so that when collect_metadata applies
// the item transform (which will be group_transform * lerped_transform after the
// pipeline's Transform node runs), the lerped_transform cancels out and children
// get the correct footprint: parent * group_transform * child_transform.
// Only pre-compensate if the lerped transform is invertible (nonzero determinant).
// A zero determinant can occur when interpolated scale passes through zero (e.g., flipped axes),
// in which case we skip pre-compensation to avoid propagating NaN through merged_layers transforms.
if lerped_transform.matrix2.determinant().abs() > f64::EPSILON {
let lerped_inverse = lerped_transform.inverse();
for transform in graphic_list_content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
*transform = lerped_inverse * *transform;
}
}
// Fast path: when exactly at either endpoint, clone the corresponding geometry directly
// instead of extracting manipulator groups, subdividing, interpolating, and rebuilding.
if time == 0. || time == 1. {
let endpoint_index = if time == 0. { source_index } else { target_index };
let endpoint_element = content.element(endpoint_index).unwrap();
let mut attributes = content.clone_item_attributes(endpoint_index);
attributes.insert(ATTR_TRANSFORM, lerped_transform);
attributes.insert(ATTR_EDITOR_MERGED_LAYERS, graphic_list_content);
return Ok(Item::from_parts(endpoint_element.clone(), attributes));
}
let mut working = WorkingVector::default();
let appearance = {
let source = content.attribute::<Appearance>(ATTR_APPEARANCE, source_index);
let target = content.attribute::<Appearance>(ATTR_APPEARANCE, target_index);
lerp_appearance(source, target, time)
};
// Work directly with manipulator groups, bypassing the BezPath intermediate representation.
// This avoids the full Vector → BezPath → interpolate → BezPath → Vector roundtrip each frame.
let source_paths = paths_from_list_row_attributes(&content, source_index).unwrap_or_else(|| no_paths());
let target_paths = paths_from_list_row_attributes(&content, target_index).unwrap_or_else(|| no_paths());
let mut source_subpaths: Vec<_> = source_element.stroke_manipulator_groups(source_paths).collect();
let mut target_subpaths: Vec<_> = target_element.stroke_manipulator_groups(target_paths).collect();
// Interpolate geometry in local space (no transform baked in); the lerped transform handles positioning
let matched_count = source_subpaths.len().min(target_subpaths.len());
let extra_source = source_subpaths.split_off(matched_count);
let extra_target = target_subpaths.split_off(matched_count);
// Pre-allocate the working form based on total manipulator counts across all subpaths
let mut total_points = 0;
let mut total_segments = 0;
for ((source_manips, source_closed), (target_manips, _)) in source_subpaths.iter().zip(target_subpaths.iter()) {
if source_manips.is_empty() || target_manips.is_empty() {
continue;
}
let manip_count = source_manips.len().max(target_manips.len());
total_points += manip_count;
total_segments += if *source_closed { manip_count } else { manip_count.saturating_sub(1) };
}
for (manips, closed) in extra_source.iter().chain(extra_target.iter()) {
total_points += manips.len();
total_segments += if *closed { manips.len() } else { manips.len().saturating_sub(1) };
}
working.point_ids.reserve(total_points);
working.point_positions.reserve(total_points);
working.segment_ids.reserve(total_segments);
working.segment_start.reserve(total_segments);
working.segment_end.reserve(total_segments);
working.segment_handles.reserve(total_segments);
let mut point_id = PointId::ZERO;
let mut segment_id = SegmentId::ZERO;
for ((mut source_manips, source_closed), (mut target_manips, target_closed)) in source_subpaths.into_iter().zip(target_subpaths) {
if source_manips.is_empty() || target_manips.is_empty() {
continue;
}
// Align manipulator counts by subdividing the last segment of the shorter subpath
let source_count = source_manips.len();
let target_count = target_manips.len();
for _ in 0..target_count.saturating_sub(source_count) {
subdivide_last_manipulator_segment(&mut source_manips, source_closed);
}
for _ in 0..source_count.saturating_sub(target_count) {
subdivide_last_manipulator_segment(&mut target_manips, target_closed);
}
// Build interpolated manipulator groups
let mut interpolated: Vec<ManipulatorGroup> = source_manips
.iter()
.zip(target_manips.iter())
.map(|(s, t)| ManipulatorGroup {
anchor: s.anchor.lerp(t.anchor, time),
in_handle: None,
out_handle: None,
id: PointId::ZERO,
})
.collect();
// Interpolate handles per segment, preserving handle type when source and target match
let segment_count = if source_closed { source_manips.len() } else { source_manips.len().saturating_sub(1) };
for segment_index in 0..segment_count {
let next_index = (segment_index + 1) % source_manips.len();
let source_out = source_manips[segment_index].out_handle;
let source_in = source_manips[next_index].in_handle;
let target_out = target_manips[segment_index].out_handle;
let target_in = target_manips[next_index].in_handle;
match (source_out, source_in, target_out, target_in) {
// Both linear: no handles needed
(None, None, None, None) => {}
// Both cubic: lerp handle pairs directly
(Some(s_out), Some(s_in), Some(t_out), Some(t_in)) => {
interpolated[segment_index].out_handle = Some(s_out.lerp(t_out, time));
interpolated[next_index].in_handle = Some(s_in.lerp(t_in, time));
}
// Both quadratic with handle in the same position: lerp the single handle
(Some(s_out), None, Some(t_out), None) => {
interpolated[segment_index].out_handle = Some(s_out.lerp(t_out, time));
}
(None, Some(s_in), None, Some(t_in)) => {
interpolated[next_index].in_handle = Some(s_in.lerp(t_in, time));
}
// Linear vs. quadratic: elevate the linear side to a zero-length quadratic in the matching position
(None, None, Some(t_out), None) => {
interpolated[segment_index].out_handle = Some(source_manips[segment_index].anchor.lerp(t_out, time));
}
(None, None, None, Some(t_in)) => {
interpolated[next_index].in_handle = Some(source_manips[next_index].anchor.lerp(t_in, time));
}
(Some(s_out), None, None, None) => {
interpolated[segment_index].out_handle = Some(s_out.lerp(target_manips[segment_index].anchor, time));
}
(None, Some(s_in), None, None) => {
interpolated[next_index].in_handle = Some(s_in.lerp(target_manips[next_index].anchor, time));
}
// Mismatched types: promote both to cubic and lerp
_ => {
let (s_h1, s_h2) = promote_handles_to_cubic(source_manips[segment_index].anchor, source_out, source_in, source_manips[next_index].anchor);
let (t_h1, t_h2) = promote_handles_to_cubic(target_manips[segment_index].anchor, target_out, target_in, target_manips[next_index].anchor);
interpolated[segment_index].out_handle = Some(s_h1.lerp(t_h1, time));
interpolated[next_index].in_handle = Some(s_h2.lerp(t_h2, time));
}
}
}
push_manipulators_to_vector(&mut working, &interpolated, source_closed, &mut point_id, &mut segment_id);
}
// Deal with unmatched extra source subpaths by collapsing them toward their end point
for (mut manips, closed) in extra_source {
let Some(end) = manips.last().map(|m| m.anchor) else { continue };
for manip in &mut manips {
manip.anchor = manip.anchor.lerp(end, time);
manip.in_handle = manip.in_handle.map(|h| h.lerp(end, time));
manip.out_handle = manip.out_handle.map(|h| h.lerp(end, time));
}
push_manipulators_to_vector(&mut working, &manips, closed, &mut point_id, &mut segment_id);
}
// Deal with unmatched extra target subpaths by expanding them from their start point
for (mut manips, closed) in extra_target {
let Some(start) = manips.first().map(|m| m.anchor) else { continue };
for manip in &mut manips {
manip.anchor = start.lerp(manip.anchor, time);
manip.in_handle = manip.in_handle.map(|h| start.lerp(h, time));
manip.out_handle = manip.out_handle.map(|h| start.lerp(h, time));
}
push_manipulators_to_vector(&mut working, &manips, closed, &mut point_id, &mut segment_id);
}
// The result is a synthesis of source and target, so adopt whichever endpoint the result is closer to as
// the click-target identity (so the editor can route clicks back to one of the contributing layers)
let primary_index = if time < 0.5 { source_index } else { target_index };
let (mut vector, mut paths) = (Vector::default(), List::new());
working.reweave(&mut vector, &mut paths);
let mut item = Item::new_from_element(vector);
item.set_paths(paths);
item.set_attribute(ATTR_TRANSFORM, lerped_transform);
// Propagate each blending/layer column only when the input carries it, so attribute presence stays determined by the graph rather than by runtime values
if content.attribute::<BlendMode>(ATTR_BLEND_MODE, source_index).is_some() {
item.set_attribute(ATTR_BLEND_MODE, lerped_blend_mode);
}
if content.attribute::<f64>(ATTR_OPACITY, source_index).is_some() {
item.set_attribute(ATTR_OPACITY, lerped_opacity);
}
if content.attribute::<f64>(ATTR_OPACITY_FILL, source_index).is_some() {
item.set_attribute(ATTR_OPACITY_FILL, lerped_fill);
}
if content.attribute::<bool>(ATTR_CLIPPING_MASK, source_index).is_some() {
item.set_attribute(ATTR_CLIPPING_MASK, lerped_clip);
}
if let Some(layer_path) = content.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, primary_index) {
item.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
}
item.set_attribute(ATTR_EDITOR_MERGED_LAYERS, graphic_list_content);
if let Some(appearance) = appearance {
item.set_attribute(ATTR_APPEARANCE, appearance);
}
Ok(item)
}
fn bevel_algorithm(vector: &mut Vector, paths: &mut List<Path>, transform: DAffine2, distance: f64) {
// Splits a bézier curve based on a distance measurement
fn split_distance(bezier: PathSeg, distance: f64, length: f64) -> PathSeg {
let parametric = eval_pathseg_euclidean(bezier, (distance / length).clamp(0., 1.), DEFAULT_ACCURACY);
bezier.subsegment(parametric..1.)
}
/// Produces a list that corresponds with the point ID. The value is how many segments are connected.
fn segments_connected_count(working: &WorkingVector) -> Vec<usize> {
// Count the number of segments connecting to each point.
let mut segments_connected_count = vec![0; working.point_ids.len()];
for &point_index in working.segment_start.iter().chain(&working.segment_end) {
segments_connected_count[point_index] += 1;
}
// Zero out points without exactly two connectors. These are ignored.
for count in &mut segments_connected_count {
if *count != 2 {
*count = 0;
}
}
segments_connected_count
}
/// Updates the index so that it points at a point with the position. If nobody else will look at the index, the original point is updated. Otherwise a new point is created.
fn create_or_modify_point(working: &mut WorkingVector, segments_connected_count: &mut [usize], pos: DVec2, index: &mut usize, next_id: &mut PointId, new_segments: &mut Vec<[usize; 2]>) {
segments_connected_count[*index] -= 1;
if segments_connected_count[*index] == 0 {
// If nobody else is going to look at this point, we're alright to modify it
working.point_positions[*index] = pos;
} else {
let original_index = *index;
// Create a new point (since someone will wish to look at the point in the original position in future)
let new_index = push_working_point(working, next_id.next_id(), pos);
*index = new_index;
// Add a new segment to be created later
new_segments.push([new_index, original_index]);
}
}
fn calculate_distance_to_split(bezier1: PathSeg, bezier2: PathSeg, bevel_length: f64) -> f64 {
if is_linear(bezier1) && is_linear(bezier2) {
let v1 = (bezier1.end() - bezier1.start()).normalize();
let v2 = (bezier1.end() - bezier2.end()).normalize();
let dot_product = v1.dot(v2);
let angle_rad = dot_product.acos();
return bevel_length / (2. * (angle_rad / 2.).sin());
}
let length1 = bezier1.perimeter(DEFAULT_ACCURACY);
let length2 = bezier2.perimeter(DEFAULT_ACCURACY);
let max_split = length1.min(length2);
let mut split_distance = 0.;
let mut best_diff = f64::MAX;
let mut current_best_distance = 0.;
let clamp_and_round = |value: f64| ((value * 1000.).round() / 1000.).clamp(0., 1.);
const INITIAL_SAMPLES: usize = 50;
for i in 0..=INITIAL_SAMPLES {
let distance_sample = max_split * (i as f64 / INITIAL_SAMPLES as f64);
let x_point_t = eval_pathseg_euclidean(bezier1, 1. - clamp_and_round(distance_sample / length1), DEFAULT_ACCURACY);
let y_point_t = eval_pathseg_euclidean(bezier2, clamp_and_round(distance_sample / length2), DEFAULT_ACCURACY);
let x_point = bezier1.eval(x_point_t);
let y_point = bezier2.eval(y_point_t);
let distance = x_point.distance(y_point);
let diff = (bevel_length - distance).abs();
if diff < best_diff {
best_diff = diff;
current_best_distance = distance_sample;
}
if bevel_length - distance < 0. {
split_distance = distance_sample;
if i > 0 {
let prev_sample = max_split * ((i - 1) as f64 / INITIAL_SAMPLES as f64);
const REFINE_STEPS: usize = 10;
for j in 1..=REFINE_STEPS {
let refined_sample = prev_sample + (distance_sample - prev_sample) * (j as f64 / REFINE_STEPS as f64);
let x_point_t = eval_pathseg_euclidean(bezier1, 1. - (refined_sample / length1).clamp(0., 1.), DEFAULT_ACCURACY);
let y_point_t = eval_pathseg_euclidean(bezier2, (refined_sample / length2).clamp(0., 1.), DEFAULT_ACCURACY);
let x_point = bezier1.eval(x_point_t);
let y_point = bezier2.eval(y_point_t);
let distance = x_point.distance(y_point);
if bevel_length - distance < 0. {
split_distance = refined_sample;
break;
}
}
}
break;
}
}
if split_distance == 0. && current_best_distance > 0. {
split_distance = current_best_distance;
}
split_distance
}
fn sort_segments(working: &WorkingVector) -> Vec<usize> {
let start_points = &working.segment_start;
let end_points = &working.segment_end;
let mut sorted_segments = vec![0];
let segment_count = working.segment_ids.len();
for _ in 0..segment_count {
match sorted_segments.last() {
Some(&last) => {
if let Some(index) = start_points.iter().position(|&p| p == end_points[last]) {
// The chain ends where it runs into a segment it already passed through
if sorted_segments.contains(&index) {
break;
}
sorted_segments.push(index);
}
}
None => break,
}
}
if segment_count != sorted_segments.len() {
for i in 0..segment_count {
if !sorted_segments.contains(&i) {
sorted_segments.push(i);
}
}
}
sorted_segments
}
fn update_existing_segments(working: &mut WorkingVector, transform: DAffine2, distance: f64, segments_connected: &mut [usize]) -> Vec<[usize; 2]> {
let mut next_id = next_working_point_id(working);
let mut new_segments = Vec::new();
let sorted_segments = sort_segments(working);
let segment_count = working.segment_ids.len();
let mut first_original_length = 0.;
let mut first_length = 0.;
let mut prev_original_length = 0.;
let mut prev_length = 0.;
for i in 0..segment_count {
let (index, next_index) = if i == segment_count - 1 { (i, 0) } else { (i, i + 1) };
let (segment, next_segment) = (sorted_segments[index], sorted_segments[next_index]);
let (start_point, mut end_point) = (working.segment_start[segment], working.segment_end[segment]);
let (mut next_start_point, next_end_point) = (working.segment_start[next_segment], working.segment_end[next_segment]);
let start = working.point_positions[start_point];
let end = working.point_positions[end_point];
let mut bezier = handles_to_segment(start, working.segment_handles[segment], end);
bezier = Affine::new(transform.to_cols_array()) * bezier;
let next_start = working.point_positions[next_start_point];
let next_end = working.point_positions[next_end_point];
let mut next_bezier = handles_to_segment(next_start, working.segment_handles[next_segment], next_end);
next_bezier = Affine::new(transform.to_cols_array()) * next_bezier;
let calculated_split_distance = calculate_distance_to_split(bezier, next_bezier, distance);
if is_linear(bezier) {
bezier = PathSeg::Line(Line::new(bezier.start(), bezier.end()));
}
if is_linear(next_bezier) {
next_bezier = PathSeg::Line(Line::new(next_bezier.start(), next_bezier.end()));
}
let inverse_transform = transform.inverse();
if index == 0 && next_index == 1 {
first_original_length = bezier.perimeter(DEFAULT_ACCURACY);
first_length = first_original_length;
}
let (original_length, length) = if index == 0 {
(bezier.perimeter(DEFAULT_ACCURACY), bezier.perimeter(DEFAULT_ACCURACY))
} else {
(prev_original_length, prev_length)
};
let (next_original_length, mut next_length) = if index == segment_count - 1 && next_index == 0 {
(first_original_length, first_length)
} else {
(next_bezier.perimeter(DEFAULT_ACCURACY), next_bezier.perimeter(DEFAULT_ACCURACY))
};
// Only split if the length is big enough to make it worthwhile
let valid_length = length > 1e-10;
if segments_connected[end_point] > 0 && valid_length {
// Apply the bevel to the end
let distance = calculated_split_distance.min(original_length.min(next_original_length) / 2.);
bezier = split_distance(bezier.reverse(), distance, length).reverse();
if index == 0 && next_index == 1 {
first_length = (length - distance).max(0.);
}
// Update the end position
let pos = inverse_transform.transform_point2(point_to_dvec2(bezier.end()));
create_or_modify_point(working, segments_connected, pos, &mut end_point, &mut next_id, &mut new_segments);
working.segment_end[segment] = end_point;
}
// Update the handles
working.segment_handles[segment] = segment_to_handles(&bezier).apply_transformation(|p| inverse_transform.transform_point2(p));
// Only split if the length is big enough to make it worthwhile
let valid_length = next_length > 1e-10;
if segments_connected[next_start_point] > 0 && valid_length {
// Apply the bevel to the start
let distance = calculated_split_distance.min(next_original_length.min(original_length) / 2.);
next_bezier = split_distance(next_bezier, distance, next_length);
next_length = (next_length - distance).max(0.);
// Update the start position
let pos = inverse_transform.transform_point2(point_to_dvec2(next_bezier.start()));
create_or_modify_point(working, segments_connected, pos, &mut next_start_point, &mut next_id, &mut new_segments);
working.segment_start[next_segment] = next_start_point;
// Update the handles
working.segment_handles[next_segment] = segment_to_handles(&next_bezier).apply_transformation(|p| inverse_transform.transform_point2(p));
}
prev_original_length = next_original_length;
prev_length = next_length;
}
new_segments
}
fn insert_new_segments(working: &mut WorkingVector, new_segments: &[[usize; 2]]) {
let mut next_id = next_working_segment_id(working);
for &[start, end] in new_segments {
let handles = BezierHandles::Linear;
push_working_segment(working, next_id.next_id(), start, end, handles);
}
}
if distance <= 1. {
return;
}
if !transform.matrix2.determinant().is_normal() {
return;
}
let mut working = WorkingVector::flatten(vector, paths);
if working.segment_ids.len() > 1 {
let mut segments_connected = segments_connected_count(&working);
let new_segments = update_existing_segments(&mut working, transform, distance, &mut segments_connected);
insert_new_segments(&mut working, &new_segments);
working.reweave(vector, paths);
}
}
#[node_macro::node(category("Vector: Path"), icon("NodeBevel"), path(core_types::vector))]
fn bevel<V: MapVectorItems + Send + Sync + 'static>(
_: impl Ctx,
#[implementations(Graphic, Vector)] source: Item<V>,
#[unit(" px")]
#[hard(0..)]
#[default(10.)]
distance: Item<f64>,
) -> Item<V> {
V::map_vector_items(source, |source| {
let mut source = source;
let distance = *distance.element();
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
edit_item_geometry(&mut source, |vector, paths| bevel_algorithm(vector, paths, transform, distance));
source
})
}
/// Closes every open path with a straight segment from its end back to its start, or by joining the two where they already meet.
#[node_macro::node(category("Vector: Path"), icon("NodeClosePaths"), path(core_types::vector))]
fn close_paths<V: MapVectorItems + Send + Sync + 'static>(
_: impl Ctx,
/// The vector with paths to close.
#[implementations(Graphic, Vector)]
content: Item<V>,
) -> Item<V> {
V::map_vector_items(content, |mut item| {
edit_item_geometry(&mut item, |vector, paths| vector.close_subpaths(paths));
item
})
}
/// Reverses the direction every path runs in.
#[node_macro::node(category("Vector: Path"), icon("NodeReversePaths"), path(core_types::vector))]
fn reverse_paths<V: MapVectorItems + Send + Sync + 'static>(
_: impl Ctx,
/// The vector with paths to reverse.
#[implementations(Graphic, Vector)]
content: Item<V>,
) -> Item<V> {
V::map_vector_items(content, |mut item| {
edit_item_geometry(&mut item, |_, paths| reverse_path_flows(paths));
item
})
}
#[node_macro::node(category("Vector: Measure"), icon("NodePointInside"), path(core_types::vector))]
fn point_inside(_: impl Ctx, source: Item<Vector>, point: Item<DVec2>) -> Item<bool> {
let point = point.into_element();
let paths = paths_from_item_attributes(&source).unwrap_or_else(|| no_paths());
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
let inside = source.element().check_point_inside_shape(paths, transform, point);
Item::new_from_element(inside)
}
// TODO: Return i64 instead of f64 once automatic type conversion is implemented for nodes with generic type inputs, so an integer output doesn't wall this count off from the generic math nodes.
// TODO: (Currently automatic type conversion only works for concrete types, via the Graphene preprocessor and not the full Graphene type system.)
#[node_macro::node(category("Data: List"), icon("NodeCount"), path(graphene_core::vector), footprint_invariant)]
fn count(_: impl Ctx, content: ListDyn) -> Item<f64> {
Item::new_from_element(content.len() as f64)
}
#[node_macro::node(category("Vector: Measure"), icon("NodeCountPoints"), path(graphene_core::vector), footprint_invariant)]
fn count_points(_: impl Ctx, content: Item<Vector>) -> Item<f64> {
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
let count = content.element().anchor_indices(paths).len() as f64;
Item::new_from_element(count)
}
/// Retrieves the vec2 position (in local space) of the anchor point at the specified index within a vector element.
/// If no value exists at that index, the position (0, 0) is returned.
#[node_macro::node(category("Vector: Measure"), icon("NodeIndexPoints"), path(graphene_core::vector), footprint_invariant)]
fn index_points(
_: impl Ctx,
/// The vector element containing the anchor points to be retrieved.
content: Item<Vector>,
/// The index of the points to retrieve, starting from 0 for the first point. Negative indices count backwards from the end, starting from -1 for the last point.
index: Item<i64>,
) -> Item<DVec2> {
let index = index.into_element();
let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths());
let positions = content.element().anchor_positions(paths);
let Some(last_index) = positions.len().checked_sub(1) else {
return Item::new_from_element(DVec2::ZERO);
};
// Clamp and allow negative indexing from the end
let index = if index < 0 {
(positions.len() as i64 + index).max(0) as usize
} else {
index.min(last_index as i64) as usize
};
Item::new_from_element(positions[index])
}
#[node_macro::node(category("Vector: Measure"), icon("NodePathLength"), path(core_types::vector), footprint_invariant)]
fn path_length(_: impl Ctx, source: Item<Vector>) -> Item<f64> {
let paths = paths_from_item_attributes(&source).unwrap_or_else(|| no_paths());
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
let length = source
.element()
.stroke_bezpath_iter(paths)
.map(|mut bezpath| {
bezpath.apply_affine(Affine::new(transform.to_cols_array()));
bezpath.perimeter(DEFAULT_ACCURACY)
})
.sum::<f64>();
Item::new_from_element(length)
}
#[node_macro::node(category("Vector: Measure"), icon("NodeArea"), path(core_types::vector), version(2))]
fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectFootprint, content: impl Node<Context<'static>, Output = Item<Vector>>) -> Result<Item<f64>, Interrupt> {
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
let vector = content.eval(&new_ctx)?;
let transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM);
let area_scale = transform.matrix2.determinant().abs();
let paths = paths_from_item_attributes(&vector).unwrap_or_else(|| no_paths());
let area = vector.element().stroke_bezpath_iter(paths).map(|subpath| subpath.area() * area_scale).sum::<f64>();
Ok(Item::new_from_element(area))
}
#[derive(Debug, thiserror::Error)]
pub enum CentroidError {
#[error("The content has no points to find the centroid of")]
NoPoints,
}
#[node_macro::node(category("Vector: Measure"), icon("NodeCentroid"), path(core_types::vector), version(2))]
fn centroid(
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectFootprint,
content: impl Node<Context<'static>, Output = Item<Vector>>,
centroid_type: Item<CentroidType>,
) -> Result<Item<DVec2>, Interrupt> {
let centroid_type = centroid_type.into_element();
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
let vector = content.eval(&new_ctx)?;
let transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM);
let paths = paths_from_item_attributes(&vector).unwrap_or_else(|| no_paths());
let Some(position) = element_centroid(vector.element(), paths, transform, centroid_type) else {
return Err(NodeError::from(CentroidError::NoPoints).into());
};
Ok(Item::new_from_element(position))
}
/// The area- or length-weighted centroid of one vector element's subpaths, averaging anchor positions when the weights all vanish,
/// or `None` for an element without points. A subpath with non-finite coordinates makes the centroid NaN.
fn element_centroid(element: &Vector, paths: &List<Path>, transform: DAffine2, centroid_type: CentroidType) -> Option<DVec2> {
// All subpath centroid positions added together as if they were vectors from the origin, weighted by area or length
let mut centroid = DVec2::ZERO;
let mut sum = 0.;
for bezpath in element.stroke_bezpath_iter(paths) {
if !bezpath.is_finite() {
return Some(DVec2::NAN);
}
let partial = match centroid_type {
CentroidType::Area => bezpath_area_centroid_and_area(&bezpath, Some(1e-3), Some(1e-3)).filter(|(_, area)| *area > 0.),
CentroidType::Length => bezpath_length_centroid_and_length(&bezpath, None, true),
};
if let Some((path_centroid, area_or_length)) = partial {
sum += area_or_length;
centroid += area_or_length * transform.transform_point2(path_centroid);
}
}
if sum > 0. {
return Some(centroid / sum);
}
// Without a summed denominator, return the average of all positions instead
let positions = element.anchor_positions(paths);
if positions.is_empty() {
return None;
}
Some(positions.iter().map(|&p| transform.transform_point2(p)).sum::<DVec2>() / (positions.len() as f64))
}
#[cfg(test)]
mod test {
use super::*;
use core_types::{Node, Poll};
use kurbo::{CubicBez, ParamCurveNearest, Point, Rect};
use vector_types::vector::algorithms::bezpath_algorithms::{TValue, trim_pathseg};
use vector_types::vector::algorithms::shapes::ellipse_bezpath;
use vector_types::vector::misc::pathseg_abs_diff_eq;
#[derive(Clone)]
pub struct ValueNode<T: Clone>(T);
impl<T: Clone> Node<Footprint> for ValueNode<T> {
type Output = T;
fn eval(&self, _input: &Footprint) -> Poll<T> {
Poll::Final(self.0.clone())
}
}
fn vector_node_from_bezpath(bezpath: BezPath) -> List<Vector> {
List::new_from_item(Vector::item_from_bezpath(&bezpath))
}
/// Stands in for the embedding adapter a compiled graph inserts ahead of a `List<Graphic>` connector.
fn embed_vectors(vectors: List<Vector>) -> List<Graphic> {
vectors.into_iter().map(|item| Item::new_from_element(Graphic::from(item))).collect()
}
fn vector_item_from_bezpath(bezpath: BezPath) -> Item<Vector> {
Vector::item_from_bezpath(&bezpath)
}
fn create_vector_item(bezpath: BezPath, transform: DAffine2) -> Item<Vector> {
Vector::item_from_bezpath(&bezpath).with_attribute(ATTR_TRANSFORM, transform)
}
fn item<T>(value: T) -> Item<T> {
Item::new_from_element(value)
}
/// The paths riding an item, standing in for the empty weave when the item carries none.
fn item_paths<T>(item: &Item<T>) -> &List<Path> {
paths_from_item_attributes(item).unwrap_or_else(|| no_paths())
}
/// The paths riding one list row, standing in for the empty weave when the row carries none.
fn row_paths<T>(list: &List<T>, index: usize) -> &List<Path> {
paths_from_list_row_attributes(list, index).unwrap_or_else(|| no_paths())
}
fn vector_item_from_points(points: &[DVec2]) -> Item<Vector> {
super::points_to_vector((), points.iter().map(|&position| Item::new_from_element(position)).collect())
}
const SQUARE_WITH_CENTER: [DVec2; 5] = [DVec2::new(0., 0.), DVec2::new(10., 0.), DVec2::new(10., 10.), DVec2::new(0., 10.), DVec2::new(5., 5.)];
#[test]
fn points_to_vector_keeps_positions_in_order_and_unconnected() {
let result = vector_item_from_points(&SQUARE_WITH_CENTER);
let paths = shared_paths_from_item_attributes(&result);
assert_eq!(result.element().anchor_positions(&paths), SQUARE_WITH_CENTER);
assert_eq!(result.element().segment_iter(&paths).count(), 0);
}
// The lone handle of a quadratic answers to both anchors, so it moves by the average of their deltas
#[test]
fn point_deltas_carry_a_quadratic_handle_with_both_anchors() {
let mut quadratic = BezPath::new();
quadratic.move_to((0., 0.));
quadratic.quad_to((5., 10.), (10., 0.));
let (mut vector, paths) = Vector::from_bezpath(&quadratic);
let anchors = vector.anchor_indices(&paths);
super::apply_point_deltas(&mut vector, &paths, &anchors, &[DVec2::X, DVec2::X * 3.]);
assert_eq!(vector.position(0), Some(DVec2::new(1., 0.)));
assert_eq!(vector.position(1), Some(DVec2::new(7., 10.)));
assert_eq!(vector.position(2), Some(DVec2::new(13., 0.)));
}
// A point no segment touches still takes its delta, so jitter can shift a bare point cloud
#[test]
fn point_deltas_move_free_floating_points() {
let cloud = vector_item_from_points(&[DVec2::ZERO, DVec2::new(10., 0.)]);
let paths = item_paths(&cloud).clone();
let mut vector = cloud.element().clone();
let anchors = vector.anchor_indices(&paths);
super::apply_point_deltas(&mut vector, &paths, &anchors, &[DVec2::Y, DVec2::Y * 2.]);
assert_eq!(vector.position(0), Some(DVec2::new(0., 1.)));
assert_eq!(vector.position(1), Some(DVec2::new(10., 2.)));
}
// Point 1 is a handle of the first path and an anchor of the second, so it keeps its own delta rather than its neighbor's
#[test]
fn point_deltas_keep_an_anchor_that_is_also_a_handle_on_its_own_delta() {
let mut vector = Vector::default();
for x in 0..7 {
vector.0.push(Item::new_from_element(DVec2::new(x as f64 * 10., 0.)));
}
let mut paths = List::new();
vector_types::vector::push_path(&mut paths, CurveType::Cubic, [0, 1, 2, 3], []);
vector_types::vector::push_path(&mut paths, CurveType::Cubic, [1, 4, 5, 6], []);
let anchors = vector.anchor_indices(&paths);
assert_eq!(anchors, [0, 1, 3, 6]);
super::apply_point_deltas(&mut vector, &paths, &anchors, &[DVec2::X, DVec2::Y, DVec2::X * 2., DVec2::X * 3.]);
assert_eq!(vector.position(1), Some(DVec2::new(10., 1.)));
assert_eq!(vector.position(2), Some(DVec2::new(22., 0.)));
assert_eq!(vector.position(4), Some(DVec2::new(40., 1.)));
assert_eq!(vector.position(5), Some(DVec2::new(53., 0.)));
}
#[test]
fn offset_path_does_not_duplicate_closing_anchors() {
// Offsetting closed triangles must not leave each subpath with a redundant start/end anchor (a Kurbo offset
// contour returns to approximately, not exactly, its start; that near-coincident point must close, not duplicate).
let delaunay = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).unwrap();
let offset = super::offset_path((), delaunay, item(0.5), item(StrokeJoin::Miter), item(4.)).unwrap();
let paths = item_paths(&offset);
let result = offset.element();
let mut subpaths = 0;
for (group, closed) in result.stroke_manipulator_groups(paths) {
subpaths += 1;
assert!(closed, "offset of a closed triangle should stay closed");
let first = group.first().unwrap().anchor;
let last = group.last().unwrap().anchor;
assert!(first.distance(last) > 1e-6, "closed subpath has a duplicated start/end anchor: {first:?} ~= {last:?}");
}
assert!(subpaths > 0);
}
#[test]
fn delaunay_disconnected_cells_make_one_subpath_per_triangle() {
let result = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).unwrap();
let paths = item_paths(&result);
let vector = result.element();
// The square plus its center tessellates into four triangles, each its own closed subpath.
assert_eq!(vector.stroke_manipulator_groups(paths).filter(|(_, closed)| *closed).count(), 4);
assert_eq!(vector.segment_ids(paths).len(), 4 * 3);
assert_eq!(vector.anchor_indices(paths).len(), 4 * 3);
assert!(!vector.use_face_fill(paths));
}
#[test]
fn delaunay_and_voronoi_cells_share_winding() {
fn signed_area(anchors: &[DVec2]) -> f64 {
(0..anchors.len()).map(|i| anchors[i].perp_dot(anchors[(i + 1) % anchors.len()])).sum::<f64>() / 2.
}
fn subpath_winding_signs(vector: &Vector, paths: &List<Path>) -> Vec<f64> {
vector
.stroke_manipulator_groups(paths)
.map(|(group, _)| signed_area(&group.iter().map(|g| g.anchor).collect::<Vec<_>>()).signum())
.collect()
}
// The Rectangle and Ellipse generators define the framework's fill winding convention, built from these
// shape constructors (`rectangle_bezpath` / `ellipse_bezpath`), so their winding is the source of truth.
use vector_types::vector::algorithms::shapes::{ellipse_bezpath, rectangle_bezpath};
let (rectangle, rectangle_paths) = Vector::from_bezpath(&rectangle_bezpath(DVec2::new(-50., -50.), DVec2::new(50., 50.)));
let (ellipse, ellipse_paths) = Vector::from_bezpath(&ellipse_bezpath(DVec2::new(-50., -25.), DVec2::new(50., 25.)));
let expected = subpath_winding_signs(&rectangle, &rectangle_paths)[0];
assert_eq!(subpath_winding_signs(&ellipse, &ellipse_paths)[0], expected, "Rectangle and Ellipse should agree on winding");
// Delaunay and Voronoi must emit subpaths that wind the same way as those generators.
let delaunay = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).unwrap();
let voronoi = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).unwrap();
for sign in subpath_winding_signs(delaunay.element(), item_paths(&delaunay)) {
assert_eq!(sign, expected, "Delaunay subpath winding should match the Rectangle/Ellipse generators");
}
for sign in subpath_winding_signs(voronoi.element(), item_paths(&voronoi)) {
assert_eq!(sign, expected, "Voronoi subpath winding should match the Rectangle/Ellipse generators");
}
}
#[test]
fn delaunay_shared_mesh_welds_points_and_shares_edges() {
let result = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)).unwrap();
let paths = item_paths(&result);
let vector = result.element();
// The connected mesh reuses the five input points and shares edges, so it fills face by face.
assert!(vector.use_face_fill(paths));
assert_eq!(vector.anchor_indices(paths).len(), 5);
// Four hull edges plus four spokes to the center, each emitted once.
assert_eq!(vector.segment_ids(paths).len(), 8);
}
#[test]
fn voronoi_disconnected_cells_make_a_subpath_per_cell() {
let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).unwrap();
let paths = item_paths(&result);
let vector = result.element();
let cells = vector.stroke_manipulator_groups(paths).filter(|(_, closed)| *closed).count();
assert!(cells > 0, "expected at least one Voronoi cell");
// Every cell is a closed subpath, so segments and points come in matched per-cell loops.
assert_eq!(vector.segment_ids(paths).len(), vector.anchor_indices(paths).len());
// Clipping to the convex hull keeps all cell vertices within the input bounds.
for position in vector.anchor_positions(paths) {
assert!(position.x >= -1e-6 && position.x <= 10. + 1e-6);
assert!(position.y >= -1e-6 && position.y <= 10. + 1e-6);
}
}
#[test]
fn voronoi_shared_mesh_uses_face_fill() {
let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)).unwrap();
let paths = item_paths(&result);
let vector = result.element();
assert!(vector.use_face_fill(paths));
assert!(!vector.segment_ids(paths).is_empty());
}
#[test]
fn voronoi_leaves_degenerate_input_untouched() {
// Two points cannot form a diagram, so the element passes through unchanged.
let points = [DVec2::new(0., 0.), DVec2::new(1., 1.)];
let result = super::voronoi_cells((), vector_item_from_points(&points), item(false)).unwrap();
let paths = item_paths(&result);
let vector = result.element();
assert_eq!(vector.anchor_indices(paths).len(), 2);
assert_eq!(vector.segment_ids(paths).len(), 0);
}
#[test]
fn relax_points_redistributes_anchors() {
// Four hull corners plus two off-center interior points.
let points = [
DVec2::new(0., 0.),
DVec2::new(10., 0.),
DVec2::new(10., 10.),
DVec2::new(0., 10.),
DVec2::new(3., 4.),
DVec2::new(7., 5.),
];
let result = super::relax_points((), vector_item_from_points(&points), item(2.)).unwrap();
let positions = result.element().anchor_positions(item_paths(&result));
// Relaxation preserves the point count but repositions the interior anchors within the hull.
assert_eq!(positions.len(), points.len());
assert_ne!(positions, points);
// The convex-hull corners are pinned. Asserted on the count first, since zipping a short result
// would skip the checks rather than fail them.
assert!(positions.len() >= 4, "the relaxed hull should still have its four corners");
for (corner, (&position, &point)) in positions.iter().zip(&points).take(4).enumerate() {
assert_eq!(position, point, "hull corner {corner} should be pinned");
}
for point in positions {
assert!(point.x >= -1e-6 && point.x <= 10. + 1e-6);
assert!(point.y >= -1e-6 && point.y <= 10. + 1e-6);
}
}
#[test]
fn bounding_box() {
let bounding_box = super::bounding_box((), Vector::item_from_bezpath(&Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY)));
let paths = item_paths(&bounding_box);
let bounding_box = bounding_box.element();
assert_eq!(bounding_box.stroke_manipulator_groups(paths).count(), 1);
let manipulator_groups_anchors = bounding_box
.stroke_manipulator_groups(paths)
.next()
.unwrap()
.0
.iter()
.map(|manipulators| manipulators.anchor)
.collect::<Vec<DVec2>>();
assert_eq!(&manipulator_groups_anchors[..4], &[DVec2::NEG_ONE, DVec2::new(1., -1.), DVec2::ONE, DVec2::new(-1., 1.),]);
// Test a rectangular path with nonzero rotation
let square = Vector::item_from_bezpath(&Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY));
let mut square = List::new_from_item(square);
square.with_attribute_mut_or_default(ATTR_TRANSFORM, 0, |t: &mut DAffine2| *t *= DAffine2::from_angle(std::f64::consts::FRAC_PI_4));
let bounding_box = BoundingBoxNodeMapped { content: ValueNode(square) }.eval(&Footprint::default()).value().unwrap();
let paths = row_paths(&bounding_box, 0);
let bounding_box = bounding_box.element(0).unwrap();
assert_eq!(bounding_box.stroke_manipulator_groups(paths).count(), 1);
let manipulator_groups_anchors = bounding_box
.stroke_manipulator_groups(paths)
.next()
.unwrap()
.0
.iter()
.map(|manipulators| manipulators.anchor)
.collect::<Vec<DVec2>>();
let expected_bounding_box = [DVec2::NEG_ONE, DVec2::new(1., -1.), DVec2::ONE, DVec2::new(-1., 1.)];
for i in 0..4 {
assert_eq!(manipulator_groups_anchors[i], expected_bounding_box[i]);
}
}
#[test]
fn vector_to_points() {
let square = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY);
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(2.), 0., DVec2::new(5., 7.));
let points = super::vector_to_points((), create_vector_item(square, transform));
let positions: Vec<DVec2> = points.iter_element_values().copied().collect();
assert_eq!(positions, [DVec2::new(-15., -13.), DVec2::new(25., -13.), DVec2::new(25., 27.), DVec2::new(-15., 27.)]);
}
#[test]
fn vector_to_points_and_open_ends_keep_point_attributes() {
use core_types::list::{ATTR_DEPTH, ATTR_HEADING, ATTR_KIND};
// A trunk with a branch to the left, placed 100 px to the right
let tree = crate::turtle::turtle_path("F[+F]F", &Default::default()).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(100., 0.)));
let points = super::vector_to_points((), tree.clone());
assert_eq!(points.iter_element_values().count(), 4);
assert_eq!(
points.iter_attribute_values::<i64>(ATTR_DEPTH).map(|depths| depths.copied().collect::<Vec<_>>()),
Some(vec![0, 0, 1, 0])
);
// The root and both tips, but not the junction where the branch leaves the trunk
let ends = super::open_ends((), tree);
let positions: Vec<DVec2> = ends.iter_element_values().copied().collect();
assert_eq!(positions, [DVec2::new(100., 0.), DVec2::new(90., -10.), DVec2::new(100., -20.)]);
assert_eq!(
ends.iter_attribute_values::<f64>(ATTR_HEADING).map(|headings| headings.copied().collect::<Vec<_>>()),
Some(vec![-90., 180., -90.])
);
// A closed path has no open ends
let square = crate::turtle::turtle_path("F+F+F+F", &Default::default());
assert_eq!(super::open_ends((), square).len(), 0);
// A point placed by `.` outside a shape is listed with the anchors, but isn't an open end
let marked = crate::turtle::turtle_path("F.(3)", &Default::default());
assert_eq!(
super::vector_to_points((), marked.clone())
.iter_attribute_values::<i64>(ATTR_KIND)
.map(|kinds| kinds.copied().collect::<Vec<_>>()),
Some(vec![0, 0, 3])
);
assert_eq!(super::open_ends((), marked).len(), 2);
}
fn convex_hull_of(bezpath: BezPath, transform: DAffine2, curvature: f64) -> Item<Vector> {
let hull = super::convex_hull((), create_vector_item(bezpath, transform), item(curvature));
assert_eq!(hull.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM), transform, "the hull should keep its item's transform");
hull
}
fn enclosed_area(content: &Item<Vector>) -> f64 {
content.element().stroke_bezpath_iter(item_paths(content)).map(|bezpath| bezpath.area().abs()).sum()
}
/// Two squares far apart and a floating point above them, all in one item.
fn two_squares_and_a_point() -> BezPath {
let mut content = Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY);
content.extend(Rect::new(100., 0., 110., 10.).path_elements(DEFAULT_ACCURACY));
content.move_to((50., 200.));
content
}
/// A square with a rectangular notch cut into the middle of one edge.
fn notched_square(size: f64, notch_width: f64, notch_depth: f64) -> BezPath {
let (left, right) = ((size - notch_width) / 2., (size + notch_width) / 2.);
BezPath::from_vec(vec![
PathEl::MoveTo(Point::new(0., 0.)),
PathEl::LineTo(Point::new(size, 0.)),
PathEl::LineTo(Point::new(size, size)),
PathEl::LineTo(Point::new(right, size)),
PathEl::LineTo(Point::new(right, size - notch_depth)),
PathEl::LineTo(Point::new(left, size - notch_depth)),
PathEl::LineTo(Point::new(left, size)),
PathEl::LineTo(Point::new(0., size)),
PathEl::ClosePath,
])
}
#[test]
fn convex_hull_at_zero_curvature_wraps_every_path_and_floating_point() {
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(1.5), 0.4, DVec2::new(30., -20.));
let hull = convex_hull_of(two_squares_and_a_point(), transform, 0.);
// The hull is the pentagon spanning both squares' outer corners and the floating point
let positions = hull.element().anchor_positions(item_paths(&hull));
assert_eq!(positions.len(), 5, "expected a pentagon, got anchors at {positions:?}");
for expected in [DVec2::new(0., 0.), DVec2::new(110., 0.), DVec2::new(110., 10.), DVec2::new(50., 200.), DVec2::new(0., 10.)] {
assert!(positions.iter().any(|position| position.distance(expected) < 1e-6), "expected a hull anchor near {expected}");
}
}
#[test]
fn convex_hull_curvature_separates_parts_farther_apart_than_the_ball() {
let hull = convex_hull_of(two_squares_and_a_point(), DAffine2::IDENTITY, 1. / 20.);
// Each square gets a hull of its own, and the floating point stays behind as an anchor
let hulls: Vec<BezPath> = hull.element().stroke_bezpath_iter(item_paths(&hull)).filter(|bezpath| bezpath.segments().next().is_some()).collect();
assert_eq!(hulls.len(), 2, "expected one hull per square, got {hulls:?}");
assert!((enclosed_area(&hull) - 200.).abs() < 1e-6, "expected the two squares' area, got {}", enclosed_area(&hull));
let positions = hull.element().anchor_positions(item_paths(&hull));
assert!(
positions.iter().any(|position| position.distance(DVec2::new(50., 200.)) < 1e-6),
"the floating point should remain, got {positions:?}"
);
}
#[test]
fn convex_hull_strands_share_anchors_with_the_regions_they_meet() {
// A ring of points with a tail, each point too close to the next for a ball of radius 30 to pass
let mut points: Vec<DVec2> = (0..12).map(|i| DVec2::from_angle(i as f64 * PI / 6.) * 100.).collect();
points.extend([DVec2::new(150., 0.), DVec2::new(200., 0.)]);
let hull = super::convex_hull((), vector_item_from_points(&points), item(1. / 30.));
// The tail is traced once, setting out from the ring's own anchor rather than a copy of it
let paths = item_paths(&hull);
let positions = hull.element().anchor_positions(paths);
assert_eq!(positions.len(), points.len(), "expected every point once, got {positions:?}");
assert_eq!(hull.element().segment_iter(paths).count(), 12 + 2);
}
#[test]
fn convex_hull_curvature_lets_the_ball_into_dents_wider_than_itself() {
let notched = notched_square(100., 40., 60.);
// A ball wider than the notch bridges its mouth, giving the full square
assert!((enclosed_area(&convex_hull_of(notched.clone(), DAffine2::IDENTITY, 0.)) - 10_000.).abs() < 1e-6);
assert!((enclosed_area(&convex_hull_of(notched.clone(), DAffine2::IDENTITY, 1. / 30.)) - 10_000.).abs() < 1e-6);
// A ball of radius 10 enters the notch and cuts each of its inner corners with a chord, filling a triangle of area 50
let area = enclosed_area(&convex_hull_of(notched, DAffine2::IDENTITY, 1. / 10.));
assert!((area - (10_000. - 40. * 60. + 2. * 50.)).abs() < 1e-3, "expected the notch to be kept, got an area of {area}");
}
#[test]
fn convex_hull_ball_is_sized_in_the_items_parent_space() {
// The notch is 15 wide locally, too narrow for a ball of radius 10, but twice that once the transform widens it
let notched = notched_square(50., 15., 30.);
// Scaled uniformly by 2, each corner's triangle of area 50 is a quarter of that locally
let similarity = DAffine2::from_scale_angle_translation(DVec2::splat(2.), 0.7, DVec2::new(-40., 25.));
let area = enclosed_area(&convex_hull_of(notched.clone(), similarity, 1. / 10.));
assert!((area - (2500. - 15. * 30. + 2. * 12.5)).abs() < 1e-3, "expected the notch to be kept, got an area of {area}");
// Stretched along one axis, the round ball is an ellipse locally, and each corner's triangle is half its area of 50
let stretch = DAffine2::from_scale(DVec2::new(2., 1.));
let area = enclosed_area(&convex_hull_of(notched, stretch, 1. / 10.));
assert!((area - (2500. - 15. * 30. + 2. * 25.)).abs() < 1e-3, "expected the notch to be kept, got an area of {area}");
}
#[test]
fn sample_polyline() {
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
let sample_polyline = super::sample_polyline(
Footprint::default(),
vector_item_from_bezpath(path),
Item::new_from_element(PointSpacingType::Separation),
Item::new_from_element(30.),
Item::new_from_element(0),
Item::new_from_element(0.),
Item::new_from_element(0.),
Item::new_from_element(false),
)
.unwrap();
let positions = sample_polyline.element().anchor_positions(item_paths(&sample_polyline));
assert_eq!(positions.len(), 4);
for (pos, expected) in positions.iter().zip([DVec2::X * 0., DVec2::X * 30., DVec2::X * 60., DVec2::X * 90.]) {
assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}");
}
}
#[test]
fn sample_polyline_adaptive_spacing() {
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
let sample_polyline = super::sample_polyline(
Footprint::default(),
vector_item_from_bezpath(path),
Item::new_from_element(PointSpacingType::Separation),
Item::new_from_element(18.),
Item::new_from_element(0),
Item::new_from_element(45.),
Item::new_from_element(10.),
Item::new_from_element(true),
)
.unwrap();
let positions = sample_polyline.element().anchor_positions(item_paths(&sample_polyline));
assert_eq!(positions.len(), 4);
for (pos, expected) in positions.iter().zip([DVec2::X * 45., DVec2::X * 60., DVec2::X * 75., DVec2::X * 90.]) {
assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}");
}
}
#[test]
fn poisson() {
let poisson_points = super::scatter_points(
Footprint::default(),
vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.))),
Item::new_from_element(10. * std::f64::consts::SQRT_2),
Item::new_from_element(0),
)
.expect("the separation should fit the circle");
let positions = poisson_points.element().anchor_positions(item_paths(&poisson_points));
assert!((20..=40).contains(&positions.len()), "actual len {}", positions.len());
for point in positions {
assert!(point.length() < 50. + 1., "Expected point in circle {point}")
}
}
#[test]
fn path_length() {
let bezpath = Rect::new(100., 100., 201., 201.).to_path(DEFAULT_ACCURACY);
let transform = DAffine2::from_scale(DVec2::new(2., 2.));
let item = create_vector_item(bezpath, transform);
let length = super::path_length(Footprint::default(), item);
// 101 (each rectangle edge length) * 4 (rectangle perimeter) * 2 (scale)
assert_eq!(length.into_element(), 101. * 4. * 2.);
}
#[test]
fn spline() {
let spline = super::spline(Footprint::default(), vector_item_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)));
let paths = item_paths(&spline);
let spline = spline.element();
assert_eq!(spline.stroke_bezpath_iter(paths).count(), 1);
assert_eq!(spline.anchor_positions(paths), [DVec2::ZERO, DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)]);
assert_eq!(spline.colinear_pairs(paths).len(), 4, "every anchor of the closed spline should be smooth");
// An open spline is smooth only between its ends
let mut open = BezPath::new();
open.move_to((0., 0.));
open.line_to((10., 10.));
open.line_to((20., 0.));
open.line_to((30., 10.));
let spline = super::spline(Footprint::default(), vector_item_from_bezpath(open));
assert_eq!(smooth_anchors_by_contour(&spline), [[false, true, true, false]]);
}
// A curved source's handles are replaced by the spline's own rather than kept alongside them
#[test]
fn spline_replaces_the_handles_of_a_curved_source() {
let ellipse = vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.)));
let anchors = ellipse.element().anchor_positions(item_paths(&ellipse));
assert_eq!(anchors.len(), 4);
let spline = super::spline(Footprint::default(), ellipse);
let paths = item_paths(&spline);
let spline = spline.element();
assert_eq!(spline.anchor_positions(paths), anchors);
assert_eq!(spline.segment_iter(paths).count(), 4);
assert_eq!(spline.point_count(), 4 + 4 * 2, "each of the four spans should hold two new handles and no old ones");
}
// Only the source's anchors become corners, joined by lines in their stored order
#[test]
fn points_to_polyline_joins_the_anchors_with_lines() {
let ellipse = vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.)));
let anchors = ellipse.element().anchor_positions(item_paths(&ellipse));
let closed = super::points_to_polyline(Footprint::default(), ellipse.clone(), item(true));
let paths = item_paths(&closed);
let segments: Vec<PathSeg> = closed.element().segment_iter(paths).map(|(_, segment, ..)| segment).collect();
assert_eq!(closed.element().point_count(), anchors.len(), "the source's handles should be dropped");
assert_eq!(closed.element().anchor_positions(paths), anchors);
assert_eq!(segments.len(), 4);
assert!(segments.iter().all(|segment| matches!(segment, PathSeg::Line(_))));
assert!(closed.element().stroke_bezpath_iter(paths).all(|bezpath| bezpath.elements().last() == Some(&PathEl::ClosePath)));
let open = super::points_to_polyline(Footprint::default(), ellipse, item(false));
assert_eq!(open.element().segment_iter(item_paths(&open)).count(), 3);
// Two points have nowhere to close back to, so they draw one segment either way
let pair = super::points_to_polyline(Footprint::default(), vector_item_from_points(&[DVec2::ZERO, DVec2::X]), item(true));
assert_eq!(pair.element().segment_iter(item_paths(&pair)).count(), 1);
}
/// Whether each anchor keeps a smooth tangent pair, contour by contour.
fn smooth_anchors_by_contour(item: &Item<Vector>) -> Vec<Vec<bool>> {
use vector_types::vector::misc::ManipulatorPointId;
let (vector, paths) = (item.element(), item_paths(item));
vector
.stroke_manipulator_groups(paths)
.map(|(group, _)| group.iter().map(|manipulators| vector.colinear(paths, ManipulatorPointId::Anchor(manipulators.id))).collect())
.collect()
}
// Existing handles are kept, so only the anchors without them are tangented and smooth
#[test]
fn smooth_anchors_marks_the_tangented_anchors_smooth() {
let mut bezpath = BezPath::new();
bezpath.move_to((0., 0.));
bezpath.line_to((10., 10.));
bezpath.line_to((20., 0.));
bezpath.line_to((30., 10.));
bezpath.move_to((100., 0.));
bezpath.line_to((150., 0.));
bezpath.line_to((125., 40.));
bezpath.close_path();
bezpath.move_to((200., 0.));
bezpath.curve_to((210., -20.), (240., 30.), (250., 0.));
bezpath.line_to((250., 50.));
bezpath.line_to((200., 50.));
bezpath.close_path();
let output = super::smooth_anchors((), vector_item_from_bezpath(bezpath), item(0.5), item(true));
assert_eq!(
smooth_anchors_by_contour(&output),
[vec![false, true, true, false], vec![true, true, true], vec![false, false, true, true]]
);
}
// Spreading by nothing is a no-op when the source's handles are preserved, so its curves keep their type and shape
#[test]
fn smooth_anchors_spread_of_zero_keeps_the_source_curves() {
let mut bezpath = BezPath::new();
bezpath.move_to((0., 0.));
bezpath.curve_to((50., 0.), (100., 0.), (100., 0.));
bezpath.curve_to((100., 0.), (75., 100.), (50., 100.));
bezpath.curve_to((25., 100.), (0., 0.), (0., 0.));
bezpath.close_path();
let source = vector_item_from_bezpath(bezpath);
let output = super::smooth_anchors((), source.clone(), item(0.), item(true));
let segments = |item: &Item<Vector>| item.element().segment_iter(item_paths(item)).map(|(_, segment, ..)| segment).collect::<Vec<_>>();
assert_eq!(segments(&output), segments(&source));
}
// A loop of one segment has no neighbor to share a tangent with, so it passes through unchanged
#[test]
fn smooth_anchors_keeps_a_single_segment_loop() {
let teardrop = CubicBez::new((0., 0.), (50., -50.), (100., 50.), (0., 0.));
let mut bezpath = BezPath::new();
bezpath.move_to(teardrop.p0);
bezpath.curve_to(teardrop.p1, teardrop.p2, teardrop.p3);
bezpath.close_path();
bezpath.move_to((200., 0.));
bezpath.line_to((250., 0.));
bezpath.line_to((225., 40.));
bezpath.close_path();
let output = super::smooth_anchors((), vector_item_from_bezpath(bezpath), item(0.5), item(true));
let paths = item_paths(&output);
let segments: Vec<PathSeg> = output.element().segment_iter(paths).map(|(_, segment, ..)| segment).collect();
assert_eq!(segments.len(), 4);
assert!(segments.contains(&PathSeg::Cubic(teardrop)), "the loop should keep its curve, not among {segments:?}");
assert_eq!(smooth_anchors_by_contour(&output), [vec![false], vec![true, true, true]]);
}
// A spur setting out from an anchor of a loop stays welded to it, keeping the mesh a mesh rather than a loop and a loose open path
#[test]
fn smooth_anchors_keeps_a_mesh_welded() {
let mut mesh = BezPath::new();
mesh.move_to((0., 0.));
mesh.line_to((100., 0.));
mesh.line_to((50., 80.));
mesh.close_path();
mesh.move_to((100., 0.));
mesh.line_to((160., -30.));
mesh.line_to((200., 10.));
let (vector, paths) = Vector::from_bezpath_welded(&mesh);
let mut source = item(vector);
source.set_paths(paths);
assert!(source.element().is_branching(item_paths(&source)));
let output = super::smooth_anchors((), source, item(0.5), item(true));
let paths = item_paths(&output);
assert!(output.element().is_branching(paths), "the spur should still set out from the loop's anchor");
assert_eq!(output.element().anchor_positions(paths).len(), 5);
assert_eq!(output.element().segment_iter(paths).count(), 5);
}
#[test]
fn morph() {
let mut rectangles = vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
let mut second_rectangle = rectangles.clone_item(0).unwrap();
*second_rectangle.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM) *= DAffine2::from_translation((-100., -100.).into());
rectangles.push(second_rectangle);
let morphed = super::morph(
Footprint::default(),
embed_vectors(rectangles),
Item::new_from_element(0.5),
Item::new_from_element(false),
Item::new_from_element(InterpolationDistribution::default()),
Item::default(),
)
.unwrap();
let morphed = List::new_from_item(morphed);
let morphed_positions = morphed.element(0).unwrap().anchor_positions(row_paths(&morphed, 0));
// Geometry stays in local space (original rectangle coordinates)
assert_eq!(&morphed_positions[..4], vec![DVec2::new(0., 0.), DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)]);
// The interpolated transform carries the midpoint translation (approximate due to arc-length parameterization)
assert!((morphed.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0).translation - DVec2::new(-50., -50.)).length() < 1e-3);
}
#[test]
fn morph_interpolates_fill() {
let rect = || Vector::item_from_bezpath(&Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
let solid_fill = |color: Color| Appearance::new_single(Coverage::new_fill(), Graphic::from(List::new_from_element(color)));
let item_a = rect().with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY).with_attribute(ATTR_APPEARANCE, solid_fill(Color::RED));
let item_b = rect()
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation((-100., -100.).into()))
.with_attribute(ATTR_APPEARANCE, solid_fill(Color::BLUE));
let mut content = List::new_from_item(item_a);
content.push(item_b);
let morphed = super::morph(
Footprint::default(),
embed_vectors(content),
Item::new_from_element(0.5),
Item::new_from_element(false),
Item::new_from_element(InterpolationDistribution::default()),
Item::default(),
)
.unwrap();
let morphed = List::new_from_item(morphed);
let appearance = morphed.attribute::<Appearance>(ATTR_APPEARANCE, 0).expect("Morph should keep the appearance at the midpoint");
let fill = appearance.first_paint_of(Cover::Fill).expect("Morph should keep the fill paint at the midpoint");
// Interpolated color between red and blue should have >0 value on both R and B
let Graphic::Color(color) = fill else {
panic!("Expected a solid color fill, got {fill:?}");
};
let color = *color.element();
assert!(color.r() > 0. && color.b() > 0., "Fill should be a red-to-blue blend, got {color:?}");
}
#[test]
fn morph_pairs_appearance_coverages_by_cover() {
let rect = || Vector::item_from_bezpath(&Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
let paint_color = |appearance: &Appearance, cover| {
let paint = appearance.first_paint_of(cover).expect("Morph should keep both paints at the midpoint");
let Graphic::Color(color) = paint else {
panic!("Expected a solid color paint, got {paint:?}");
};
*color.element()
};
// The two endpoints list their covers in opposite paint orders, which pairing by position would cross
let appearance = |fill: Color, stroke: Color, stroke_placement| {
let mut appearance = Appearance::default();
appearance.replace_or_insert(Coverage::new_fill(), Graphic::from(List::new_from_element(fill)), DAffine2::IDENTITY, CoverPlacement::Above);
appearance.replace_or_insert(
Coverage::new_stroke(&Stroke::new(4.)),
Graphic::from(List::new_from_element(stroke)),
DAffine2::IDENTITY,
stroke_placement,
);
appearance
};
let item_a = rect()
.with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY)
.with_attribute(ATTR_APPEARANCE, appearance(Color::RED, Color::BLACK, CoverPlacement::Above));
let item_b = rect()
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation((-100., -100.).into()))
.with_attribute(ATTR_APPEARANCE, appearance(Color::BLUE, Color::WHITE, CoverPlacement::Below));
let mut content = List::new_from_item(item_a);
content.push(item_b);
let morphed = super::morph(
Footprint::default(),
embed_vectors(content),
Item::new_from_element(0.5),
Item::new_from_element(false),
Item::new_from_element(InterpolationDistribution::default()),
Item::default(),
)
.unwrap();
let morphed = List::new_from_item(morphed);
let appearance = morphed.attribute::<Appearance>(ATTR_APPEARANCE, 0).expect("Morph should keep the appearance at the midpoint");
assert_eq!(appearance.len(), 2, "the midpoint should hold one fill and one stroke, not a duplicated cover");
let fill = paint_color(appearance, Cover::Fill);
assert!(fill.r() > 0. && fill.b() > 0. && fill.g() == 0., "the fill should interpolate against the other fill, got {fill:?}");
let stroke = paint_color(appearance, Cover::Stroke);
assert!(
stroke.r() > 0. && stroke.r() == stroke.g() && stroke.g() == stroke.b(),
"the stroke should interpolate against the other stroke, got {stroke:?}"
);
}
#[track_caller]
fn contains_segment(vector: &Vector, paths: &List<Path>, target: PathSeg) {
let segments = vector.segment_iter(paths).map(|x| x.1);
let count = segments
.filter(|segment| pathseg_abs_diff_eq(*segment, target, 0.01) || pathseg_abs_diff_eq(segment.reverse(), target, 0.01))
.count();
assert_eq!(
count,
1,
"Expected exactly one matching segment for {target:?}, but found {count}. The given segments are: {:#?}",
vector.segment_iter(paths).collect::<Vec<_>>()
);
}
#[test]
fn bevel_rect() {
let source = Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY);
let beveled = super::bevel(Footprint::default(), vector_item_from_bezpath(source), Item::new_from_element(2_f64.sqrt() * 10.));
let paths = item_paths(&beveled);
let beveled = beveled.element();
assert_eq!(beveled.anchor_positions(paths).len(), 8);
assert_eq!(beveled.segment_ids(paths).len(), 8);
// Segments
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(10., 0.), Point::new(90., 0.))));
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(90., 100.))));
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(0., 10.), Point::new(0., 90.))));
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 10.), Point::new(100., 90.))));
// Joins
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(10., 0.), Point::new(0., 10.))));
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(90., 0.), Point::new(100., 10.))));
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 90.), Point::new(90., 100.))));
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(0., 90.))));
}
#[test]
fn bevel_open_curve() {
let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.)));
let mut source = BezPath::new();
source.move_to(Point::new(-100., 0.));
source.line_to(Point::ZERO);
source.push(curve.as_path_el());
let beveled = super::bevel((), vector_item_from_bezpath(source), Item::new_from_element(2_f64.sqrt() * 10.));
let paths = item_paths(&beveled);
let beveled = beveled.element();
assert_eq!(beveled.anchor_positions(paths).len(), 4);
assert_eq!(beveled.segment_ids(paths).len(), 3);
// Segments
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(-8.2, 0.), Point::new(-100., 0.))));
let trimmed = trim_pathseg(curve, TValue::Euclidean(8.2 / curve.perimeter(DEFAULT_ACCURACY)), TValue::Parametric(1.)).unwrap();
contains_segment(beveled, paths, trimmed);
// Join
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start())));
}
#[test]
fn bevel_with_transform() {
let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.)));
let mut source = BezPath::new();
source.move_to(Point::new(-100., 0.));
source.line_to(Point::ZERO);
source.push(curve.as_path_el());
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(10.), 1., DVec2::new(99., 77.));
let vector_item = Vector::item_from_bezpath(&source).with_attribute(ATTR_TRANSFORM, transform);
let beveled = super::bevel((), vector_item, Item::new_from_element(2_f64.sqrt() * 100.));
let paths = item_paths(&beveled);
let beveled = beveled.element();
assert_eq!(beveled.anchor_positions(paths).len(), 4);
assert_eq!(beveled.segment_ids(paths).len(), 3);
// Segments
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(-8.2, 0.), Point::new(-100., 0.))));
let trimmed = trim_pathseg(curve, TValue::Euclidean(8.2 / curve.perimeter(DEFAULT_ACCURACY)), TValue::Parametric(1.)).unwrap();
contains_segment(beveled, paths, trimmed);
// Join
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start())));
}
#[test]
fn bevel_too_high() {
let mut source = BezPath::new();
source.move_to(Point::ZERO);
source.line_to(Point::new(100., 0.));
source.line_to(Point::new(100., 100.));
source.line_to(Point::new(0., 100.));
let beveled = super::bevel(Footprint::default(), vector_item_from_bezpath(source), Item::new_from_element(999.));
let paths = item_paths(&beveled);
let beveled = beveled.element();
assert_eq!(beveled.anchor_positions(paths).len(), 6);
assert_eq!(beveled.segment_ids(paths).len(), 5);
// Segments
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(0., 0.), Point::new(50., 0.))));
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(100., 50.))));
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.))));
// Joins
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(50., 0.), Point::new(100., 50.))));
contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.))));
}
#[test]
fn bevel_repeated_point() {
let line = PathSeg::Line(Line::new(Point::ZERO, Point::new(100., 0.)));
let point = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::ZERO, Point::ZERO, Point::new(100., 0.)));
let curve = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::new(110., 0.), Point::new(110., 200.), Point::new(200., 0.)));
let subpath = BezPath::from_path_segments([line, point, curve].into_iter());
let beveled_item = super::bevel(Footprint::default(), vector_item_from_bezpath(subpath), Item::new_from_element(5.));
let paths = item_paths(&beveled_item);
let beveled = beveled_item.element();
assert_eq!(beveled.anchor_positions(paths).len(), 6);
assert_eq!(beveled.segment_ids(paths).len(), 5);
}
// A rank-0 vector reaches the same per-list styling path as a vector list, rather than being skipped
#[test]
fn vary_fill_colors_reaches_rank_0_vector_graphics() {
let leaf = Graphic::Vector(Box::new(vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY))));
let content = List::new_from_element(leaf);
let styled = super::vary_fill_colors(
Footprint::default(),
content,
Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])),
Item::new_from_element(false),
Item::new_from_element(false),
Item::new_from_element(0),
Item::new_from_element(0_i64),
)
.unwrap();
let Some(Graphic::Vector(item)) = styled.element(0) else {
panic!("the leaf should stay a rank-0 vector")
};
let appearance = item.attribute::<Appearance>(ATTR_APPEARANCE).expect("the leaf should have gained an appearance");
assert!(appearance.has_painted_cover(Cover::Fill), "the fill of a rank-0 vector should be styled like a list element");
}
// Fill's automatic gradient placement measures rank-0 vector content instead of falling back to the unit box
#[test]
fn vector_item_mut_reaches_a_rank_0_vector_graphic() {
let transform = DAffine2::from_translation(DVec2::new(7., 3.));
let item = create_vector_item(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY), transform);
let mut content = Item::new_from_element(Graphic::Vector(Box::new(item)));
let mut visited = Vec::new();
content.for_each_vector_mut(|vector, vector_paths, vector_transform| visited.push((vector.bounding_box(vector_paths), vector_transform)));
assert_eq!(visited.len(), 1, "the lone vector should be visited exactly once");
assert_eq!(visited[0].1, transform, "its own transform attribute should come along for placement");
assert!(visited[0].0.is_some(), "its geometry should be measurable for the automatic gradient bounds");
}
fn round_corners_of(bezpath: BezPath, transform: DAffine2) -> Vec<BezPath> {
let rounded = super::round_corners((), create_vector_item(bezpath, transform), item(10.), item(0.5), item(100.), item(5.));
rounded.element().stroke_bezpath_iter(item_paths(&rounded)).collect()
}
fn distance_to_path(point: DVec2, bezpath: &BezPath) -> f64 {
bezpath
.segments()
.map(|segment| segment.nearest(dvec2_to_point(point), 1e-6).distance_sq.sqrt())
.fold(f64::INFINITY, f64::min)
}
#[test]
fn round_corners_leaves_a_circle_unchanged() {
let circle = ellipse_bezpath(DVec2::ZERO, DVec2::splat(200.));
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(1.5), 0.4, DVec2::new(30., -20.));
let rounded = round_corners_of(circle.clone(), transform);
assert_eq!(rounded.len(), 1);
assert_eq!(rounded[0].segments().count(), circle.segments().count(), "a circle has no corners to round");
for (rounded, original) in rounded[0].segments().zip(circle.segments()) {
assert!(pathseg_abs_diff_eq(rounded, original, 1e-6), "the circle's curves should be kept: {rounded:?} != {original:?}");
}
}
#[test]
fn round_corners_rounds_a_rectangles_corners() {
let rounded = round_corners_of(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY), DAffine2::IDENTITY);
let segments: Vec<PathSeg> = rounded[0].segments().collect();
assert_eq!(segments.len(), 8, "each of the four corners becomes a curve between two edges");
// A right angle is cut back by the radius divided by sin(45°) along both edges
let cut_distance = 10. / std::f64::consts::FRAC_PI_4.sin();
for segment in &segments {
match segment {
PathSeg::Line(line) => assert!((line.length() - (100. - 2. * cut_distance)).abs() < 1e-9, "the edges are shortened at both ends"),
PathSeg::Cubic(cubic) => assert!((point_to_dvec2(cubic.p0).distance(point_to_dvec2(cubic.p3)) - cut_distance * 2_f64.sqrt()).abs() < 1e-9),
PathSeg::Quad(_) => panic!("rounded corners are cubic"),
}
}
}
#[test]
fn round_corners_keeps_curves_beside_a_corner() {
// A half-disc, whose two corners join its arc to its flat side, and whose arc is smooth where its two curves meet
let handle = 50. * 0.552_284_749_8;
let mut half_disc = BezPath::new();
half_disc.move_to((-50., 0.));
half_disc.curve_to((-50., -handle), (-handle, -50.), (0., -50.));
half_disc.curve_to((handle, -50.), (50., -handle), (50., 0.));
half_disc.line_to((-50., 0.));
half_disc.close_path();
let rounded = round_corners_of(half_disc.clone(), DAffine2::IDENTITY);
assert_eq!(rounded[0].segments().count(), 5, "only the two corners are rounded");
// The arc away from the corners, up to and past the smooth join at its top
let arc: Vec<PathSeg> = half_disc.segments().take(2).collect();
for (segment, t) in [(arc[0], 0.5), (arc[0], 0.8), (arc[0], 1.), (arc[1], 0.2), (arc[1], 0.5)] {
let on_arc = point_to_dvec2(segment.eval(t));
assert!(distance_to_path(on_arc, &rounded[0]) < 1e-6, "the arc at {on_arc} should be kept");
}
assert!(distance_to_path(DVec2::new(-50., 0.), &rounded[0]) > 1., "the corner should be rounded off");
}
#[test]
fn round_corners_leaves_short_subpaths_in_place() {
let mut line = BezPath::new();
line.move_to((0., 0.));
line.line_to((40., 10.));
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(2.), 0.3, DVec2::new(100., 50.));
let rounded = round_corners_of(line.clone(), transform);
assert_eq!(rounded.len(), 1);
assert!(
pathseg_abs_diff_eq(rounded[0].segments().next().unwrap(), line.segments().next().unwrap(), 1e-9),
"a subpath too short to have corners should stay where it was"
);
}
/// Two halves of a diamond drawn down its left side and back up its right, welded at both ends.
fn welded_diamond() -> Item<Vector> {
let mut vector = Vector::default();
for position in [DVec2::new(0., 0.), DVec2::new(-10., 10.), DVec2::new(0., 20.), DVec2::new(10., 10.)] {
vector.0.push(Item::new_from_element(position));
}
let mut paths = List::new();
push_path(&mut paths, CurveType::Linear, [0, 1, 2], []);
push_path(&mut paths, CurveType::Linear, [2, 3, 0], []);
Item::new_from_element(vector).with_attribute(ATTR_PATHS, paths)
}
// The welded diamond reads as one closed contour, and once unwelded as two open paths
#[test]
fn unwelded_paths_are_read_one_at_a_time() {
let diamond = welded_diamond();
let unwelded = super::unweld((), diamond.clone(), item(UnweldMethod::SharedPoints));
assert!(*super::path_is_closed((), diamond.clone(), item(0)).element());
assert!(!*super::path_is_closed((), unwelded.clone(), item(0)).element());
assert_eq!(super::separate_paths((), diamond.clone()).len(), 1);
assert_eq!(super::separate_paths((), unwelded.clone()).len(), 2);
assert_eq!(super::separate_paths((), super::unweld((), diamond.clone(), item(UnweldMethod::All))).len(), 4);
// Halfway along the whole contour is the diamond's far tip, while halfway along the first path alone is its left corner
let halfway = super::evaluate_path((), diamond, item(0.5), item(false), item(false)).unwrap();
assert!(halfway.position.element().distance(DVec2::new(0., 20.)) < 1e-3, "{:?}", halfway.position);
let halfway = super::evaluate_path((), unwelded, item(0.5), item(false), item(false)).unwrap();
assert!(halfway.position.element().distance(DVec2::new(-10., 10.)) < 1e-3, "{:?}", halfway.position);
}
// Sampling the welded diamond goes once around its closed contour, and once unwelded, along each open path on its own
#[test]
fn unwelded_paths_are_sampled_one_at_a_time() {
let sample = |content: Item<Vector>| super::sample_polyline((), content, item(PointSpacingType::Quantity), item(100.), item(5), item(0.), item(0.), item(false)).unwrap();
let polylines = |sampled: Item<Vector>| sampled.element().stroke_bezpath_iter(item_paths(&sampled)).collect::<Vec<_>>();
let welded = polylines(sample(welded_diamond()));
assert!(matches!(welded.as_slice(), [polyline] if polyline.elements().last() == Some(&PathEl::ClosePath)));
// Each half runs from tip to tip by way of its own side corner, down the left and back up the right
let unwelded = polylines(sample(super::unweld((), welded_diamond(), item(UnweldMethod::SharedPoints))));
assert_eq!(unwelded.len(), 2);
let (top, bottom) = (DVec2::ZERO, DVec2::new(0., 20.));
for (polyline, [from, side_corner, to]) in unwelded.iter().zip([[top, DVec2::new(-10., 10.), bottom], [bottom, DVec2::new(10., 10.), top]]) {
let points: Vec<DVec2> = polyline.elements().iter().filter_map(|element| element.end_point()).map(point_to_dvec2).collect();
assert_eq!(points.len(), 5);
assert!(points[0].distance(from) < 1e-3 && points[2].distance(side_corner) < 1e-3 && points[4].distance(to) < 1e-3, "{points:?}");
}
}
// Morphing reads the welded diamond as one closed contour and the unwelded one as two open paths, both as the control path and as the shapes morphed
#[test]
fn unwelded_paths_are_morphed_one_at_a_time() {
let unwelded = || super::unweld((), welded_diamond(), item(UnweldMethod::SharedPoints));
// Halfway along the whole contour is the diamond's far tip, while halfway along the first path alone is its left corner
let squares = || embed_vectors([(); 3].map(|_| vector_item_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))).into_iter().collect());
let morph_along = |path: Item<Vector>| super::morph((), squares(), item(0.5), item(false), item(InterpolationDistribution::Objects), path).unwrap();
let position = |morphed: Item<Vector>| morphed.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM).translation;
assert!(position(morph_along(welded_diamond())).distance(DVec2::new(0., 20.)) < 1e-3);
assert!(position(morph_along(unwelded())).distance(DVec2::new(-10., 10.)) < 1e-3);
// Midway between two copies of the diamond, the welded one stays one closed contour and the unwelded one two open paths
let morph_between = |diamond: Item<Vector>| {
super::morph(
(),
embed_vectors([diamond.clone(), diamond].into_iter().collect()),
item(0.5),
item(false),
item(InterpolationDistribution::Objects),
Item::default(),
)
.unwrap()
};
let closed = |morphed: Item<Vector>| {
let subpaths = morphed.element().stroke_bezpath_iter(item_paths(&morphed));
subpaths.map(|subpath| subpath.elements().last() == Some(&PathEl::ClosePath)).collect::<Vec<_>>()
};
assert_eq!(closed(morph_between(welded_diamond())), [true]);
assert_eq!(closed(morph_between(unwelded())), [false, false]);
}
#[test]
fn point_diagrams_report_non_finite_points() {
let mut points = SQUARE_WITH_CENTER.to_vec();
points.push(DVec2::new(f64::NAN, 3.));
let points = || vector_item_from_points(&points);
assert!(matches!(super::triangulate((), points(), item(false)), Err(PointDiagramError::NonFinitePoints)));
assert!(matches!(super::voronoi_cells((), points(), item(false)), Err(PointDiagramError::NonFinitePoints)));
assert!(matches!(super::relax_points((), points(), item(1.)), Err(PointDiagramError::NonFinitePoints)));
// No relaxation step needs the diagram
assert!(super::relax_points((), points(), item(0.)).is_ok());
}
#[test]
fn offset_path_reports_a_shape_too_large_to_clip() {
let star = vector_item_from_bezpath(vector_types::vector::algorithms::shapes::star_polygon_bezpath(DVec2::ZERO, 5, 1e20, 5e19).unwrap());
let offset = super::offset_path((), star, item(-1e18), item(StrokeJoin::Miter), item(4.));
assert!(matches!(offset, Err(OffsetPathError::TooLarge)));
}
// A collapsed transform has no inverse, so these nodes leave its item as it was
#[test]
fn collapsed_items_pass_through() {
let collapsed = create_vector_item(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY), DAffine2::from_scale(DVec2::new(0., 1.)));
assert_eq!(super::round_corners((), collapsed.clone(), item(10.), item(0.5), item(100.), item(5.)), collapsed);
assert_eq!(super::offset_path((), collapsed.clone(), item(5.), item(StrokeJoin::Miter), item(4.)).unwrap(), collapsed);
assert_eq!(super::simplify((), collapsed.clone(), item(5.)), collapsed);
assert_eq!(super::decimate((), collapsed.clone(), item(5.)), collapsed);
assert_eq!(super::bevel((), collapsed.clone(), item(10.)), collapsed);
}
// Kurbo drops a subpath that simplifies down to nothing, so one without length passes through
#[test]
fn simplify_keeps_a_subpath_without_length() {
let point = vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(5.), DVec2::splat(5.)));
let simplified = super::simplify((), point, item(5.));
assert_eq!(simplified.element().stroke_bezpath_iter(item_paths(&simplified)).count(), 1);
}
#[test]
fn decimate_with_a_tolerance_finer_than_float_precision() {
let circle = vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.)));
let decimated = super::decimate((), circle, item(1e-60));
assert!(decimated.element().point_count() > 4);
}
#[test]
fn evaluate_path_without_a_path() {
assert!(matches!(super::evaluate_path((), Item::default(), item(0.5), item(false), item(false)), Err(EvaluatePathError::NoPath)));
}
#[test]
fn progression_must_be_a_number() {
let square = || vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY));
assert!(matches!(super::cut_path((), square(), item(f64::NAN), item(false), item(true)), Err(ProgressionError::NotANumber)));
assert!(matches!(
super::evaluate_path((), square(), item(f64::NAN), item(false), item(true)),
Err(EvaluatePathError::Progression(_))
));
let squares = embed_vectors([square(), square()].into_iter().collect());
assert!(matches!(
super::morph((), squares, item(f64::NAN), item(false), item(InterpolationDistribution::Objects), Item::default()),
Err(ProgressionError::NotANumber)
));
}
#[test]
fn scatter_points_skips_an_infinite_subpath() {
let ellipse = || ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.));
let mut bezpath = ellipse();
bezpath.move_to((0., 0.));
bezpath.line_to((f64::INFINITY, 0.));
bezpath.line_to((0., 10.));
bezpath.close_path();
let points = scattered_points(bezpath, 10., 0);
assert!(!points.is_empty());
assert_eq!(points, scattered_points(ellipse(), 10., 0));
}
#[test]
fn scatter_points_samples_each_vector_in_graphic_content() {
let shapes = [ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.)), ellipse_bezpath(DVec2::new(200., -40.), DVec2::new(300., 40.))];
let vectors: List<Vector> = shapes.iter().cloned().map(vector_item_from_bezpath).collect();
let scattered = super::scatter_points((), Item::new_from_element(Graphic::VectorList(vectors)), item(10.), item(0)).expect("the shapes should scatter");
let Graphic::VectorList(vectors) = scattered.element() else {
panic!("the content should stay a vector list")
};
assert_eq!(vectors.len(), shapes.len());
for (vector, shape) in vectors.iter_element_values().zip(shapes) {
let alone: Vec<_> = scattered_points(shape, 10., 0).into_iter().map(|(position, _)| position).collect();
assert_eq!(vector.0.iter_element_values().copied().collect::<Vec<_>>(), alone);
}
}
#[test]
fn scatter_points_on_empty_content_gives_no_points() {
let scattered = super::scatter_points((), vector_item_from_bezpath(BezPath::new()), item(10.), item(0)).expect("empty content should scatter nothing");
assert_eq!(scattered.element().point_count(), 0);
}
fn scattered_points(bezpath: BezPath, separation: f64, seed: i64) -> Vec<(DVec2, PointId)> {
let scattered = super::scatter_points((), vector_item_from_bezpath(bezpath), item(separation), item(seed)).expect("the separation should fit the shape");
let points = &scattered.element().0;
points.iter_element_values().copied().zip(points.iter_attribute_values::<PointId>(ATTR_ID).unwrap().copied()).collect()
}
#[test]
fn scatter_points_changes_only_points_near_an_edit() {
// A square with a vertex partway down its right side, which the edit pushes outward
let pentagon = |bulge: f64| {
let mut bezpath = BezPath::new();
bezpath.move_to((0., 0.));
bezpath.line_to((400., 0.));
bezpath.line_to((400. + bulge, 200.));
bezpath.line_to((400., 400.));
bezpath.line_to((0., 400.));
bezpath.close_path();
scattered_points(bezpath, 10., 0)
};
let (before, after) = (pentagon(0.), pentagon(40.));
// Points over ten separations from the edit keep their positions and IDs, while the bulge gains points of its own
let far_from_edit = |points: &[(DVec2, PointId)]| points.iter().copied().filter(|(position, _)| position.x < 300.).collect::<Vec<_>>();
assert_eq!(far_from_edit(&before), far_from_edit(&after));
assert!(after.iter().any(|(position, _)| position.x > 405.));
let unchanged = before.iter().filter(|point| after.contains(point)).count();
assert!(unchanged as f64 > before.len() as f64 * 0.95, "only {unchanged} of {} points are unchanged", before.len());
}
#[test]
fn scatter_points_ignores_distant_geometry() {
let circle = || ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.));
let alone = scattered_points(circle(), 7., 3);
// Distant shapes on opposite sides, plus a frame around the circle that shares its grid while staying too far away to affect its points
let mut with_distant_shapes = circle();
with_distant_shapes.extend(ellipse_bezpath(DVec2::new(500., -900.), DVec2::new(700., -600.)));
with_distant_shapes.extend(ellipse_bezpath(DVec2::new(-800., 300.), DVec2::new(-600., 700.)));
with_distant_shapes.extend(Rect::new(-400., -400., 400., 400.).to_path(DEFAULT_ACCURACY));
with_distant_shapes.extend(Rect::new(-200., -200., 200., 200.).to_path(DEFAULT_ACCURACY).reverse_subpaths());
let with_distant_shapes = scattered_points(with_distant_shapes, 7., 3);
let near_first_circle: Vec<_> = with_distant_shapes.iter().copied().filter(|(position, _)| position.length() < 60.).collect();
assert_eq!(alone, near_first_circle);
assert!(with_distant_shapes.len() > alone.len() * 2, "the distant shapes should get points of their own");
assert!(
with_distant_shapes.iter().any(|(position, _)| position.x.abs().max(position.y.abs()) > 200.),
"the frame should get points of its own"
);
}
#[test]
fn scatter_points_keeps_its_separation_across_overlapping_subpaths() {
let mut bezpath = ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.));
bezpath.extend(ellipse_bezpath(DVec2::new(-20., -50.), DVec2::new(80., 50.)));
let points = scattered_points(bezpath, 10., 0);
assert!(points.iter().any(|(position, _)| position.x > 55.), "the second ellipse should get points of its own");
for (i, (a, _)) in points.iter().enumerate() {
for (b, _) in &points[i + 1..] {
assert!(a.distance(*b) > 10. * (1. - 1e-9), "{a} and {b} are closer than the separation");
}
}
}
#[test]
fn scatter_points_reports_a_separation_too_small_for_the_shape() {
let circle = |center: DVec2, radius: f64| vector_item_from_bezpath(ellipse_bezpath(center - radius, center + radius));
let scatter = |content, separation| super::scatter_points((), content, item(separation), item(0));
assert!(matches!(scatter(circle(DVec2::ZERO, 100.), 0.15), Err(PoissonDiskError::SeparationTooSmall { .. })));
assert!(matches!(scatter(circle(DVec2::ZERO, 100.), 0.01), Err(PoissonDiskError::ExtentTooLarge)));
assert!(matches!(scatter(circle(DVec2::new(1e10, 0.), 10.), 1.), Err(PoissonDiskError::TooFarFromOrigin)));
let scattered = scatter(circle(DVec2::ZERO, 100.), 1.).expect("a 1 px separation should fit a 200 px circle");
assert!(scattered.element().point_count() > 10_000);
}
#[test]
fn scatter_points_samples_small_shapes_spread_far_apart() {
// The empty space between the shapes doesn't count toward the limit on points
let mut bezpath = ellipse_bezpath(DVec2::splat(-10.), DVec2::splat(10.));
bezpath.extend(ellipse_bezpath(DVec2::splat(4990.), DVec2::splat(5010.)));
let points = scattered_points(bezpath, 1., 0);
assert!(points.iter().any(|(position, _)| position.length() < 10.));
assert!(points.iter().any(|(position, _)| position.distance(DVec2::splat(5000.)) < 10.));
}
// The axis a collapsed transform keeps is too long to square, but still gives the perpendicular one a direction
#[test]
fn point_offsets_under_a_collapsed_transform_with_a_huge_axis() {
let transform = DAffine2::from_cols(DVec2::new(1e160, 0.), DVec2::ZERO, DVec2::ZERO);
let content = || create_vector_item(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY), transform);
let jittered = super::jitter_points((), content(), item(5.), item(0), item(true));
assert!(jittered.element().positions().all(|position| position.is_finite()));
let offset = super::offset_points((), content(), item(10.));
assert!(offset.element().positions().all(|position| position.is_finite()));
}
// The loop's closing segment, from its lone anchor back to itself, is split to match the anchors of the shape it morphs from
#[test]
fn morph_into_a_one_anchor_loop() {
let mut teardrop = BezPath::new();
teardrop.move_to((0., 0.));
teardrop.curve_to((50., -50.), (100., 50.), (0., 0.));
teardrop.close_path();
let square = vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY));
for content in [
[square.clone(), vector_item_from_bezpath(teardrop.clone())],
[vector_item_from_bezpath(teardrop.clone()), square.clone()],
] {
let morphed = super::morph(
(),
embed_vectors(content.into_iter().collect()),
item(0.5),
item(false),
item(InterpolationDistribution::Objects),
Item::default(),
)
.unwrap();
assert_eq!(morphed.element().anchor_positions(item_paths(&morphed)).len(), 4);
}
}
// The chain of segments from the first one runs into a loop that doesn't come back to it, as Points to Polyline then Weld can leave
#[test]
fn bevel_a_lasso() {
let mut vector = Vector::default();
for position in [(0., 0.), (100., 0.), (200., 0.), (150., 100.), (0., 200.), (100., 200.), (200., 250.)] {
vector.0.push(Item::new_from_element(DVec2::from(position)));
}
let mut paths = List::new();
push_path(&mut paths, CurveType::Linear, [0, 1, 2, 3, 1], []);
push_path(&mut paths, CurveType::Linear, [4, 5, 6], []);
let beveled = super::bevel((), Item::new_from_element(vector).with_attribute(ATTR_PATHS, paths), item(10.));
assert!(beveled.element().segment_iter(item_paths(&beveled)).count() > 6);
}
#[test]
fn box_warp_onto_too_few_corners() {
let content = vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY));
assert_eq!(super::box_warp((), content.clone(), Item::default()).unwrap(), content);
let triangle = vector_item_from_points(&[DVec2::ZERO, DVec2::X, DVec2::Y]);
assert!(matches!(super::box_warp((), content, triangle), Err(BoxWarpError::TooFewCorners)));
}
#[test]
fn sample_polyline_reports_too_many_points() {
let line = || vector_item_from_bezpath(Line::new((0., 0.), (100., 0.)).to_path(DEFAULT_ACCURACY));
let sample = |spacing, separation, quantity| super::sample_polyline((), line(), item(spacing), item(separation), item(quantity), item(0.), item(0.), item(false));
assert!(matches!(sample(PointSpacingType::Separation, 0., 100), Err(SampleCountError::SeparationTooSmall { limit: 10_000 })));
assert!(matches!(sample(PointSpacingType::Quantity, 100., 10_001), Err(SampleCountError::QuantityTooLarge { limit: 10_000 })));
assert_eq!(sample(PointSpacingType::Quantity, 100., 10_000).unwrap().element().point_count(), 10_000);
}
#[test]
fn vary_colors_from_an_empty_gradient() {
let content = || List::new_from_item(vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY)));
let empty = || item(Gradient::from(Vec::<Color>::new()));
let fills = super::vary_fill_colors((), content(), empty(), item(false), item(false), item(0), item(0));
let strokes = super::vary_stroke_colors((), content(), empty(), item(false), item(false), item(0), item(0));
assert!(matches!(fills, Err(VaryColorsError::EmptyGradient)));
assert!(matches!(strokes, Err(VaryColorsError::EmptyGradient)));
}
#[test]
fn vary_stroke_colors_recolors_only_existing_strokes() {
let rect = || vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY));
let mut stroked = Appearance::default();
stroked.replace_or_insert(
Coverage::new_stroke(&Stroke::new(4.)),
Graphic::from(List::new_from_element(Color::BLACK)),
DAffine2::IDENTITY,
CoverPlacement::Above,
);
let content: List<Vector> = [rect().with_attribute(ATTR_APPEARANCE, stroked), rect()].into_iter().collect();
let styled = super::vary_stroke_colors((), content, item(Gradient::from(vec![Color::WHITE])), item(false), item(false), item(0), item(0)).unwrap();
let stroke_paint = styled
.attribute::<Appearance>(ATTR_APPEARANCE, 0)
.and_then(|appearance| appearance.first_paint_of(Cover::Stroke).cloned());
assert_eq!(stroke_paint, Some(Graphic::ColorList(List::new_from_element(Color::WHITE))));
assert!(
!styled.attribute::<Appearance>(ATTR_APPEARANCE, 1).is_some_and(|appearance| appearance.has_cover(Cover::Stroke)),
"an element without a stroke should not gain one"
);
}
#[test]
fn solidify_stroke_passes_an_item_without_a_stroke_through() {
let fill = Appearance::new_single(Coverage::new_fill(), Graphic::from(List::new_from_element(Color::RED)));
let filled = vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY)).with_attribute(ATTR_APPEARANCE, fill);
let solidified = super::solidify_stroke((), filled.clone());
assert_eq!(solidified.len(), 1);
assert_eq!(solidified.element(0), Some(filled.element()));
assert_eq!(solidified.attribute::<Appearance>(ATTR_APPEARANCE, 0), filled.attribute::<Appearance>(ATTR_APPEARANCE));
}
}