Skip to content

Commit 320d030

Browse files
0HyperCubeKeavon
andauthored
Fix the spline node algorithm to be continuous across start/end points (#2092)
* Simplify spline node implementation using stroke_bezier_paths * Improve closed splines * Code review --------- Co-authored-by: Keavon Chambers <[email protected]>
1 parent c3b526a commit 320d030

File tree

2 files changed

+122
-104
lines changed

2 files changed

+122
-104
lines changed

libraries/bezier-rs/src/subpath/core.rs

Lines changed: 107 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ impl<PointId: crate::Identifier> Subpath<PointId> {
325325
// Number of points = number of points to find handles for
326326
let len_points = points.len();
327327

328-
let out_handles = solve_spline_first_handle(&points);
328+
let out_handles = solve_spline_first_handle_open(&points);
329329

330330
let mut subpath = Subpath::new(Vec::new(), false);
331331

@@ -366,14 +366,14 @@ impl<PointId: crate::Identifier> Subpath<PointId> {
366366
}
367367
}
368368

369-
pub fn solve_spline_first_handle(points: &[DVec2]) -> Vec<DVec2> {
369+
pub fn solve_spline_first_handle_open(points: &[DVec2]) -> Vec<DVec2> {
370370
let len_points = points.len();
371371
if len_points == 0 {
372372
return Vec::new();
373373
}
374374

375375
// Matrix coefficients a, b and c (see https://mathworld.wolfram.com/CubicSpline.html).
376-
// Because the 'a' coefficients are all 1, they need not be stored.
376+
// Because the `a` coefficients are all 1, they need not be stored.
377377
// This algorithm does a variation of the above algorithm.
378378
// Instead of using the traditional cubic (a + bt + ct^2 + dt^3), we use the bezier cubic.
379379

@@ -417,3 +417,107 @@ pub fn solve_spline_first_handle(points: &[DVec2]) -> Vec<DVec2> {
417417

418418
d
419419
}
420+
421+
pub fn solve_spline_first_handle_closed(points: &[DVec2]) -> Vec<DVec2> {
422+
let len_points = points.len();
423+
if len_points < 3 {
424+
return Vec::new();
425+
}
426+
427+
// Matrix coefficients `a`, `b` and `c` (see https://mathworld.wolfram.com/CubicSpline.html).
428+
// We don't really need to allocate them but it keeps the maths understandable.
429+
let a = vec![DVec2::splat(1.); len_points];
430+
let b = vec![DVec2::splat(4.); len_points];
431+
let c = vec![DVec2::splat(1.); len_points];
432+
433+
let mut cmod = vec![DVec2::ZERO; len_points];
434+
let mut u = vec![DVec2::ZERO; len_points];
435+
436+
// `x` is initially the output of the matrix multiplication, but is converted to the second value.
437+
let mut x = vec![DVec2::ZERO; len_points];
438+
439+
for (i, point) in x.iter_mut().enumerate() {
440+
let previous_i = i.checked_sub(1).unwrap_or(len_points - 1);
441+
let next_i = (i + 1) % len_points;
442+
*point = 3. * (points[next_i] - points[previous_i]);
443+
}
444+
445+
// Solve using https://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm#Variants (the variant using periodic boundary conditions).
446+
// This code below is based on the reference C language implementation provided in that section of the article.
447+
let alpha = a[0];
448+
let beta = c[len_points - 1];
449+
450+
// Arbitrary, but chosen such that division by zero is avoided.
451+
let gamma = -b[0];
452+
453+
cmod[0] = alpha / (b[0] - gamma);
454+
u[0] = gamma / (b[0] - gamma);
455+
x[0] /= b[0] - gamma;
456+
457+
// Handle from from `1` to `len_points - 2` (inclusive).
458+
for ix in 1..=(len_points - 2) {
459+
let m = 1.0 / (b[ix] - a[ix] * cmod[ix - 1]);
460+
cmod[ix] = c[ix] * m;
461+
u[ix] = (0.0 - a[ix] * u[ix - 1]) * m;
462+
x[ix] = (x[ix] - a[ix] * x[ix - 1]) * m;
463+
}
464+
465+
// Handle `len_points - 1`.
466+
let m = 1.0 / (b[len_points - 1] - alpha * beta / gamma - beta * cmod[len_points - 2]);
467+
u[len_points - 1] = (alpha - a[len_points - 1] * u[len_points - 2]) * m;
468+
x[len_points - 1] = (x[len_points - 1] - a[len_points - 1] * x[len_points - 2]) * m;
469+
470+
// Loop from `len_points - 2` to `0` (inclusive).
471+
for ix in (0..=(len_points - 2)).rev() {
472+
u[ix] = u[ix] - cmod[ix] * u[ix + 1];
473+
x[ix] = x[ix] - cmod[ix] * x[ix + 1];
474+
}
475+
476+
let fact = (x[0] + x[len_points - 1] * beta / gamma) / (1.0 + u[0] + u[len_points - 1] * beta / gamma);
477+
478+
for ix in 0..(len_points) {
479+
x[ix] -= fact * u[ix];
480+
}
481+
482+
let mut real = vec![DVec2::ZERO; len_points];
483+
for i in 0..len_points {
484+
let previous = i.checked_sub(1).unwrap_or(len_points - 1);
485+
let next = (i + 1) % len_points;
486+
real[i] = x[previous] * a[next] + x[i] * b[i] + x[next] * c[i];
487+
}
488+
489+
// The matrix is now solved.
490+
491+
// Since we have computed the derivative, work back to find the start handle.
492+
for i in 0..len_points {
493+
x[i] = (x[i] / 3.) + points[i];
494+
}
495+
496+
x
497+
}
498+
499+
#[test]
500+
fn closed_spline() {
501+
// These points are just chosen arbitrary
502+
let points = [DVec2::new(0., 0.), DVec2::new(0., 0.), DVec2::new(6., 5.), DVec2::new(7., 9.), DVec2::new(2., 3.)];
503+
504+
let out_handles = solve_spline_first_handle_closed(&points);
505+
506+
// Construct the Subpath
507+
let mut manipulator_groups = Vec::new();
508+
for i in 0..out_handles.len() {
509+
manipulator_groups.push(ManipulatorGroup::<EmptyId>::new(points[i], Some(2. * points[i] - out_handles[i]), Some(out_handles[i])));
510+
}
511+
let subpath = Subpath::new(manipulator_groups, true);
512+
513+
// For each pair of bézier curves, ensure that the second derivative is continuous
514+
for (bézier_a, bézier_b) in subpath.iter().zip(subpath.iter().skip(1).chain(subpath.iter().take(1))) {
515+
let derivative2_end_a = bézier_a.derivative().unwrap().derivative().unwrap().evaluate(crate::TValue::Parametric(1.));
516+
let derivative2_start_b = bézier_b.derivative().unwrap().derivative().unwrap().evaluate(crate::TValue::Parametric(0.));
517+
518+
assert!(
519+
derivative2_end_a.abs_diff_eq(derivative2_start_b, 1e-10),
520+
"second derivative at the end of a {derivative2_end_a} is equal to the second derivative at the start of b {derivative2_start_b}"
521+
);
522+
}
523+
}

node-graph/gcore/src/vector/vector_nodes.rs

Lines changed: 15 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use super::misc::CentroidType;
22
use super::style::{Fill, Gradient, GradientStops, Stroke};
3-
use super::{PointId, SegmentId, StrokeId, VectorData};
3+
use super::{PointId, SegmentDomain, SegmentId, StrokeId, VectorData};
44
use crate::registry::types::{Angle, Fraction, IntegerCount, Length, SeedValue};
55
use crate::renderer::GraphicElementRendered;
66
use crate::transform::{Footprint, Transform, TransformMut};
@@ -11,7 +11,6 @@ use crate::{Color, GraphicElement, GraphicGroup};
1111
use bezier_rs::{Cap, Join, Subpath, SubpathTValue, TValue};
1212
use glam::{DAffine2, DVec2};
1313
use rand::{Rng, SeedableRng};
14-
use std::collections::{BTreeMap, BTreeSet, VecDeque};
1514

1615
/// Implemented for types that can be converted to an iterator of vector data.
1716
/// Used for the fill and stroke node so they can be used on VectorData or GraphicGroup
@@ -857,120 +856,35 @@ async fn splines_from_points<F: 'n + Send>(
857856
return vector_data;
858857
}
859858

860-
// Extract points and take ownership of the segment domain for processing.
861-
let points = &vector_data.point_domain;
862-
let segments = std::mem::take(&mut vector_data.segment_domain);
863-
864-
// Map segment IDs to their indices using BTreeMap for deterministic ordering.
865-
let segment_id_to_index = segments.ids().iter().copied().enumerate().map(|(i, id)| (id, i)).collect::<BTreeMap<_, _>>();
866-
867-
// Iterate over all segments to generate splines.
868-
let mut visited_segments = BTreeSet::new();
869-
for (segment_index, &segment_id) in segments.ids().iter().enumerate() {
870-
// Skip segments that have already been visited.
871-
if visited_segments.contains(&segment_id) {
872-
continue;
873-
}
874-
875-
let mut current_subpath_segments = Vec::new();
876-
let mut queue = VecDeque::new();
877-
queue.push_back(segment_index);
878-
879-
// Traverse the connected segments to form a subpath.
880-
while let Some(segment_index) = queue.pop_front() {
881-
// Skip segments that have already been visited, otherwise add them to the visited set and the current subpath.
882-
let seg_id = segments.ids()[segment_index];
883-
if visited_segments.contains(&seg_id) {
884-
continue;
885-
}
886-
visited_segments.insert(seg_id);
887-
current_subpath_segments.push(segment_index);
888-
889-
// Get the start and end points of the segment.
890-
let start_point_index = segments.start_point()[segment_index];
891-
let end_point_index = segments.end_point()[segment_index];
892-
893-
// For both start and end points, find and enqueue connected segments.
894-
for point_index in [start_point_index, end_point_index] {
895-
let mut connected_seg_ids = segments.start_connected(point_index).chain(segments.end_connected(point_index)).collect::<Vec<_>>();
896-
connected_seg_ids.sort_unstable(); // Ensure deterministic order
897-
for connected_seg_id in connected_seg_ids {
898-
let connected_seg_index = *segment_id_to_index.get(&connected_seg_id).unwrap_or(&usize::MAX);
899-
if connected_seg_index != usize::MAX && !visited_segments.contains(&connected_seg_id) {
900-
queue.push_back(connected_seg_index);
901-
}
902-
}
903-
}
904-
}
905-
906-
// Build a mapping from each point to its connected points using BTreeMap for deterministic ordering.
907-
let mut point_connections: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
908-
for &seg_index in &current_subpath_segments {
909-
let start = segments.start_point()[seg_index];
910-
let end = segments.end_point()[seg_index];
911-
point_connections.entry(start).or_default().push(end);
912-
point_connections.entry(end).or_default().push(start);
913-
}
914-
915-
// Sort connected points for deterministic traversal.
916-
for neighbors in point_connections.values_mut() {
917-
neighbors.sort_unstable();
918-
}
919-
920-
// Identify endpoints.
921-
let endpoints = point_connections
922-
.iter()
923-
.filter(|(_, neighbors)| neighbors.len() == 1)
924-
.map(|(&point_index, _)| point_index)
925-
.collect::<Vec<_>>();
926-
927-
let mut ordered_point_indices = Vec::new();
928-
929-
// Start with the first endpoint or the first point if there are no endpoints because it's a closed subpath.
930-
let start_point_index = endpoints.first().copied().unwrap_or_else(|| *point_connections.keys().next().unwrap());
931-
932-
// Traverse points to order them into a path.
933-
let mut visited_points = BTreeSet::new();
934-
let mut current_point = start_point_index;
935-
loop {
936-
ordered_point_indices.push(current_point);
937-
visited_points.insert(current_point);
938-
939-
let Some(neighbors) = point_connections.get(&current_point) else { break };
940-
let next_point = neighbors.iter().find(|&pt| !visited_points.contains(pt));
941-
let Some(&next_point) = next_point else { break };
942-
current_point = next_point;
943-
}
944-
945-
// If it's a closed subpath, close the spline loop by adding the start point at the end.
946-
let closed = endpoints.is_empty();
947-
if closed {
948-
ordered_point_indices.push(start_point_index);
949-
}
950-
951-
// Collect the positions of the ordered points.
952-
let positions = ordered_point_indices.iter().map(|&index| points.positions()[index]).collect::<Vec<_>>();
859+
let mut segment_domain = SegmentDomain::default();
860+
for subpath in vector_data.stroke_bezier_paths() {
861+
let positions = subpath.manipulator_groups().iter().map(|group| group.anchor).collect::<Vec<_>>();
862+
let closed = subpath.closed();
953863

954864
// Compute control point handles for Bezier spline.
955-
// TODO: Make this support wrapping around between start and end points for closed subpaths.
956-
let first_handles = bezier_rs::solve_spline_first_handle(&positions);
865+
let first_handles = if closed {
866+
bezier_rs::solve_spline_first_handle_closed(&positions)
867+
} else {
868+
bezier_rs::solve_spline_first_handle_open(&positions)
869+
};
957870

958871
let stroke_id = StrokeId::ZERO;
959872

960873
// Create segments with computed Bezier handles and add them to vector data.
961-
for i in 0..(positions.len() - 1) {
874+
for i in 0..(positions.len() - if closed { 0 } else { 1 }) {
962875
let next_index = (i + 1) % positions.len();
963876

964-
let start_index = ordered_point_indices[i];
965-
let end_index = ordered_point_indices[next_index];
877+
let start_index = vector_data.point_domain.resolve_id(subpath.manipulator_groups()[i].id).unwrap();
878+
let end_index = vector_data.point_domain.resolve_id(subpath.manipulator_groups()[next_index].id).unwrap();
966879

967880
let handle_start = first_handles[i];
968881
let handle_end = positions[next_index] * 2. - first_handles[next_index];
969882
let handles = bezier_rs::BezierHandles::Cubic { handle_start, handle_end };
970883

971-
vector_data.segment_domain.push(SegmentId::generate(), start_index, end_index, handles, stroke_id);
884+
segment_domain.push(SegmentId::generate(), start_index, end_index, handles, stroke_id);
972885
}
973886
}
887+
vector_data.segment_domain = segment_domain;
974888

975889
vector_data
976890
}

0 commit comments

Comments
 (0)