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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
use super::{swap_remove_to_first, trivial_hull};
use crate::algorithm::kernels::*;
use crate::{Coordinate, GeoNum, LineString};
pub fn graham_hull<T>(mut points: &mut [Coordinate<T>], include_on_hull: bool) -> LineString<T>
where
T: GeoNum,
{
if points.len() < 4 {
return trivial_hull(points, include_on_hull);
}
let mut output = Vec::with_capacity(points.len());
use crate::utils::least_index;
use std::cmp::Ordering;
let min_idx = least_index(points);
let head = swap_remove_to_first(&mut points, min_idx);
output.push(*head);
let cmp = |q: &Coordinate<T>, r: &Coordinate<T>| match T::Ker::orient2d(*q, *head, *r) {
Orientation::CounterClockwise => Ordering::Greater,
Orientation::Clockwise => Ordering::Less,
Orientation::Collinear => {
let dist1 = T::Ker::square_euclidean_distance(*head, *q);
let dist2 = T::Ker::square_euclidean_distance(*head, *r);
dist1.partial_cmp(&dist2).unwrap()
}
};
points.sort_unstable_by(cmp);
for pt in points.iter() {
while output.len() > 1 {
let len = output.len();
match T::Ker::orient2d(output[len - 2], output[len - 1], *pt) {
Orientation::CounterClockwise => {
break;
}
Orientation::Clockwise => {
output.pop();
}
Orientation::Collinear => {
if include_on_hull {
break;
} else {
output.pop();
}
}
}
}
if include_on_hull || pt != output.last().unwrap() {
output.push(*pt);
}
}
let mut output = LineString(output);
output.close();
output
}
#[cfg(test)]
mod test {
use super::*;
use crate::algorithm::is_convex::IsConvex;
fn test_convexity<T: GeoNum>(initial: &[(T, T)]) {
let mut v: Vec<_> = initial
.iter()
.map(|e| Coordinate::from((e.0, e.1)))
.collect();
let hull = graham_hull(&mut v, false);
assert!(hull.is_strictly_ccw_convex());
let hull = graham_hull(&mut v, true);
assert!(hull.is_ccw_convex());
}
#[test]
fn test_graham_hull_ccw() {
let initial = vec![
(1.0, 0.0),
(2.0, 1.0),
(1.75, 1.1),
(1.0, 2.0),
(0.0, 1.0),
(1.0, 0.0),
];
test_convexity(&initial);
}
#[test]
fn graham_hull_test1() {
let v: Vec<_> = vec![(0, 0), (4, 0), (4, 1), (1, 1), (1, 4), (0, 4), (0, 0)];
test_convexity(&v);
}
#[test]
fn graham_hull_test2() {
let v = vec![
(0, 10),
(1, 1),
(10, 0),
(1, -1),
(0, -10),
(-1, -1),
(-10, 0),
(-1, 1),
(0, 10),
];
test_convexity(&v);
}
#[test]
fn graham_test_complex() {
let v = include!("../test_fixtures/poly1.rs");
test_convexity(&v);
}
#[test]
fn quick_hull_test_complex_2() {
let coords = include!("../test_fixtures/poly2.rs");
test_convexity(&coords);
}
}