1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use crate::geom::vector;
use crate::path::{PathEvent, Winding};
pub fn compute_winding<Iter>(path: &mut Iter) -> Option<Winding>
where
Iter: Iterator<Item = PathEvent>,
{
let first = if let Some(PathEvent::Begin { at }) = path.next() {
at
} else {
return None;
};
let mut area = 0.0;
let mut v0 = vector(0.0, 0.0);
for evt in path {
match evt {
PathEvent::Begin { .. } => {
return None;
}
PathEvent::End { last, first, .. } => {
let v1 = last - first;
area += v0.cross(v1);
return if area > 0.0 {
Some(Winding::Positive)
} else {
Some(Winding::Negative)
};
}
PathEvent::Line { to, .. } => {
let v1 = to - first;
area += v0.cross(v1);
v0 = v1;
}
PathEvent::Quadratic { ctrl, to, .. } => {
let v1 = ctrl - first;
let v2 = to - first;
area += v0.cross(v1) + v1.cross(v2);
v0 = v2;
}
PathEvent::Cubic {
ctrl1, ctrl2, to, ..
} => {
let v1 = ctrl1 - first;
let v2 = ctrl2 - first;
let v3 = to - first;
area += v0.cross(v1) + v1.cross(v2) + v2.cross(v3);
v0 = v3;
}
};
}
None
}
pub struct Windings<Iter = PathEvent>(pub Iter);
impl<Iter: Iterator<Item = PathEvent>> Iterator for Windings<Iter> {
type Item = Winding;
fn next(&mut self) -> Option<Winding> {
compute_winding(&mut self.0)
}
}
#[test]
fn path_winding() {
use crate::geom::point;
let mut path = crate::path::Path::builder();
path.begin(point(0.0, 0.0));
path.line_to(point(1.0, 0.0));
path.line_to(point(1.0, 1.0));
path.line_to(point(0.0, 1.0));
path.close();
path.begin(point(0.0, 0.0));
path.line_to(point(0.0, 1.0));
path.line_to(point(1.0, 1.0));
path.line_to(point(1.0, 0.0));
path.close();
let path = path.build();
let mut iter = path.iter();
assert_eq!(compute_winding(&mut iter), Some(Winding::Positive));
assert_eq!(compute_winding(&mut iter), Some(Winding::Negative));
assert_eq!(compute_winding(&mut iter), None);
}