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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use std::collections::HashSet;
use std::fmt;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use crate::{Distance, GPSBounds, Line, PolyLine, Polygon, Pt2D};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Ring {
pts: Vec<Pt2D>,
}
impl Ring {
pub fn new(pts: Vec<Pt2D>) -> Result<Ring> {
if pts.len() < 3 {
bail!("Can't make a ring with < 3 points");
}
if pts[0] != *pts.last().unwrap() {
bail!("Can't make a ring with mismatching first/last points");
}
if pts.windows(2).any(|pair| pair[0] == pair[1]) {
bail!("Ring has ~dupe adjacent pts");
}
let result = Ring { pts };
let mut seen_pts = HashSet::new();
for pt in result.pts.iter().skip(1) {
seen_pts.insert(pt.to_hashable());
}
if seen_pts.len() != result.pts.len() - 1 {
bail!("Ring has repeat non-adjacent points");
}
Ok(result)
}
pub fn must_new(pts: Vec<Pt2D>) -> Ring {
Ring::new(pts).unwrap()
}
pub fn to_outline(&self, thickness: Distance) -> Polygon {
PolyLine::unchecked_new(self.pts.clone()).make_polygons(thickness)
}
pub fn into_polygon(self) -> Polygon {
Polygon::with_holes(self, Vec::new())
}
pub fn points(&self) -> &Vec<Pt2D> {
&self.pts
}
pub fn into_points(self) -> Vec<Pt2D> {
self.pts
}
pub fn all_intersections(&self, other: &PolyLine) -> Vec<Pt2D> {
let mut hits = Vec::new();
let mut seen = HashSet::new();
for l1 in other.lines() {
for l2 in self
.pts
.windows(2)
.map(|pair| Line::must_new(pair[0], pair[1]))
{
if let Some(pt) = l1.intersection(&l2) {
if !seen.contains(&pt.to_hashable()) {
hits.push(pt);
seen.insert(pt.to_hashable());
}
}
}
}
hits
}
pub(crate) fn get_both_slices_btwn(
&self,
pt1: Pt2D,
pt2: Pt2D,
) -> Option<(PolyLine, PolyLine)> {
assert!(pt1 != pt2);
let pl = PolyLine::unchecked_new(self.pts.clone());
let mut dist1 = pl.dist_along_of_point(pt1)?.0;
let mut dist2 = pl.dist_along_of_point(pt2)?.0;
if dist1 > dist2 {
std::mem::swap(&mut dist1, &mut dist2);
}
if dist1 == dist2 {
return None;
}
let candidate1 = pl.maybe_exact_slice(dist1, dist2).ok()?;
let candidate2 = pl
.maybe_exact_slice(dist2, pl.length())
.ok()?
.must_extend(pl.maybe_exact_slice(Distance::ZERO, dist1).ok()?);
Some((candidate1, candidate2))
}
pub fn get_shorter_slice_btwn(&self, pt1: Pt2D, pt2: Pt2D) -> Option<PolyLine> {
let (candidate1, candidate2) = self.get_both_slices_btwn(pt1, pt2)?;
if candidate1.length() < candidate2.length() {
Some(candidate1)
} else {
Some(candidate2)
}
}
pub fn split_points(pts: &[Pt2D]) -> Result<(Vec<PolyLine>, Vec<Ring>)> {
let mut seen = HashSet::new();
let mut intersections = HashSet::new();
for pt in pts {
let pt = pt.to_hashable();
if seen.contains(&pt) {
intersections.insert(pt);
} else {
seen.insert(pt);
}
}
intersections.insert(pts[0].to_hashable());
intersections.insert(pts.last().unwrap().to_hashable());
let mut polylines = Vec::new();
let mut rings = Vec::new();
let mut current = Vec::new();
for pt in pts.iter().cloned() {
current.push(pt);
if intersections.contains(&pt.to_hashable()) && current.len() > 1 {
if current[0] == pt && current.len() >= 3 {
rings.push(Ring::new(current.drain(..).collect())?);
} else {
polylines.push(PolyLine::new(current.drain(..).collect())?);
}
current.push(pt);
}
}
Ok((polylines, rings))
}
pub fn contains_pt(&self, pt: Pt2D) -> bool {
PolyLine::unchecked_new(self.pts.clone())
.dist_along_of_point(pt)
.is_some()
}
pub fn to_geojson(&self, gps: Option<&GPSBounds>) -> geojson::Geometry {
let mut pts = Vec::new();
if let Some(ref gps) = gps {
for pt in gps.convert_back(&self.pts) {
pts.push(vec![pt.x(), pt.y()]);
}
} else {
for pt in &self.pts {
pts.push(vec![pt.x(), pt.y()]);
}
}
geojson::Geometry::new(geojson::Value::Polygon(vec![pts]))
}
pub fn translate(mut self, dx: f64, dy: f64) -> Ring {
for pt in &mut self.pts {
*pt = pt.offset(dx, dy);
}
self
}
}
impl fmt::Display for Ring {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "Ring::new(vec![")?;
for pt in &self.pts {
writeln!(f, " Pt2D::new({}, {}),", pt.x(), pt.y())?;
}
write!(f, "])")
}
}
impl From<Ring> for geo::LineString<f64> {
fn from(ring: Ring) -> Self {
let coords = ring
.pts
.into_iter()
.map(geo::Coordinate::from)
.collect::<Vec<_>>();
Self(coords)
}
}
impl From<geo::LineString<f64>> for Ring {
fn from(line_string: geo::LineString<f64>) -> Self {
let mut pts: Vec<Pt2D> = line_string.0.into_iter().map(Pt2D::from).collect();
pts.dedup();
Self::must_new(pts)
}
}