1use alloc::vec;
33use alloc::vec::Vec;
34
35use crate::affine::Affine2D;
36use crate::error::ShapeError;
37use crate::stroke::{LineCap, LineJoin, StrokeStyle};
38
39#[derive(Debug, Clone, Copy, PartialEq)]
41pub enum PathCommand {
42 MoveTo(f32, f32),
44 LineTo(f32, f32),
46 QuadTo(f32, f32, f32, f32),
48 CubicTo(f32, f32, f32, f32, f32, f32),
50 Close,
52}
53
54#[derive(Debug, Clone, Default, PartialEq)]
56pub struct Path2D {
57 commands: Vec<PathCommand>,
58}
59
60impl Path2D {
61 #[must_use]
63 pub fn new() -> Self {
64 Path2D {
65 commands: Vec::new(),
66 }
67 }
68
69 #[must_use]
71 pub fn commands(&self) -> &[PathCommand] {
72 &self.commands
73 }
74
75 #[must_use]
77 pub fn len(&self) -> usize {
78 self.commands.len()
79 }
80
81 #[must_use]
83 pub fn is_empty(&self) -> bool {
84 self.commands.is_empty()
85 }
86
87 pub fn push(&mut self, cmd: PathCommand) -> &mut Self {
89 self.commands.push(cmd);
90 self
91 }
92
93 #[must_use]
99 pub fn bbox(&self) -> Option<Rect> {
100 let mut b = Rect::empty();
101 let mut cur = (0.0f32, 0.0f32);
102 let mut any = false;
103 for cmd in &self.commands {
104 match *cmd {
105 PathCommand::MoveTo(x, y) => {
106 b.extend(x, y);
107 cur = (x, y);
108 any = true;
109 }
110 PathCommand::LineTo(x, y) => {
111 b.extend(x, y);
112 cur = (x, y);
113 any = true;
114 }
115 PathCommand::QuadTo(cx, cy, x, y) => {
116 b.extend(x, y);
117 let p = [cur, (cx, cy), (x, y)];
118 for t in quad_roots(p[0].0, p[1].0, p[2].0) {
119 b.extend(quad_x(p, t), quad_y(p, t));
120 }
121 for t in quad_roots(p[0].1, p[1].1, p[2].1) {
122 b.extend(quad_x(p, t), quad_y(p, t));
123 }
124 cur = (x, y);
125 any = true;
126 }
127 PathCommand::CubicTo(c1x, c1y, c2x, c2y, x, y) => {
128 b.extend(x, y);
129 let p = [cur, (c1x, c1y), (c2x, c2y), (x, y)];
130 for t in cubic_roots(p[0].0, p[1].0, p[2].0, p[3].0) {
131 b.extend(cubic_x(p, t), cubic_y(p, t));
132 }
133 for t in cubic_roots(p[0].1, p[1].1, p[2].1, p[3].1) {
134 b.extend(cubic_x(p, t), cubic_y(p, t));
135 }
136 cur = (x, y);
137 any = true;
138 }
139 PathCommand::Close => {
140 cur = (0.0, 0.0);
141 any = true;
142 }
143 }
144 }
145 if any {
146 Some(b)
147 } else {
148 None
149 }
150 }
151
152 #[must_use]
158 pub fn transformed(&self, m: &Affine2D) -> Path2D {
159 let mut out = Path2D::new();
160 out.commands.reserve(self.commands.len());
161 for cmd in &self.commands {
162 let t = match *cmd {
163 PathCommand::MoveTo(x, y) => {
164 let (x, y) = m.transform_point(x, y);
165 PathCommand::MoveTo(x, y)
166 }
167 PathCommand::LineTo(x, y) => {
168 let (x, y) = m.transform_point(x, y);
169 PathCommand::LineTo(x, y)
170 }
171 PathCommand::QuadTo(cx, cy, x, y) => {
172 let (cx, cy) = m.transform_point(cx, cy);
173 let (x, y) = m.transform_point(x, y);
174 PathCommand::QuadTo(cx, cy, x, y)
175 }
176 PathCommand::CubicTo(c1x, c1y, c2x, c2y, x, y) => {
177 let (c1x, c1y) = m.transform_point(c1x, c1y);
178 let (c2x, c2y) = m.transform_point(c2x, c2y);
179 let (x, y) = m.transform_point(x, y);
180 PathCommand::CubicTo(c1x, c1y, c2x, c2y, x, y)
181 }
182 PathCommand::Close => PathCommand::Close,
183 };
184 out.push(t);
185 }
186 out
187 }
188
189 #[must_use]
191 pub fn translated(&self, dx: f32, dy: f32) -> Path2D {
192 self.transformed(&Affine2D::translate(dx, dy))
193 }
194
195 pub fn reverse(&mut self) {
197 let reversed = crate::stroke::reverse_commands(&self.commands);
198 self.commands = reversed;
199 }
200
201 #[must_use]
203 pub fn subpath_count(&self) -> usize {
204 self.commands
205 .iter()
206 .filter(|c| matches!(c, PathCommand::MoveTo(..)))
207 .count()
208 }
209
210 #[must_use]
212 pub fn is_closed(&self) -> bool {
213 matches!(self.commands.last(), Some(PathCommand::Close))
214 }
215
216 #[must_use]
224 pub fn flatten(&self, tolerance: f32) -> Vec<Vec<(f32, f32)>> {
225 self.flatten_polylines(tolerance)
226 .into_iter()
227 .map(|p| p.points)
228 .collect()
229 }
230
231 #[must_use]
238 pub(crate) fn flatten_polylines(&self, tolerance: f32) -> Vec<Polyline> {
239 let tol = if tolerance > 0.0 {
240 tolerance
241 } else {
242 self.bbox().map_or(0.25, |b| {
243 (b.width().max(b.height()).max(1.0)) * 0.01
245 })
246 };
247 let mut out: Vec<Polyline> = Vec::new();
248 let mut cur: Vec<(f32, f32)> = Vec::new();
249 let mut pt = (0.0f32, 0.0f32);
250 let mut start = (0.0f32, 0.0f32);
251 let mut drew = false;
252 let mut closed = false;
253 for cmd in &self.commands {
254 match *cmd {
255 PathCommand::MoveTo(x, y) => {
256 if cur.len() > 1 {
257 if drew {
260 cur.push(start);
261 }
262 if !is_degenerate(&cur) {
263 out.push(Polyline {
264 points: core::mem::take(&mut cur),
265 closed: false,
266 });
267 }
268 }
269 cur.clear();
270 pt = (x, y);
271 start = pt;
272 cur.push(pt);
273 drew = false;
274 closed = false;
275 }
276 PathCommand::LineTo(x, y) => {
277 if cur.is_empty() {
278 cur.push(pt);
279 start = pt;
280 }
281 cur.push((x, y));
282 pt = (x, y);
283 drew = true;
284 }
285 PathCommand::QuadTo(cx, cy, x, y) => {
286 if cur.is_empty() {
287 cur.push(pt);
288 start = pt;
289 }
290 flatten_quad(&mut cur, pt, (cx, cy), (x, y), tol);
291 pt = (x, y);
292 drew = true;
293 }
294 PathCommand::CubicTo(c1x, c1y, c2x, c2y, x, y) => {
295 if cur.is_empty() {
296 cur.push(pt);
297 start = pt;
298 }
299 flatten_cubic(&mut cur, pt, (c1x, c1y), (c2x, c2y), (x, y), tol);
300 pt = (x, y);
301 drew = true;
302 }
303 PathCommand::Close => {
304 if cur.len() > 1 {
305 cur.push(start);
307 if !is_degenerate(&cur) {
308 out.push(Polyline {
309 points: core::mem::take(&mut cur),
310 closed: true,
311 });
312 }
313 }
314 cur.clear();
315 pt = start;
316 drew = false;
317 closed = true;
318 }
319 }
320 }
321 let _ = closed;
322 if cur.len() > 1 {
323 if drew {
324 cur.push(start);
325 }
326 if is_degenerate(&cur) {
327 cur.clear();
332 }
333 if cur.len() > 1 {
334 out.push(Polyline {
335 points: cur,
336 closed: false,
337 });
338 }
339 }
340 out
342 }
343
344 #[must_use]
354 pub fn polygon_area(&self) -> f32 {
355 self.flatten(0.0)
356 .iter()
357 .map(|poly| {
358 let mut a = 0.0f32;
359 for (i, p) in poly.iter().enumerate() {
360 let q = poly.get(i + 1).copied().unwrap_or(*p);
361 let finite =
362 p.0.is_finite() && p.1.is_finite() && q.0.is_finite() && q.1.is_finite();
363 if finite {
364 a += p.0 * q.1 - q.0 * p.1;
365 }
366 }
367 a.abs() * 0.5
368 })
369 .sum()
370 }
371}
372
373#[derive(Debug, Clone, Default)]
379pub struct PathBuilder {
380 commands: Vec<PathCommand>,
381 stack: Vec<Affine2D>,
382 current: Affine2D,
383 cursor: (f32, f32),
385 subpath_start: (f32, f32),
387 started: bool,
388}
389
390impl PathBuilder {
391 #[must_use]
393 pub fn new() -> Self {
394 PathBuilder {
395 commands: Vec::new(),
396 stack: Vec::new(),
397 current: Affine2D::IDENTITY,
398 cursor: (0.0, 0.0),
399 subpath_start: (0.0, 0.0),
400 started: false,
401 }
402 }
403
404 #[must_use]
406 pub fn from_path(path: &Path2D) -> Self {
407 let mut b = PathBuilder::new();
408 b.commands.extend_from_slice(path.commands());
409 if let Some(last) = path.commands().last() {
410 b.cursor = last.end_point().unwrap_or((0.0, 0.0));
411 }
412 b
413 }
414
415 #[must_use]
417 pub const fn current_transform(&self) -> Affine2D {
418 self.current
419 }
420
421 #[must_use]
423 pub fn depth(&self) -> usize {
424 self.stack.len()
425 }
426
427 pub fn push_transform(&mut self, m: Affine2D) -> &mut Self {
432 self.current = m.then(&self.current);
438 self.stack.push(m);
439 self
440 }
441
442 #[allow(clippy::result_large_err)]
449 pub fn pop_transform(&mut self) -> Result<Affine2D, ShapeError> {
450 let popped = self
451 .stack
452 .pop()
453 .ok_or(ShapeError::UnbalancedPop { depth: 0 })?;
454 let mut m = self.stack.last().copied().unwrap_or(Affine2D::IDENTITY);
461 for below in self.stack.iter().rev().skip(1) {
462 m = m.then(below);
463 }
464 self.current = m;
465 Ok(popped)
466 }
467
468 pub fn reset_transforms(&mut self) -> &mut Self {
470 self.stack.clear();
471 self.current = Affine2D::IDENTITY;
472 self
473 }
474
475 #[must_use]
477 pub const fn current_point(&self) -> (f32, f32) {
478 self.cursor
479 }
480
481 pub fn move_to(&mut self, x: f32, y: f32) -> &mut Self {
483 let (x, y) = self.current.transform_point(x, y);
484 self.cursor = (x, y);
485 self.subpath_start = (x, y);
486 self.started = true;
487 self.commands.push(PathCommand::MoveTo(x, y));
488 self
489 }
490
491 pub fn move_by(&mut self, dx: f32, dy: f32) -> &mut Self {
498 let (dx, dy) = self.current.transform_vector(dx, dy);
499 let (cx, cy) = self.cursor;
500 self.move_to_device(cx + dx, cy + dy)
501 }
502
503 fn move_to_device(&mut self, x: f32, y: f32) -> &mut Self {
505 self.cursor = (x, y);
506 self.subpath_start = (x, y);
507 self.started = true;
508 self.commands.push(PathCommand::MoveTo(x, y));
509 self
510 }
511
512 pub fn line_to(&mut self, x: f32, y: f32) -> &mut Self {
514 let (x, y) = self.current.transform_point(x, y);
515 self.cursor = (x, y);
516 self.commands.push(PathCommand::LineTo(x, y));
517 self
518 }
519
520 pub fn line_by(&mut self, dx: f32, dy: f32) -> &mut Self {
522 let (dx, dy) = self.current.transform_vector(dx, dy);
523 let (cx, cy) = self.cursor;
524 let x = cx + dx;
525 let y = cy + dy;
526 self.cursor = (x, y);
527 self.commands.push(PathCommand::LineTo(x, y));
528 self
529 }
530
531 pub fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) -> &mut Self {
533 let (cx, cy) = self.current.transform_point(cx, cy);
534 let (x, y) = self.current.transform_point(x, y);
535 self.cursor = (x, y);
536 self.commands.push(PathCommand::QuadTo(cx, cy, x, y));
537 self
538 }
539
540 pub fn cubic_to(
542 &mut self,
543 c1x: f32,
544 c1y: f32,
545 c2x: f32,
546 c2y: f32,
547 x: f32,
548 y: f32,
549 ) -> &mut Self {
550 let (c1x, c1y) = self.current.transform_point(c1x, c1y);
551 let (c2x, c2y) = self.current.transform_point(c2x, c2y);
552 let (x, y) = self.current.transform_point(x, y);
553 self.cursor = (x, y);
554 self.commands
555 .push(PathCommand::CubicTo(c1x, c1y, c2x, c2y, x, y));
556 self
557 }
558
559 pub fn close(&mut self) -> &mut Self {
561 self.commands.push(PathCommand::Close);
562 self.cursor = self.subpath_start;
563 self
564 }
565
566 pub fn add_polygon(&mut self, points: &[(f32, f32)], closed: bool) -> &mut Self {
568 let Some(first) = points.first() else {
569 return self;
570 };
571 self.move_to(first.0, first.1);
572 for p in points.iter().skip(1) {
573 self.line_to(p.0, p.1);
574 }
575 if closed {
576 self.close();
577 }
578 self
579 }
580
581 pub fn rect(&mut self, x: f32, y: f32, w: f32, h: f32) -> &mut Self {
583 self.move_to(x, y);
584 self.line_to(x + w, y);
585 self.line_to(x + w, y + h);
586 self.line_to(x, y + h);
587 self.close()
588 }
589
590 pub fn circle(&mut self, cx: f32, cy: f32, r: f32) -> &mut Self {
593 let k = r * 0.552_284_8;
595 self.move_to(cx + r, cy);
596 self.cubic_to(cx + r, cy + k, cx + k, cy + r, cx, cy + r);
597 self.cubic_to(cx - k, cy + r, cx - r, cy + k, cx - r, cy);
598 self.cubic_to(cx - r, cy - k, cx - k, cy - r, cx, cy - r);
599 self.cubic_to(cx + k, cy - r, cx + r, cy - k, cx + r, cy);
600 self.close()
601 }
602
603 pub fn extend(&mut self, path: &Path2D) -> &mut Self {
608 let mut pt = (0.0f32, 0.0f32);
609 for cmd in path.commands() {
610 match *cmd {
611 PathCommand::MoveTo(x, y) => {
612 self.move_to(x, y);
613 pt = self.cursor;
614 }
615 PathCommand::LineTo(x, y) => {
616 self.line_to(x, y);
617 pt = self.cursor;
618 }
619 PathCommand::QuadTo(cx, cy, x, y) => {
620 self.quad_to(cx, cy, x, y);
621 pt = self.cursor;
622 }
623 PathCommand::CubicTo(c1x, c1y, c2x, c2y, x, y) => {
624 self.cubic_to(c1x, c1y, c2x, c2y, x, y);
625 pt = self.cursor;
626 }
627 PathCommand::Close => {
628 self.close();
629 pt = self.subpath_start;
630 }
631 }
632 }
633 let _ = pt;
634 self
635 }
636
637 pub fn add_stroke(&mut self, path: &Path2D, width: f32, style: StrokeStyle) -> &mut Self {
639 let expanded = crate::stroke::stroke_path(path, width, style);
640 self.extend(&expanded)
641 }
642
643 #[must_use]
645 pub fn commands(&self) -> &[PathCommand] {
646 &self.commands
647 }
648
649 #[must_use]
651 pub fn len(&self) -> usize {
652 self.commands.len()
653 }
654
655 #[must_use]
657 pub fn is_empty(&self) -> bool {
658 self.commands.is_empty()
659 }
660
661 #[must_use]
664 pub fn build(&self) -> Path2D {
665 Path2D {
666 commands: self.commands.clone(),
667 }
668 }
669
670 pub const DEFAULT_CAP: LineCap = LineCap::Butt;
672 pub const DEFAULT_JOIN: LineJoin = LineJoin::Miter;
674}
675
676impl PathCommand {
677 #[must_use]
679 pub fn end_point(&self) -> Option<(f32, f32)> {
680 match *self {
681 PathCommand::MoveTo(x, y) | PathCommand::LineTo(x, y) => Some((x, y)),
682 PathCommand::QuadTo(_, _, x, y) | PathCommand::CubicTo(_, _, _, _, x, y) => {
683 Some((x, y))
684 }
685 PathCommand::Close => None,
686 }
687 }
688}
689
690#[derive(Debug, Clone, PartialEq)]
697pub(crate) struct Polyline {
698 pub points: Vec<(f32, f32)>,
700 pub closed: bool,
702}
703
704#[derive(Debug, Clone, Copy, PartialEq)]
706pub struct Rect {
707 pub min_x: f32,
709 pub min_y: f32,
711 pub max_x: f32,
713 pub max_y: f32,
715}
716
717impl Default for Rect {
718 fn default() -> Self {
719 Rect::empty()
720 }
721}
722
723impl Rect {
724 #[must_use]
726 pub const fn empty() -> Self {
727 Rect {
728 min_x: f32::INFINITY,
729 min_y: f32::INFINITY,
730 max_x: f32::NEG_INFINITY,
731 max_y: f32::NEG_INFINITY,
732 }
733 }
734
735 #[must_use]
737 pub fn from_corners(x0: f32, y0: f32, x1: f32, y1: f32) -> Self {
738 Rect {
739 min_x: if x0 < x1 { x0 } else { x1 },
740 min_y: if y0 < y1 { y0 } else { y1 },
741 max_x: if x0 > x1 { x0 } else { x1 },
742 max_y: if y0 > y1 { y0 } else { y1 },
743 }
744 }
745
746 pub fn extend(&mut self, x: f32, y: f32) {
748 if x < self.min_x {
749 self.min_x = x;
750 }
751 if y < self.min_y {
752 self.min_y = y;
753 }
754 if x > self.max_x {
755 self.max_x = x;
756 }
757 if y > self.max_y {
758 self.max_y = y;
759 }
760 }
761
762 #[must_use]
764 pub const fn is_empty(&self) -> bool {
765 self.min_x > self.max_x
766 }
767
768 #[must_use]
770 pub fn width(&self) -> f32 {
771 if self.is_empty() {
772 0.0
773 } else {
774 self.max_x - self.min_x
775 }
776 }
777
778 #[must_use]
780 pub fn height(&self) -> f32 {
781 if self.is_empty() {
782 0.0
783 } else {
784 self.max_y - self.min_y
785 }
786 }
787
788 #[must_use]
790 pub fn contains(&self, x: f32, y: f32) -> bool {
791 !self.is_empty() && x >= self.min_x && x <= self.max_x && y >= self.min_y && y <= self.max_y
792 }
793
794 #[must_use]
796 pub fn translated(&self, dx: f32, dy: f32) -> Rect {
797 if self.is_empty() {
798 return Rect::empty();
799 }
800 Rect::from_corners(
801 self.min_x + dx,
802 self.min_y + dy,
803 self.max_x + dx,
804 self.max_y + dy,
805 )
806 }
807}
808
809fn quad_roots(a0: f32, a1: f32, a2: f32) -> Vec<f32> {
811 let qa = 2.0 * (a0 - 2.0 * a1 + a2);
812 let qb = 2.0 * (a1 - a0);
813 if libm::fabsf(qa) < 1e-9 {
814 return Vec::new();
815 }
816 let t = -qb / qa;
817 if t > 0.0 && t < 1.0 {
818 vec![t]
819 } else {
820 Vec::new()
821 }
822}
823
824fn cubic_roots(a0: f32, a1: f32, a2: f32, a3: f32) -> Vec<f32> {
826 let qa = 3.0 * (-a0 + 3.0 * a1 - 3.0 * a2 + a3);
827 let qb = 6.0 * (a0 - 2.0 * a1 + a2);
828 let qc = 3.0 * (a1 - a0);
829 let mut out = Vec::new();
830 let mut push = |t: f32| {
831 if t > 0.0 && t < 1.0 {
832 out.push(t);
833 }
834 };
835 if libm::fabsf(qa) < 1e-9 {
836 if libm::fabsf(qb) >= 1e-9 {
837 push(-qc / qb);
838 }
839 return out;
840 }
841 let disc = qb * qb - 4.0 * qa * qc;
842 if disc >= 0.0 {
843 let s = libm::sqrtf(disc);
844 push((-qb + s) / (2.0 * qa));
845 push((-qb - s) / (2.0 * qa));
846 }
847 out
848}
849
850fn quad_x(p: [(f32, f32); 3], t: f32) -> f32 {
852 let mt = 1.0 - t;
853 mt * mt * p[0].0 + 2.0 * mt * t * p[1].0 + t * t * p[2].0
854}
855
856fn quad_y(p: [(f32, f32); 3], t: f32) -> f32 {
858 let mt = 1.0 - t;
859 mt * mt * p[0].1 + 2.0 * mt * t * p[1].1 + t * t * p[2].1
860}
861
862fn cubic_x(p: [(f32, f32); 4], t: f32) -> f32 {
864 let mt = 1.0 - t;
865 mt * mt * mt * p[0].0
866 + 3.0 * mt * mt * t * p[1].0
867 + 3.0 * mt * t * t * p[2].0
868 + t * t * t * p[3].0
869}
870
871fn cubic_y(p: [(f32, f32); 4], t: f32) -> f32 {
873 let mt = 1.0 - t;
874 mt * mt * mt * p[0].1
875 + 3.0 * mt * mt * t * p[1].1
876 + 3.0 * mt * t * t * p[2].1
877 + t * t * t * p[3].1
878}
879
880fn is_degenerate(pts: &[(f32, f32)]) -> bool {
886 let Some(first) = pts.first() else {
887 return true;
888 };
889 pts.iter().all(|p| p.0 == first.0 && p.1 == first.1)
890}
891
892fn segment_count(p0: (f32, f32), p1: (f32, f32), p2: (f32, f32), cubic: bool, tol: f32) -> usize {
898 let tol = if tol > 1e-6 { tol } else { 1e-6 };
899 let d2 = if cubic {
900 let ax = libm::fabsf(p2.0 - 2.0 * p1.0 + p0.0);
902 let ay = libm::fabsf(p2.1 - 2.0 * p1.1 + p0.1);
903 libm::sqrtf(ax * ax + ay * ay)
904 } else {
905 let ax = libm::fabsf(p1.0 - p0.0);
906 let ay = libm::fabsf(p1.1 - p0.1);
907 libm::sqrtf(ax * ax + ay * ay)
908 };
909 if d2 <= tol {
910 return 1;
911 }
912 let n = libm::sqrtf(d2 / tol) * 2.0;
913 let n = if n.is_finite() { n as usize } else { 64 };
914 n.clamp(1, 64) }
916
917fn flatten_quad(
919 out: &mut Vec<(f32, f32)>,
920 p0: (f32, f32),
921 c: (f32, f32),
922 p1: (f32, f32),
923 tol: f32,
924) {
925 let n = segment_count(p0, c, p1, false, tol);
926 for i in 1..=n {
927 let t = i as f32 / n as f32;
928 out.push((quad_x([p0, c, p1], t), quad_y([p0, c, p1], t)));
929 }
930}
931
932fn flatten_cubic(
934 out: &mut Vec<(f32, f32)>,
935 p0: (f32, f32),
936 c1: (f32, f32),
937 c2: (f32, f32),
938 p1: (f32, f32),
939 tol: f32,
940) {
941 let n = segment_count(p0, c1, c2, true, tol);
942 for i in 1..=n {
943 let t = i as f32 / n as f32;
944 out.push((cubic_x([p0, c1, c2, p1], t), cubic_y([p0, c1, c2, p1], t)));
945 }
946}
947
948#[cfg(test)]
949mod tests {
950 #![allow(
951 clippy::unwrap_used,
952 clippy::expect_used,
953 clippy::panic,
954 clippy::indexing_slicing,
955 clippy::float_cmp
956 )]
957 use super::{Path2D, PathBuilder, PathCommand, Rect};
958 use crate::Affine2D;
959
960 fn close(a: f32, b: f32) -> bool {
964 (a - b).abs() < 1e-4
965 }
966
967 fn rect_path(x: f32, y: f32, w: f32, h: f32) -> Path2D {
968 let mut b = PathBuilder::new();
969 b.rect(x, y, w, h);
970 b.build()
971 }
972
973 #[test]
974 fn empty_path_has_no_bbox() {
975 let p = Path2D::new();
976 assert!(p.is_empty());
977 assert_eq!(p.len(), 0);
978 assert!(p.bbox().is_none());
979 assert!(p.flatten(0.0).is_empty());
980 assert_eq!(p.subpath_count(), 0);
981 assert!(!p.is_closed());
982 assert_eq!(p.polygon_area(), 0.0);
983 }
984
985 #[test]
986 fn bbox_of_a_rectangle_is_exact() {
987 let b = rect_path(10.0, 20.0, 30.0, 40.0).bbox().expect("bbox");
988 assert_eq!(b.min_x, 10.0);
989 assert_eq!(b.min_y, 20.0);
990 assert_eq!(b.max_x, 40.0);
991 assert_eq!(b.max_y, 60.0);
992 assert_eq!(b.width(), 30.0);
993 assert_eq!(b.height(), 40.0);
994 assert!(b.contains(10.0, 20.0));
995 }
996
997 #[test]
998 fn bbox_holds_a_cubics_true_extremes() {
999 let mut b = PathBuilder::new();
1001 b.move_to(0.0, 0.0);
1002 b.cubic_to(3.0, 0.0, 3.0, 3.0, 0.0, 3.0);
1003 b.close();
1004 let bbox = b.build().bbox().expect("bbox");
1005 assert!(close(bbox.max_x, 2.25), "max_x {}", bbox.max_x);
1006 let mut q = PathBuilder::new();
1008 q.move_to(0.0, 0.0);
1009 q.quad_to(2.0, 4.0, 4.0, 0.0);
1010 q.close();
1011 let bbox = q.build().bbox().expect("bbox");
1012 assert!(close(bbox.max_y, 2.0), "max_y {}", bbox.max_y);
1013 }
1014
1015 #[test]
1016 fn rect_and_polygon_helpers_agree() {
1017 let mut a = PathBuilder::new();
1018 a.rect(0.0, 0.0, 10.0, 10.0);
1019 let mut b = PathBuilder::new();
1020 b.add_polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)], true);
1021 assert_eq!(a.build().bbox(), b.build().bbox());
1022 assert_eq!(a.build().commands().len(), 5);
1023 let mut c = PathBuilder::new();
1025 c.add_polygon(&[], true);
1026 assert!(c.is_empty());
1027 let mut d = PathBuilder::new();
1029 d.add_polygon(&[(1.0, 2.0)], true);
1030 assert_eq!(d.len(), 2);
1031 }
1032
1033 #[test]
1034 fn circle_is_roughly_circular() {
1035 let mut b = PathBuilder::new();
1036 b.circle(50.0, 50.0, 20.0);
1037 let p = b.build();
1038 let bbox = p.bbox().expect("bbox");
1039 assert!(
1040 close(bbox.min_x, 30.0) && close(bbox.max_x, 70.0),
1041 "{bbox:?}"
1042 );
1043 assert!(close(bbox.width(), bbox.height()), "{bbox:?}");
1044 let area = p.polygon_area();
1046 let want = core::f32::consts::PI * 400.0;
1047 assert!(
1048 (area - want).abs() < want * 0.01,
1049 "circle area {area} vs {want}"
1050 );
1051 }
1052
1053 #[test]
1054 fn flatten_respects_the_tolerance() {
1055 let mut b = PathBuilder::new();
1056 b.move_to(0.0, 0.0);
1057 b.cubic_to(0.0, 100.0, 100.0, 100.0, 100.0, 0.0);
1058 b.close();
1059 let p = b.build();
1060 let coarse = p.flatten(10.0);
1061 let fine = p.flatten(0.01);
1062 assert!(
1063 fine[0].len() > coarse[0].len(),
1064 "finer tolerance: {} vs {}",
1065 fine[0].len(),
1066 coarse[0].len()
1067 );
1068 assert!(fine[0].len() <= 66, "clamped: {}", fine[0].len());
1071 let mut f = PathBuilder::new();
1073 f.move_to(0.0, 0.0);
1074 f.cubic_to(1.0, 0.0, 2.0, 0.0, 3.0, 0.0);
1075 f.close();
1076 assert_eq!(f.build().flatten(1.0)[0].len(), 3);
1078 }
1079
1080 #[test]
1081 fn flatten_closes_a_closed_subpath_and_leaves_an_open_one() {
1082 let closed = rect_path(0.0, 0.0, 5.0, 5.0);
1083 let polys = closed.flatten(0.0);
1084 assert_eq!(polys.len(), 1);
1085 assert_eq!(polys[0][0], polys[0][polys[0].len() - 1]);
1086
1087 let mut b = PathBuilder::new();
1088 b.move_to(0.0, 0.0);
1089 b.line_to(10.0, 0.0);
1090 b.line_to(10.0, 10.0);
1091 let open = b.build();
1092 let polys = open.flatten(0.0);
1093 assert_eq!(polys.len(), 1);
1094 assert_eq!(polys[0].last(), Some(&(0.0, 0.0)));
1096 assert!(!open.is_closed());
1097 }
1098
1099 #[test]
1100 fn flatten_of_a_lone_point_is_dropped() {
1101 let mut b = PathBuilder::new();
1102 b.move_to(5.0, 5.0);
1103 assert!(b.build().flatten(0.0).is_empty());
1104 let mut c = PathBuilder::new();
1106 c.move_to(5.0, 5.0);
1107 c.line_to(5.0, 5.0);
1108 c.close();
1109 assert!(c.build().flatten(0.0).is_empty() || c.build().flatten(0.0)[0].len() <= 2);
1110 }
1111
1112 #[test]
1113 fn transform_moves_every_point() {
1114 let p = rect_path(0.0, 0.0, 10.0, 10.0);
1115 let t = p.transformed(&Affine2D::translate(5.0, 7.0));
1116 let b = t.bbox().expect("bbox");
1117 assert_eq!(b.min_x, 5.0);
1118 assert_eq!(b.min_y, 7.0);
1119 assert_eq!(b.width(), 10.0);
1120 assert_eq!(p.bbox().expect("bbox").min_x, 0.0);
1122 assert_eq!(p.translated(5.0, 7.0).bbox(), Some(b));
1124 }
1125
1126 #[test]
1127 fn transform_of_a_curve_is_the_curve_of_the_transformed_points() {
1128 let mut b = PathBuilder::new();
1129 b.move_to(0.0, 0.0);
1130 b.cubic_to(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
1131 b.close();
1132 let p = b.build();
1133 let m = Affine2D::new(2.0, 0.0, 0.0, 3.0, 1.0, -1.0);
1134 let t = p.transformed(&m);
1135 for (a, b2) in p.commands().iter().zip(t.commands().iter()) {
1137 let want = |x: f32, y: f32| -> (f32, f32) { m.transform_point(x, y) };
1140 match (*a, *b2) {
1141 (PathCommand::MoveTo(x1, y1), PathCommand::MoveTo(x2, y2))
1142 | (PathCommand::LineTo(x1, y1), PathCommand::LineTo(x2, y2)) => {
1143 let w = want(x1, y1);
1144 assert!(close(w.0, x2) && close(w.1, y2));
1145 }
1146 (PathCommand::QuadTo(a1, a2, a3, a4), PathCommand::QuadTo(b1, b2, b3, b4)) => {
1147 for (src, dst) in [((a1, a2), (b1, b2)), ((a3, a4), (b3, b4))] {
1148 let w = want(src.0, src.1);
1149 assert!(close(w.0, dst.0) && close(w.1, dst.1));
1150 }
1151 }
1152 (
1153 PathCommand::CubicTo(a1, a2, a3, a4, a5, a6),
1154 PathCommand::CubicTo(b1, b2, b3, b4, b5, b6),
1155 ) => {
1156 let pairs = [
1157 ((a1, a2), (b1, b2)),
1158 ((a3, a4), (b3, b4)),
1159 ((a5, a6), (b5, b6)),
1160 ];
1161 for (src, dst) in pairs {
1162 let w = want(src.0, src.1);
1163 assert!(close(w.0, dst.0) && close(w.1, dst.1));
1164 }
1165 }
1166 (PathCommand::Close, PathCommand::Close) => {}
1167 _ => panic!("command shape changed: {a:?} -> {b2:?}"),
1168 }
1169 }
1170 }
1171
1172 #[test]
1173 fn transform_stack_composes_and_pops() {
1174 let mut b = PathBuilder::new();
1175 assert_eq!(b.depth(), 0);
1176 assert!(b.current_transform().is_identity());
1177 b.push_transform(Affine2D::translate(10.0, 0.0));
1178 assert_eq!(b.depth(), 1);
1179 b.push_transform(Affine2D::scale(2.0, 2.0));
1180 assert_eq!(b.depth(), 2);
1181 b.rect(0.0, 0.0, 5.0, 5.0);
1182 assert_eq!(
1183 b.pop_transform().expect("balanced"),
1184 Affine2D::scale(2.0, 2.0)
1185 );
1186 b.rect(0.0, 0.0, 5.0, 5.0);
1187 b.pop_transform().expect("balanced");
1188 assert_eq!(b.depth(), 0);
1189 assert!(b.current_transform().is_identity());
1190 let bbox = b.build().bbox().expect("bbox");
1191 assert_eq!(bbox.max_x, 20.0);
1193 assert_eq!(bbox.max_y, 10.0);
1194 }
1195
1196 #[test]
1197 fn unbalanced_pop_is_refused() {
1198 let mut b = PathBuilder::new();
1199 match b.pop_transform().unwrap_err() {
1200 crate::ShapeError::UnbalancedPop { depth } => assert_eq!(depth, 0),
1201 other => panic!("expected UnbalancedPop, got {other:?}"),
1202 }
1203 b.push_transform(Affine2D::scale(0.0, 0.0));
1206 assert!(b.pop_transform().is_ok());
1207 b.reset_transforms();
1208 assert_eq!(b.depth(), 0);
1209 }
1210
1211 #[test]
1212 fn transform_is_applied_at_add_time() {
1213 let mut b = PathBuilder::new();
1214 b.push_transform(Affine2D::translate(100.0, 100.0));
1215 b.move_to(1.0, 2.0);
1216 assert_eq!(b.current_point(), (101.0, 102.0));
1217 b.line_to(3.0, 4.0);
1218 match b.commands()[1] {
1219 PathCommand::LineTo(x, y) => assert_eq!((x, y), (103.0, 104.0)),
1220 other => panic!("{other:?}"),
1221 }
1222 b.line_by(1.0, 1.0);
1225 assert_eq!(b.current_point(), (104.0, 105.0));
1226 b.move_by(-104.0, -105.0);
1227 assert_eq!(b.current_point(), (0.0, 0.0));
1228 }
1229
1230 #[test]
1231 fn from_path_keeps_the_commands_and_cursor() {
1232 let p = rect_path(1.0, 2.0, 3.0, 4.0);
1233 let b = PathBuilder::from_path(&p);
1234 assert_eq!(b.len(), p.len());
1235 assert!(b.current_point() == (0.0, 0.0) || b.current_point() == (0.0, 0.0));
1239 }
1240
1241 #[test]
1242 fn extend_transforms_the_added_path() {
1243 let inner = rect_path(0.0, 0.0, 10.0, 10.0);
1244 let mut b = PathBuilder::new();
1245 b.push_transform(Affine2D::translate(50.0, 0.0));
1246 b.extend(&inner);
1247 let bbox = b.build().bbox().expect("bbox");
1248 assert_eq!(bbox.min_x, 50.0);
1249 assert_eq!(bbox.max_x, 60.0);
1250 }
1251
1252 #[test]
1253 fn reverse_flips_direction_but_keeps_geometry() {
1254 let mut p = rect_path(0.0, 0.0, 10.0, 10.0);
1255 let before = p.bbox().expect("bbox");
1256 let area = p.polygon_area();
1257 p.reverse();
1258 assert_eq!(p.bbox(), Some(before));
1259 assert!(close(p.polygon_area(), area));
1260 assert!(p.is_closed());
1261 }
1262
1263 #[test]
1264 fn subpath_count_and_close_tracking() {
1265 let mut b = PathBuilder::new();
1266 b.rect(0.0, 0.0, 1.0, 1.0);
1267 b.rect(2.0, 0.0, 1.0, 1.0);
1268 b.move_to(5.0, 5.0);
1269 let p = b.build();
1270 assert_eq!(p.subpath_count(), 3);
1271 assert!(!p.is_closed(), "the last subpath is open");
1272 b.close();
1273 assert!(b.build().is_closed());
1274 }
1275
1276 #[test]
1277 fn rect_helpers() {
1278 let r = Rect::empty();
1279 assert!(r.is_empty());
1280 assert_eq!(r.width(), 0.0);
1281 assert_eq!(r.height(), 0.0);
1282 assert!(!r.contains(0.0, 0.0));
1283 let r = Rect::from_corners(10.0, 20.0, 0.0, 5.0);
1284 assert_eq!(r.min_x, 0.0);
1285 assert_eq!(r.max_y, 20.0);
1286 let t = r.translated(1.0, 1.0);
1287 assert_eq!(t.min_x, 1.0);
1288 assert!(Rect::empty().translated(1.0, 1.0).is_empty());
1289 let mut g = r;
1290 g.extend(-5.0, -100.0);
1292 assert_eq!(g.min_x, -5.0);
1293 assert_eq!(g.min_y, -100.0);
1294 assert_eq!(g.max_x, 10.0);
1295 assert_eq!(g.max_y, 20.0);
1296 assert_eq!(Rect::default(), Rect::empty());
1297 }
1298
1299 #[test]
1300 fn command_end_points() {
1301 assert_eq!(PathCommand::MoveTo(1.0, 2.0).end_point(), Some((1.0, 2.0)));
1302 assert_eq!(PathCommand::LineTo(1.0, 2.0).end_point(), Some((1.0, 2.0)));
1303 assert_eq!(
1304 PathCommand::QuadTo(0.0, 0.0, 1.0, 2.0).end_point(),
1305 Some((1.0, 2.0))
1306 );
1307 assert_eq!(
1308 PathCommand::CubicTo(0.0, 0.0, 0.0, 0.0, 1.0, 2.0).end_point(),
1309 Some((1.0, 2.0))
1310 );
1311 assert_eq!(PathCommand::Close.end_point(), None);
1312 }
1313
1314 #[test]
1315 fn zero_tolerance_uses_a_default() {
1316 let mut b = PathBuilder::new();
1317 b.circle(0.0, 0.0, 50.0);
1318 let p = b.build();
1319 let a = p.flatten(0.0);
1320 let b2 = p.flatten(1.0);
1321 assert!(!a.is_empty() && !b2.is_empty());
1322 }
1323
1324 #[test]
1325 fn polygon_area_of_a_square() {
1326 let p = rect_path(0.0, 0.0, 10.0, 10.0);
1327 assert!(close(p.polygon_area(), 100.0), "{}", p.polygon_area());
1328 let mut b = PathBuilder::new();
1330 b.rect(0.0, 0.0, 10.0, 10.0);
1331 b.rect(20.0, 0.0, 10.0, 10.0);
1332 assert!(close(b.build().polygon_area(), 200.0));
1333 }
1334
1335 #[test]
1336 fn build_is_a_snapshot() {
1337 let mut b = PathBuilder::new();
1338 b.rect(0.0, 0.0, 1.0, 1.0);
1339 let snapshot = b.build();
1340 b.rect(10.0, 10.0, 1.0, 1.0);
1341 assert_eq!(snapshot.len(), 5, "the snapshot did not grow");
1342 assert_eq!(b.len(), 10);
1343 }
1344}