Skip to content

Commit e6a7325

Browse files
indierustyKeavon
andauthored
Refactor the 'Bounding Box' node to use Kurbo instead of Bezier-rs (#2662)
* use kurbo's default accuracy constant * fix append_bezpath() method * refactor bounding box node * fix append bezpath implementation. * comments --------- Co-authored-by: Keavon Chambers <[email protected]>
1 parent 2bb07b8 commit e6a7325

File tree

4 files changed

+128
-85
lines changed

4 files changed

+128
-85
lines changed

node-graph/gcore/src/vector/algorithms/bezpath_algorithms.rs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
11
use super::poisson_disk::poisson_disk_sample;
22
use crate::vector::misc::dvec2_to_point;
33
use glam::DVec2;
4-
use kurbo::{BezPath, Line, ParamCurve, ParamCurveDeriv, PathSeg, Point, Rect, Shape};
5-
6-
/// Accuracy to find the position on [kurbo::Bezpath].
7-
const POSITION_ACCURACY: f64 = 1e-5;
8-
/// Accuracy to find the length of the [kurbo::PathSeg].
9-
pub const PERIMETER_ACCURACY: f64 = 1e-5;
4+
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveDeriv, PathSeg, Point, Rect, Shape};
105

116
pub fn position_on_bezpath(bezpath: &BezPath, t: f64, euclidian: bool, segments_length: Option<&[f64]>) -> Point {
127
let (segment_index, t) = t_value_to_parametric(bezpath, t, euclidian, segments_length);
@@ -79,7 +74,7 @@ pub fn sample_points_on_bezpath(bezpath: BezPath, spacing: f64, start_offset: f6
7974
let t = (next_length / next_segment_length).clamp(0., 1.);
8075

8176
let segment = bezpath.get_seg(next_segment_index + 1).unwrap();
82-
let t = eval_pathseg_euclidean(segment, t, POSITION_ACCURACY);
77+
let t = eval_pathseg_euclidean(segment, t, DEFAULT_ACCURACY);
8378
let point = segment.eval(t);
8479

8580
if sample_bezpath.elements().is_empty() {
@@ -96,7 +91,7 @@ pub fn t_value_to_parametric(bezpath: &BezPath, t: f64, euclidian: bool, segment
9691
if euclidian {
9792
let (segment_index, t) = bezpath_t_value_to_parametric(bezpath, BezPathTValue::GlobalEuclidean(t), segments_length);
9893
let segment = bezpath.get_seg(segment_index + 1).unwrap();
99-
return (segment_index, eval_pathseg_euclidean(segment, t, POSITION_ACCURACY));
94+
return (segment_index, eval_pathseg_euclidean(segment, t, DEFAULT_ACCURACY));
10095
}
10196
bezpath_t_value_to_parametric(bezpath, BezPathTValue::GlobalParametric(t), segments_length)
10297
}
@@ -164,7 +159,7 @@ fn bezpath_t_value_to_parametric(bezpath: &kurbo::BezPath, t: BezPathTValue, pre
164159
let segments_length = if let Some(segments_length) = precomputed_segments_length {
165160
segments_length
166161
} else {
167-
computed_segments_length = bezpath.segments().map(|segment| segment.perimeter(PERIMETER_ACCURACY)).collect::<Vec<f64>>();
162+
computed_segments_length = bezpath.segments().map(|segment| segment.perimeter(DEFAULT_ACCURACY)).collect::<Vec<f64>>();
168163
computed_segments_length.as_slice()
169164
};
170165

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

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use core::borrow::Borrow;
1212
use dyn_any::DynAny;
1313
use glam::{DAffine2, DVec2};
1414
pub use indexed::VectorDataIndex;
15-
use kurbo::{Affine, Shape};
15+
use kurbo::{Affine, Rect, Shape};
1616
pub use modification::*;
1717
use std::collections::HashMap;
1818

@@ -194,6 +194,11 @@ impl VectorData {
194194
vector_data
195195
}
196196

197+
/// Compute the bounding boxes of the bezpaths without any transform
198+
pub fn bounding_box_rect(&self) -> Option<Rect> {
199+
self.bounding_box_with_transform_rect(DAffine2::IDENTITY)
200+
}
201+
197202
pub fn close_subpaths(&mut self) {
198203
let segments_to_add: Vec<_> = self
199204
.stroke_bezier_paths()
@@ -213,27 +218,25 @@ impl VectorData {
213218

214219
/// Compute the bounding boxes of the subpaths without any transform
215220
pub fn bounding_box(&self) -> Option<[DVec2; 2]> {
216-
self.bounding_box_with_transform(DAffine2::IDENTITY)
221+
self.bounding_box_with_transform_rect(DAffine2::IDENTITY)
222+
.map(|rect| [DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)])
217223
}
218224

219225
/// Compute the bounding boxes of the subpaths with the specified transform
220226
pub fn bounding_box_with_transform(&self, transform: DAffine2) -> Option<[DVec2; 2]> {
221-
let combine = |[a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]| [a_min.min(b_min), a_max.max(b_max)];
222-
223-
let anchor_bounds = self
224-
.point_domain
225-
.positions()
226-
.iter()
227-
.map(|&point| transform.transform_point2(point))
228-
.map(|point| [point, point])
229-
.reduce(combine);
230-
231-
let segment_bounds = self
232-
.segment_bezier_iter()
233-
.map(|(_, bezier, _, _)| bezier.apply_transformation(|point| transform.transform_point2(point)).bounding_box())
234-
.reduce(combine);
227+
self.bounding_box_with_transform_rect(transform)
228+
.map(|rect| [DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)])
229+
}
235230

236-
anchor_bounds.iter().chain(segment_bounds.iter()).copied().reduce(combine)
231+
/// Compute the bounding boxes of the bezpaths with the specified transform
232+
pub fn bounding_box_with_transform_rect(&self, transform: DAffine2) -> Option<Rect> {
233+
let combine = |r1: Rect, r2: Rect| r1.union(r2);
234+
self.stroke_bezpath_iter()
235+
.map(|mut bezpath| {
236+
bezpath.apply_affine(Affine::new(transform.to_cols_array()));
237+
bezpath.bounding_box()
238+
})
239+
.reduce(combine)
237240
}
238241

239242
/// Calculate the corners of the bounding box but with a nonzero size.

node-graph/gcore/src/vector/vector_data/modification.rs

Lines changed: 94 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::uuid::generate_uuid;
55
use bezier_rs::BezierHandles;
66
use core::hash::BuildHasher;
77
use dyn_any::DynAny;
8-
use kurbo::{BezPath, PathEl};
8+
use kurbo::{BezPath, PathEl, Point};
99
use std::collections::{HashMap, HashSet};
1010

1111
/// Represents a procedural change to the [`PointDomain`] in [`VectorData`].
@@ -556,11 +556,12 @@ where
556556
}
557557

558558
pub struct AppendBezpath<'a> {
559+
first_point: Option<Point>,
560+
last_point: Option<Point>,
559561
first_point_index: Option<usize>,
560562
last_point_index: Option<usize>,
561563
first_segment_id: Option<SegmentId>,
562564
last_segment_id: Option<SegmentId>,
563-
next_handle: Option<BezierHandles>,
564565
point_id: PointId,
565566
segment_id: SegmentId,
566567
vector_data: &'a mut VectorData,
@@ -569,79 +570,118 @@ pub struct AppendBezpath<'a> {
569570
impl<'a> AppendBezpath<'a> {
570571
fn new(vector_data: &'a mut VectorData) -> Self {
571572
Self {
573+
first_point: None,
574+
last_point: None,
572575
first_point_index: None,
573576
last_point_index: None,
574577
first_segment_id: None,
575578
last_segment_id: None,
576-
next_handle: None,
577579
point_id: vector_data.point_domain.next_id(),
578580
segment_id: vector_data.segment_domain.next_id(),
579581
vector_data,
580582
}
581583
}
582584

583-
fn append_path_element(&mut self, handle: BezierHandles, point: kurbo::Point, next_element: Option<&PathEl>) {
584-
if let Some(PathEl::ClosePath) = next_element {
585-
self.next_handle = Some(handle);
585+
fn append_segment_and_close_path(&mut self, point: Point, handle: BezierHandles) {
586+
let handle = if self.first_point.unwrap() != point {
587+
// If the first point is not the same as the last point of the path then we append the segment
588+
// with given handle and point and then close the path with linear handle.
589+
self.append_segment(point, handle);
590+
BezierHandles::Linear
586591
} else {
587-
let next_point_index = self.vector_data.point_domain.ids().len();
588-
self.vector_data.point_domain.push(self.point_id.next_id(), point_to_dvec2(point));
592+
// if the endpoints are the same then we close the path with given handle.
593+
handle
594+
};
595+
596+
// Create a new segment.
597+
let next_segment_id = self.segment_id.next_id();
598+
self.vector_data
599+
.segment_domain
600+
.push(next_segment_id, self.last_point_index.unwrap(), self.first_point_index.unwrap(), handle, StrokeId::ZERO);
601+
602+
// Create a new region.
603+
let next_region_id = self.vector_data.region_domain.next_id();
604+
let first_segment_id = self.first_segment_id.unwrap_or(next_segment_id);
605+
let last_segment_id = next_segment_id;
606+
607+
self.vector_data.region_domain.push(next_region_id, first_segment_id..=last_segment_id, FillId::ZERO);
608+
}
589609

590-
let next_segment_id = self.segment_id.next_id();
591-
self.vector_data
592-
.segment_domain
593-
.push(self.segment_id.next_id(), self.last_point_index.unwrap(), next_point_index, handle, StrokeId::ZERO);
610+
fn append_segment(&mut self, end_point: Point, handle: BezierHandles) {
611+
// Append the point.
612+
let next_point_index = self.vector_data.point_domain.ids().len();
613+
let next_point_id = self.point_id.next_id();
594614

595-
self.last_point_index = Some(next_point_index);
596-
self.first_segment_id = Some(self.first_segment_id.unwrap_or(next_segment_id));
597-
self.last_segment_id = Some(next_segment_id);
598-
}
615+
self.vector_data.point_domain.push(next_point_id, point_to_dvec2(end_point));
616+
617+
// Append the segment.
618+
let next_segment_id = self.segment_id.next_id();
619+
self.vector_data
620+
.segment_domain
621+
.push(next_segment_id, self.last_point_index.unwrap(), next_point_index, handle, StrokeId::ZERO);
622+
623+
// Update the states.
624+
self.last_point = Some(end_point);
625+
self.last_point_index = Some(next_point_index);
626+
627+
self.first_segment_id = Some(self.first_segment_id.unwrap_or(next_segment_id));
628+
self.last_segment_id = Some(next_segment_id);
599629
}
600630

601-
pub fn append_bezpath(vector_data: &'a mut VectorData, bezpath: BezPath) {
602-
let mut this = Self::new(vector_data);
631+
fn append_first_point(&mut self, point: Point) {
632+
self.first_point = Some(point);
633+
self.last_point = Some(point);
603634

604-
let stroke_id = StrokeId::ZERO;
605-
let fill_id = FillId::ZERO;
635+
// Append the first point.
636+
let next_point_index = self.vector_data.point_domain.ids().len();
637+
self.vector_data.point_domain.push(self.point_id.next_id(), point_to_dvec2(point));
606638

607-
for i in 0..bezpath.elements().len() {
608-
let current_element = bezpath.elements()[i];
609-
let next_element = bezpath.elements().get(i + 1);
639+
// Update the state.
640+
self.first_point_index = Some(next_point_index);
641+
self.last_point_index = Some(next_point_index);
642+
}
610643

611-
match current_element {
612-
kurbo::PathEl::MoveTo(point) => {
613-
let next_point_index = this.vector_data.point_domain.ids().len();
614-
this.vector_data.point_domain.push(this.point_id.next_id(), point_to_dvec2(point));
615-
this.first_point_index = Some(next_point_index);
616-
this.last_point_index = Some(next_point_index);
644+
pub fn append_bezpath(vector_data: &'a mut VectorData, bezpath: BezPath) {
645+
let mut this = Self::new(vector_data);
646+
let mut elements = bezpath.elements().iter().peekable();
647+
648+
while let Some(element) = elements.next() {
649+
let close_path = elements.peek().is_some_and(|elm| **elm == PathEl::ClosePath);
650+
651+
match *element {
652+
PathEl::MoveTo(point) => this.append_first_point(point),
653+
PathEl::LineTo(point) => {
654+
let handle = BezierHandles::Linear;
655+
if close_path {
656+
this.append_segment_and_close_path(point, handle);
657+
} else {
658+
this.append_segment(point, handle);
659+
}
617660
}
618-
kurbo::PathEl::ClosePath => match (this.first_point_index, this.last_point_index) {
619-
(Some(first_point_index), Some(last_point_index)) => {
620-
let next_segment_id = this.segment_id.next_id();
621-
this.vector_data
622-
.segment_domain
623-
.push(next_segment_id, last_point_index, first_point_index, this.next_handle.unwrap_or(BezierHandles::Linear), stroke_id);
624-
625-
let next_region_id = this.vector_data.region_domain.next_id();
626-
// In case there is only one anchor point.
627-
let first_segment_id = this.first_segment_id.unwrap_or(next_segment_id);
628-
629-
this.vector_data.region_domain.push(next_region_id, first_segment_id..=next_segment_id, fill_id);
661+
PathEl::QuadTo(point, point1) => {
662+
let handle = BezierHandles::Quadratic { handle: point_to_dvec2(point) };
663+
if close_path {
664+
this.append_segment_and_close_path(point1, handle);
665+
} else {
666+
this.append_segment(point1, handle);
630667
}
631-
_ => {
632-
error!("Empty bezpath cannot be closed.")
668+
}
669+
PathEl::CurveTo(point, point1, point2) => {
670+
let handle = BezierHandles::Cubic {
671+
handle_start: point_to_dvec2(point),
672+
handle_end: point_to_dvec2(point1),
673+
};
674+
675+
if close_path {
676+
this.append_segment_and_close_path(point2, handle);
677+
} else {
678+
this.append_segment(point2, handle);
633679
}
634-
},
635-
kurbo::PathEl::LineTo(point) => this.append_path_element(BezierHandles::Linear, point, next_element),
636-
kurbo::PathEl::QuadTo(handle, point) => this.append_path_element(BezierHandles::Quadratic { handle: point_to_dvec2(handle) }, point, next_element),
637-
kurbo::PathEl::CurveTo(handle_start, handle_end, point) => this.append_path_element(
638-
BezierHandles::Cubic {
639-
handle_start: point_to_dvec2(handle_start),
640-
handle_end: point_to_dvec2(handle_end),
641-
},
642-
point,
643-
next_element,
644-
),
680+
}
681+
PathEl::ClosePath => {
682+
// Already handled using `append_segment_and_close_path()`;
683+
break;
684+
}
645685
}
646686
}
647687
}

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

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::algorithms::bezpath_algorithms::{self, PERIMETER_ACCURACY, position_on_bezpath, sample_points_on_bezpath, tangent_on_bezpath};
1+
use super::algorithms::bezpath_algorithms::{self, position_on_bezpath, sample_points_on_bezpath, tangent_on_bezpath};
22
use super::algorithms::offset_subpath::offset_subpath;
33
use super::misc::{CentroidType, point_to_dvec2};
44
use super::style::{Fill, Gradient, GradientStops, Stroke};
@@ -16,7 +16,7 @@ use bezier_rs::{Join, ManipulatorGroup, Subpath, SubpathTValue};
1616
use core::f64::consts::PI;
1717
use core::hash::{Hash, Hasher};
1818
use glam::{DAffine2, DVec2};
19-
use kurbo::{Affine, BezPath, Shape};
19+
use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Shape};
2020
use rand::{Rng, SeedableRng};
2121
use std::collections::hash_map::DefaultHasher;
2222
use std::f64::consts::TAU;
@@ -1028,9 +1028,14 @@ async fn bounding_box(_: impl Ctx, vector_data: VectorDataTable) -> VectorDataTa
10281028
let vector_data = vector_data_instance.instance;
10291029

10301030
let mut result = vector_data
1031-
.bounding_box()
1032-
.map(|bounding_box| VectorData::from_subpath(Subpath::new_rect(bounding_box[0], bounding_box[1])))
1031+
.bounding_box_rect()
1032+
.map(|bbox| {
1033+
let mut vector_data = VectorData::default();
1034+
vector_data.append_bezpath(bbox.to_path(DEFAULT_ACCURACY));
1035+
vector_data
1036+
})
10331037
.unwrap_or_default();
1038+
10341039
result.style = vector_data.style.clone();
10351040
result.style.set_stroke_transform(DAffine2::IDENTITY);
10361041

@@ -1413,7 +1418,7 @@ async fn subpath_segment_lengths(_: impl Ctx, vector_data: VectorDataTable) -> V
14131418
.stroke_bezpath_iter()
14141419
.flat_map(|mut bezpath| {
14151420
bezpath.apply_affine(Affine::new(transform.to_cols_array()));
1416-
bezpath.segments().map(|segment| segment.perimeter(PERIMETER_ACCURACY)).collect::<Vec<f64>>()
1421+
bezpath.segments().map(|segment| segment.perimeter(DEFAULT_ACCURACY)).collect::<Vec<f64>>()
14171422
})
14181423
.collect::<Vec<f64>>()
14191424
})

0 commit comments

Comments
 (0)