1use crate::{Contour, Point};
6
7#[derive(Clone, Copy, Debug, PartialEq)]
9pub struct PathSample {
10 pub position: Point,
12 pub tangent: Point,
14}
15
16#[derive(Clone, Debug)]
20pub struct ContourMeasure {
21 points: Vec<Point>,
22 distances: Vec<f32>,
26 closed: bool,
27}
28
29impl ContourMeasure {
30 pub(crate) fn of(contour: &Contour) -> Option<Self> {
34 let mut points = Vec::with_capacity(contour.points.len());
35 let mut distances = Vec::with_capacity(contour.points.len());
36 let mut total = 0.0;
37 for &point in &contour.points {
38 match points.last() {
39 None => {
40 points.push(point);
41 distances.push(0.0);
42 }
43 Some(&previous) => {
44 let step = distance_between(previous, point);
45 if step > 0.0 {
46 total += step;
47 points.push(point);
48 distances.push(total);
49 }
50 }
51 }
52 }
53 (points.len() > 1).then_some(Self {
54 points,
55 distances,
56 closed: contour.closed,
57 })
58 }
59
60 pub fn length(&self) -> f32 {
62 *self
63 .distances
64 .last()
65 .expect("measured contours have length")
66 }
67
68 pub fn is_closed(&self) -> bool {
70 self.closed
71 }
72
73 pub fn sample(&self, distance: f32) -> PathSample {
77 let distance = if distance.is_nan() { 0.0 } else { distance };
81 let distance = distance.clamp(0.0, self.length());
82 let index = self.segment_containing(distance);
83 let (start, end) = (self.points[index], self.points[index + 1]);
84 let span = self.distances[index + 1] - self.distances[index];
85 let fraction = (distance - self.distances[index]) / span;
86 PathSample {
87 position: lerp(start, end, fraction),
88 tangent: unit_vector(start, end),
89 }
90 }
91
92 pub fn segment(&self, start: f32, end: f32) -> Option<Contour> {
97 if start.is_nan() || end.is_nan() {
98 return None;
99 }
100 let length = self.length();
101 let (start, end) = (start.clamp(0.0, length), end.clamp(0.0, length));
102 if end <= start {
103 return None;
104 }
105 let mut points = vec![self.sample(start).position];
106 let first = self.segment_containing(start);
107 let last = self.segment_containing(end);
108 points.extend_from_slice(&self.points[first + 1..=last]);
109 points.push(self.sample(end).position);
110 Some(Contour {
111 points: dedup_adjacent(points),
112 closed: false,
113 has_segments: true,
116 })
117 }
118
119 fn segment_containing(&self, distance: f32) -> usize {
121 match self
122 .distances
123 .binary_search_by(|entry| entry.partial_cmp(&distance).expect("finite distances"))
124 {
125 Ok(index) => index.min(self.points.len() - 2),
126 Err(insert) => insert - 1,
127 }
128 }
129}
130
131fn distance_between(a: Point, b: Point) -> f32 {
132 ((b.x - a.x).powi(2) + (b.y - a.y).powi(2)).sqrt()
133}
134
135fn lerp(a: Point, b: Point, t: f32) -> Point {
136 Point::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)
137}
138
139fn unit_vector(a: Point, b: Point) -> Point {
140 let length = distance_between(a, b);
141 Point::new((b.x - a.x) / length, (b.y - a.y) / length)
142}
143
144fn dedup_adjacent(points: Vec<Point>) -> Vec<Point> {
145 let mut out: Vec<Point> = Vec::with_capacity(points.len());
146 for point in points {
147 if out.last() != Some(&point) {
148 out.push(point);
149 }
150 }
151 out
152}
153
154#[cfg(test)]
155mod tests {
156 use crate::{Path, PathBuilder, Point};
157
158 fn measured(build: impl FnOnce(&mut PathBuilder)) -> Vec<crate::ContourMeasure> {
159 let mut builder = PathBuilder::new();
160 build(&mut builder);
161 let path: std::sync::Arc<Path> = builder.build();
162 path.measure(0.05)
163 }
164
165 #[test]
166 fn a_straight_line_measures_its_own_length() {
167 let measures = measured(|b| {
168 b.move_to((10.0, 10.0)).line_to((10.0, 60.0));
169 });
170 assert_eq!(measures.len(), 1);
171 assert!((measures[0].length() - 50.0).abs() < 1e-3);
172 assert!(!measures[0].is_closed());
173 }
174
175 #[test]
176 fn sampling_walks_the_line_and_clamps_past_its_ends() {
177 let measures = measured(|b| {
178 b.move_to((0.0, 0.0)).line_to((100.0, 0.0));
179 });
180 let middle = measures[0].sample(25.0);
181 assert!((middle.position.x - 25.0).abs() < 1e-3);
182 assert!((middle.tangent.x - 1.0).abs() < 1e-3);
183 assert!(middle.tangent.y.abs() < 1e-3);
184
185 assert!((measures[0].sample(-10.0).position.x - 0.0).abs() < 1e-3);
187 assert!((measures[0].sample(500.0).position.x - 100.0).abs() < 1e-3);
188 }
189
190 #[test]
191 fn a_closed_square_measures_its_whole_perimeter() {
192 let measures = measured(|b| {
193 b.rect(crate::Rect::new(0.0, 0.0, 30.0, 30.0));
194 });
195 assert_eq!(measures.len(), 1);
196 assert!(measures[0].is_closed());
197 assert!((measures[0].length() - 120.0).abs() < 1e-3);
199 }
200
201 #[test]
202 fn a_circle_measures_near_two_pi_r() {
203 let measures = measured(|b| {
204 b.circle((0.0, 0.0), 50.0);
205 });
206 let circumference = std::f32::consts::TAU * 50.0;
207 let error = (measures[0].length() - circumference).abs() / circumference;
209 assert!(error < 0.001, "circumference off by {error}");
210 }
211
212 #[test]
213 fn each_contour_is_measured_separately() {
214 let measures = measured(|b| {
215 b.move_to((0.0, 0.0)).line_to((10.0, 0.0));
216 b.move_to((0.0, 20.0)).line_to((0.0, 60.0));
217 });
218 assert_eq!(measures.len(), 2);
219 assert!((measures[0].length() - 10.0).abs() < 1e-3);
220 assert!((measures[1].length() - 40.0).abs() < 1e-3);
221 }
222
223 #[test]
224 fn a_segment_spans_exactly_the_requested_stretch() {
225 let measures = measured(|b| {
226 b.move_to((0.0, 0.0))
227 .line_to((100.0, 0.0))
228 .line_to((100.0, 100.0));
229 });
230 let segment = measures[0].segment(50.0, 150.0).expect("non-empty");
231 assert_eq!(segment.points.first(), Some(&Point::new(50.0, 0.0)));
232 assert_eq!(segment.points.last(), Some(&Point::new(100.0, 50.0)));
233 assert!(segment.points.contains(&Point::new(100.0, 0.0)));
235 assert!(!segment.closed);
236 }
237
238 #[test]
239 fn an_empty_or_reversed_range_measures_nothing() {
240 let measures = measured(|b| {
241 b.move_to((0.0, 0.0)).line_to((10.0, 0.0));
242 });
243 assert!(measures[0].segment(5.0, 5.0).is_none());
244 assert!(measures[0].segment(8.0, 2.0).is_none());
245 }
246
247 #[test]
248 fn non_finite_distances_answer_instead_of_panicking() {
249 let measures = measured(|b| {
250 b.move_to((0.0, 0.0)).line_to((10.0, 0.0));
251 });
252 assert_eq!(measures[0].sample(f32::NAN).position, Point::new(0.0, 0.0));
253 assert!(measures[0].segment(f32::NAN, 5.0).is_none());
254 assert!(measures[0].segment(0.0, f32::INFINITY).is_some());
255 }
256
257 #[test]
258 fn degenerate_contours_are_dropped_rather_than_measured() {
259 let measures = measured(|b| {
261 b.move_to((5.0, 5.0));
262 });
263 assert!(measures.is_empty());
264 }
265}