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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use crate::{GeneralPolygon, Triangle, Triangle2d};
use itertools::Itertools;
use nalgebra::{clamp, Matrix2, Point2, RealField, Scalar, Unit, Vector2};
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ConcavePolygonError;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConvexPolygon<T>
where
T: Scalar,
{
vertices: Vec<Point2<T>>,
}
#[derive(Debug, Clone)]
pub struct HalfPlane<T>
where
T: Scalar,
{
point: Point2<T>,
normal: Unit<Vector2<T>>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct LineSegment2d<T>
where
T: Scalar,
{
from: Point2<T>,
to: Point2<T>,
}
impl<T> LineSegment2d<T>
where
T: Scalar,
{
pub fn new(from: Point2<T>, to: Point2<T>) -> Self {
Self { from, to }
}
pub fn from(&self) -> &Point2<T> {
&self.from
}
pub fn to(&self) -> &Point2<T> {
&self.to
}
pub fn reverse(&self) -> Self {
LineSegment2d {
from: self.to.clone(),
to: self.from.clone(),
}
}
}
impl<T> LineSegment2d<T>
where
T: RealField,
{
pub fn to_line(&self) -> Line2d<T> {
let dir = &self.to - &self.from;
Line2d::from_point_and_dir(self.from.clone(), dir)
}
pub fn tangent_dir(&self) -> Vector2<T> {
self.to().coords - self.from().coords
}
pub fn normal_dir(&self) -> Vector2<T> {
let tangent = self.tangent_dir();
Vector2::new(tangent.y, -tangent.x)
}
pub fn length(&self) -> T {
self.tangent_dir().norm()
}
pub fn midpoint(&self) -> Point2<T> {
Point2::from((self.from.coords + self.to.coords) / (T::one() + T::one()))
}
pub fn intersect_line_parametric(&self, line: &Line2d<T>) -> Option<T> {
self.to_line()
.intersect_line_parametric(line)
.map(|(t1, _)| t1)
}
pub fn closest_point_parametric(&self, point: &Point2<T>) -> T {
let t = self.to_line().project_point_parametric(point);
clamp(t, T::zero(), T::one())
}
pub fn closest_point(&self, point: &Point2<T>) -> Point2<T> {
let t = self.closest_point_parametric(point);
self.point_from_parameter(t)
}
pub fn point_from_parameter(&self, t: T) -> Point2<T> {
Point2::from(self.from().coords + (self.to() - self.from()) * t)
}
pub fn intersect_segment_parametric(&self, other: &LineSegment2d<T>) -> Option<T> {
let d1 = &self.to - &self.from;
let d2 = &other.to - &other.from;
let line1 = Line2d::from_point_and_dir(self.from.clone(), d1);
let line2 = Line2d::from_point_and_dir(other.from.clone(), d2);
line1
.intersect_line_parametric(&line2)
.and_then(|(t1, t2)| {
if t2 < T::zero() || t2 > T::one() {
None
} else if t1 < T::zero() || t1 > T::one() {
None
} else {
Some(t1)
}
})
}
pub fn intersect_polygon(&self, other: &ConvexPolygon<T>) -> Option<LineSegment2d<T>> {
let mut min = None;
let mut max = None;
let contains_start = other.contains_point(self.from());
let contains_end = other.contains_point(self.to());
let contained_in_poly = contains_start && contains_end;
if contains_start {
min = Some(T::zero());
}
if contains_end {
max = Some(T::one());
}
if !contained_in_poly {
for edge in other.edges() {
let edge_segment = LineSegment2d::new(*edge.0, *edge.1);
if let Some(t) = self.intersect_segment_parametric(&edge_segment) {
if t < *min.get_or_insert(t) {
min = Some(t);
}
if t > *max.get_or_insert(t) {
max = Some(t)
}
}
}
}
assert!(min.is_none() == max.is_none());
min.and_then(|min| max.and_then(|max| Some((min, max))))
.map(|(t_min, t_max)| {
let a = self.from();
let b = self.to();
let d = b - a;
debug_assert!(t_min <= t_max);
LineSegment2d::new(a + d * t_min, a + d * t_max)
})
}
}
impl<T> From<LineSegment2d<T>> for ConvexPolygon<T>
where
T: Scalar,
{
fn from(segment: LineSegment2d<T>) -> Self {
ConvexPolygon::from_vertices(vec![segment.from, segment.to])
}
}
#[derive(Debug, Clone)]
pub struct Line2d<T>
where
T: Scalar,
{
point: Point2<T>,
dir: Vector2<T>,
}
impl<T> Line2d<T>
where
T: Scalar,
{
pub fn from_point_and_dir(point: Point2<T>, dir: Vector2<T>) -> Self {
Self { point, dir }
}
}
impl<T> Line2d<T>
where
T: RealField,
{
pub fn project_point_parametric(&self, point: &Point2<T>) -> T {
let d2 = self.dir.magnitude_squared();
(point - &self.point).dot(&self.dir) / d2
}
pub fn project_point(&self, point: &Point2<T>) -> Point2<T> {
let t = self.project_point_parametric(point);
self.point_from_parameter(t)
}
pub fn point_from_parameter(&self, t: T) -> Point2<T> {
&self.point + &self.dir * t
}
pub fn intersect(&self, other: &Line2d<T>) -> Option<Point2<T>> {
self.intersect_line_parametric(other)
.map(|(t1, _)| self.point_from_parameter(t1))
}
pub fn intersect_line_parametric(&self, other: &Line2d<T>) -> Option<(T, T)> {
let rhs = &other.point - &self.point;
let matrix = Matrix2::from_columns(&[self.dir, -other.dir]);
matrix
.try_inverse()
.map(|inv| inv * rhs)
.map(|t| (t.x, t.y))
}
}
impl<T> HalfPlane<T>
where
T: RealField,
{
pub fn from_point_and_normal(point: Point2<T>, normal: Unit<Vector2<T>>) -> Self {
Self { point, normal }
}
}
impl<T> HalfPlane<T>
where
T: RealField,
{
pub fn contains_point(&self, point: &Point2<T>) -> bool {
self.surface_distance_to_point(point) >= T::zero()
}
pub fn surface_distance_to_point(&self, point: &Point2<T>) -> T {
let d = point - &self.point;
self.normal.dot(&d)
}
pub fn point(&self) -> &Point2<T> {
&self.point
}
pub fn normal(&self) -> &Vector2<T> {
&self.normal
}
pub fn surface(&self) -> Line2d<T> {
let tangent = Vector2::new(self.normal.y, -self.normal.x);
Line2d::from_point_and_dir(self.point.clone(), tangent)
}
}
impl<T> ConvexPolygon<T>
where
T: Scalar,
{
pub fn from_vertices(vertices: Vec<Point2<T>>) -> ConvexPolygon<T> {
Self { vertices }
}
pub fn vertices(&self) -> &[Point2<T>] {
&self.vertices
}
pub fn num_edges(&self) -> usize {
self.vertices().len()
}
pub fn edges(&self) -> impl Iterator<Item = (&Point2<T>, &Point2<T>)> {
let num_vertices = self.vertices().len();
self.vertices()
.iter()
.cycle()
.take(num_vertices + 1)
.tuple_windows()
}
pub fn is_empty(&self) -> bool {
self.vertices.is_empty()
}
pub fn is_point(&self) -> bool {
self.vertices.len() == 1
}
pub fn is_line_segment(&self) -> bool {
self.vertices.len() == 2
}
}
impl<T> ConvexPolygon<T>
where
T: RealField,
{
pub fn half_planes<'a>(&'a self) -> impl Iterator<Item = HalfPlane<T>> + 'a {
self.edges().filter_map(|(v1, v2)| {
if v1 != v2 {
let edge_dir = v2 - v1;
let negative_edge_normal = Vector2::new(-edge_dir.y, edge_dir.x);
let normalized_negative_edge_normal = Unit::try_new(negative_edge_normal, T::zero())
.expect("v1 != v2, so vector can be safely normalized");
Some(HalfPlane::from_point_and_normal(*v1, normalized_negative_edge_normal))
} else {
None
}
})
}
pub fn contains_point(&self, point: &Point2<T>) -> bool {
if self.is_point() {
self.vertices.first().unwrap() == point
} else if self.is_line_segment() {
unimplemented!()
} else {
self.half_planes()
.all(|half_plane| half_plane.contains_point(point))
}
}
pub fn intersect_halfplane(&self, half_plane: &HalfPlane<T>) -> ConvexPolygon<T> {
let mut new_vertices = Vec::new();
if self.vertices.len() == 1 {
let first = self.vertices().first().unwrap();
if half_plane.contains_point(first) {
new_vertices.push(first.clone());
}
} else {
for (v1, v2) in self.edges() {
let v1_contained = half_plane.contains_point(v1);
let v2_contained = half_plane.contains_point(v2);
if v1_contained {
new_vertices.push(v1.clone());
}
if (v1_contained && !v2_contained) || (!v1_contained && v2_contained) {
let dir = (v2 - v1).normalize();
let intersection_point = half_plane
.surface()
.intersect(&Line2d::from_point_and_dir(v1.clone(), dir))
.expect(
"We already know that the line must intersect the edge, \
so this should work unless we have some ugly numerical \
artifacts.",
);
new_vertices.push(intersection_point);
}
}
}
ConvexPolygon::from_vertices(new_vertices)
}
pub fn intersect_polygon(&self, other: &ConvexPolygon<T>) -> Self {
if self.is_point() || other.is_point() {
unimplemented!()
} else if self.is_line_segment() {
let segment = LineSegment2d::new(self.vertices[0], self.vertices[1]);
segment
.intersect_polygon(other)
.map(|segment| ConvexPolygon::from_vertices(vec![*segment.from(), *segment.to()]))
.unwrap_or_else(|| ConvexPolygon::from_vertices(Vec::new()))
} else if other.is_line_segment() {
other.intersect_polygon(self)
} else {
let mut result = self.clone();
for half_plane in other.half_planes() {
result = result.intersect_halfplane(&half_plane);
}
result
}
}
pub fn triangulate<'a>(&'a self) -> impl Iterator<Item = Triangle2d<T>> + 'a {
self.edges()
.take(self.num_edges().saturating_sub(1))
.skip(1)
.map(move |(a, b)| Triangle([*self.vertices.first().unwrap(), *a, *b]))
}
pub fn triangulate_into_vec(&self) -> Vec<Triangle2d<T>> {
self.triangulate().collect()
}
}
impl<T> From<ConvexPolygon<T>> for GeneralPolygon<T>
where
T: Scalar,
{
fn from(poly: ConvexPolygon<T>) -> Self {
GeneralPolygon::from_vertices(poly.vertices)
}
}