aboutsummaryrefslogtreecommitdiff
path: root/src/math/polygon/mod.rs
blob: f84211da7da8e30a3a8f4d731d9738ad64e67c8f (plain) (blame)
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
//! Contains functions and structures to help with operations on polygons.

pub mod polygon_graph;
pub mod triangulate;

pub use polygon_graph::*;
pub use triangulate::*;

use super::{LineSegment, Surface, TripletOrientation, Vec2};
use crate::math;
use nalgebra::{ClosedDiv, ClosedMul, ClosedSub, RealField, Scalar};
use num_traits::Zero;
use serde::{Deserialize, Serialize};
use std::ops::Neg;

#[derive(Debug, Deserialize, Serialize)]
// TODO: Support polygons with holes
pub struct Polygon<T: Scalar + Copy> {
    corners: Vec<Vec2<T>>,
}

impl<T: Scalar + Copy> Polygon<T> {
    /// Create a new polygon from the provided corners. If the corners are right-turning, they will
    /// be reversed to be left-turning.
    ///
    /// # Panics
    /// If one tries to create a polygon with less than three corners, it will fail. Zero area
    /// polygons however are allowed at the moment.
    pub fn new(corners: Vec<Vec2<T>>) -> Self
    where
        T: RealField,
    {
        if corners.len() < 3 {
            panic!("Cannot create polygon with less than three corners.");
        }

        let corners = if combined_angle(&corners) > T::zero() {
            corners
        } else {
            corners.into_iter().rev().collect()
        };

        Self { corners }
    }

    /// Add a vertex as a corner between the two provided neighbours. The direction of the
    /// neighbours is not relevant. The edge between the two will be replaced with two edges to the
    /// new corner from each of the neighbours respectively.
    /// If there already is a point `corner` in the polygon, this function will fail and return
    /// `false`. It will do nothing and return `false` if the provided neighbours are not actually
    /// neighbours in the polygon already.
    /// Otherwise it will perform the addition and return `true`.
    pub fn add_corner(
        &mut self,
        corner: Vec2<T>,
        neighbour1: &Vec2<T>,
        neighbour2: &Vec2<T>,
    ) -> bool {
        // Check that the corners do not contain the corner vector already.
        if self.corners.iter().find(|&c| *c == corner).is_some() {
            return false;
        }

        for i in 0..self.corners.len() {
            let next = (i + 1) % self.corners.len();

            if self.corners[i] == *neighbour1 && self.corners[next] == *neighbour2 {
                self.corners.insert(next, corner);
                return true;
            }
            if self.corners[i] == *neighbour2 && self.corners[next] == *neighbour1 {
                self.corners.insert(next, corner);
                return true;
            }
        }

        // No matching neighbour pair can be found.
        false
    }

    /// Get the corners of this polygon in left-turning direction.
    pub fn corners(&self) -> &Vec<Vec2<T>> {
        &self.corners
    }

    /// Get the corners mutable. Be careful, since if you constructed this polygon from a
    /// right-turning line-strip, these are not the same as you constructed the polygon with, since
    /// all polygons' corners are normalised to be left-turning.
    pub fn corners_mut(&mut self) -> &mut Vec<Vec2<T>> {
        &mut self.corners
    }

    /// Join this polygon with another, ensuring the area of the two stays the same, but the
    /// overlap is not doubled, but instead joined into one.
    /// Returns the Polygons themselves, if there is no overlap
    pub fn unite(self, other: Polygon<T>) -> Vec<Polygon<T>>
    where
        T: RealField,
    {
        let mut graph = PolygonGraph::from_polygon(&self);
        graph.add_all(&other);

        // TODO: Make bounding box support multiple polygons
        vec![graph.bounding_polygon()]
    }
}

impl<
        T: Scalar
            + Copy
            + ClosedSub
            + ClosedMul
            + ClosedDiv
            + Neg<Output = T>
            + PartialOrd
            + RealField
            + Zero,
    > Surface<T> for Polygon<T>
{
    fn contains_point(&self, p: &Vec2<T>) -> bool {
        let n = self.corners.len();

        let a = self.corners[n - 1];
        let mut b = self.corners[n - 2];
        let mut ax;
        let mut ay = a.y - p.y;
        let mut bx = b.x - p.x;
        let mut by = b.y - p.y;

        let mut lup = by > ay;
        for i in 0..n {
            // ax = bx;
            ay = by;
            b = self.corners[i];
            bx = b.x - p.x;
            by = b.y - p.y;

            if ay == by {
                continue;
            }
            lup = by > ay;
        }

        let mut depth = 0;
        for i in 0..n {
            ax = bx;
            ay = by;
            let b = &self.corners[i];
            bx = b.x - p.x;
            by = b.y - p.y;

            if ay < T::zero() && by < T::zero() {
                // both "up" or both "down"
                continue;
            }
            if ay > T::zero() && by > T::zero() {
                // both "up" or both "down"
                continue;
            }
            if ax < T::zero() && bx < T::zero() {
                // both points on the left
                continue;
            }

            if ay == by && (if ax < bx { ax } else { bx }) <= T::zero() {
                return true;
            }
            if ay == by {
                continue;
            }

            let lx = ax + (((bx - ax) * -ay) / (by - ay));
            if lx == T::zero() {
                // point on edge
                return true;
            }
            if lx > T::zero() {
                depth += 1;
            }
            if ay == T::zero() && lup && by > ay {
                // hit vertex, both up
                depth -= 1;
            }
            if ay == T::zero() && !lup && by < ay {
                // hit vertex, both down
                depth -= 1;
            }

            lup = by > ay;
        }

        (depth & 1) == 1
    }

    fn contains_line_segment(&self, line_segment: &LineSegment<T>) -> bool {
        /* In case at least one of the points is not contained by the polygon, the line cannot lie
         * inside of the polygon in its entirety.
         */
        if !self.contains_point(&line_segment.start) || !self.contains_point(&line_segment.end) {
            return false;
        }

        /* Both end-points are inside the polygon. */

        /* In case the an endpoint of the line segment is equal to a corner of the polygon, it's
         * not enough to merely check one edge, since if the corner is reflex, the segment may
         * still be inside, eventhough its similar to the outwards pointing normal of one edge, but
         * may be to the inside of the other edge.
         */
        let mut start_looks_inside = false;
        let mut end_looks_inside = false;
        /* Helper function that checks if a point p, when starting from the given corner c is in a
         * direction so that considering both edges that are connected to c, the point is in the
         * direction of the inside of the polygon.
         */
        let corner_vec_pointing_inside = |p: Vec2<T>, c: usize| {
            let prev = (c + self.corners.len() - 1) % self.corners.len();
            let next = (c + 1) % self.corners.len();

            let edge_angle =
                math::triplet_angle(self.corners[prev], self.corners[c], self.corners[next]);
            let vec_angle = math::triplet_angle(self.corners[prev], self.corners[c], p);

            vec_angle == T::zero() || vec_angle >= edge_angle
        };

        for c in 0..self.corners.len() {
            if line_segment.start == self.corners[c] {
                start_looks_inside = corner_vec_pointing_inside(line_segment.end, c);
                if !start_looks_inside {
                    return false;
                }
            }
            if line_segment.end == self.corners[c] {
                end_looks_inside = corner_vec_pointing_inside(line_segment.start, c);
                if !end_looks_inside {
                    return false;
                }
            }
        }

        if start_looks_inside && end_looks_inside {
            return true;
        }

        /* Check the intersections of the line segment with all polygon edges and see if it is
         * piercing through any of them.
         */
        for c in 0..self.corners.len() {
            let next = (c + 1) % self.corners.len();

            let current_edge = LineSegment::new(self.corners[c], self.corners[next]);

            if LineSegment::intersect(&line_segment, &current_edge) {
                let orientation_start = math::triplet_orientation(
                    current_edge.start,
                    current_edge.end,
                    line_segment.start,
                );
                let orientation_end = math::triplet_orientation(
                    current_edge.start,
                    current_edge.end,
                    line_segment.end,
                );
                match (orientation_start, orientation_end) {
                    /* If at least one of the points is on the edge, make sure, the line points
                     * inside of the polygon, not to the outside.
                     */
                    (TripletOrientation::Collinear, o) => {
                        if !start_looks_inside && o == TripletOrientation::Clockwise {
                            return false;
                        }
                    }
                    (o, TripletOrientation::Collinear) => {
                        if !end_looks_inside && o == TripletOrientation::Clockwise {
                            return false;
                        }
                    }
                    /* Start and endpoint are on different sides of the edge, therefore the line
                     * must be partially outside.
                     */
                    _ => return false,
                }
            }
        }

        true
    }
}

/* Helper function to calculate the combined angle of a set of points when connecting them one
 * after another until finally connecting the last point to the first point in radians. Negative,
 * when the points in sum are right-turning, positive, when they are left-turning.
 */
fn combined_angle<T: Scalar + Copy + RealField>(points: &Vec<Vec2<T>>) -> T {
    let mut combined_angle = T::zero();
    for i in 0..points.len() {
        let prev = (i + points.len() - 1) % points.len();
        let next = (i + 1) % points.len();

        let angle = math::triplet_angle(points[prev], points[i], points[next]);
        if angle == T::zero() || angle == T::two_pi() {
            continue;
        }

        // Add the change in direction.
        combined_angle += angle - T::pi();
    }

    println!("Calculated combined angle: {} Pi", combined_angle / T::pi());

    combined_angle
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn polygon_contains() {
        let polygon = Polygon::new(vec![
            Vec2::new(0., 0.),
            Vec2::new(-1., 1.),
            Vec2::new(0., 2.),
            Vec2::new(1., 3.),
            Vec2::new(3., 1.5),
            Vec2::new(2., 0.),
            Vec2::new(1., 1.),
        ]);

        assert!(!polygon.contains_point(&Vec2::new(1., -2.)));
        assert!(!polygon.contains_point(&Vec2::new(-1., 0.5)));
        assert!(polygon.contains_point(&Vec2::new(0., 0.5)));
        assert!(polygon.contains_point(&Vec2::new(0.5, 1.)));
        assert!(polygon.contains_point(&Vec2::new(0.5, 1.5)));
        assert!(!polygon.contains_point(&Vec2::new(-2., 1.9)));
        assert!(!polygon.contains_point(&Vec2::new(0., 3.)));
        assert!(polygon.contains_point(&Vec2::new(1., 3.)));
    }

    #[test]
    fn contains_line_segment() {
        let polygon = Polygon::new(vec![
            Vec2::new(0., 0.),
            Vec2::new(0., 4.5),
            Vec2::new(6.5, 4.5),
            Vec2::new(5.5, 0.),
            Vec2::new(5.5, 3.),
            Vec2::new(1.5, 3.),
            Vec2::new(1.5, 1.),
            Vec2::new(2., 0.5),
            Vec2::new(4., 2.),
            Vec2::new(4., 0.),
        ]);

        /* NOTE: From now on, inside means inside the polygon, but might be on an edge or on a
         * corner point, really inside means inside and not on an edge.
         */

        // Start point really inside, end point really inside. Line not completely inside.
        assert!(!polygon
            .contains_line_segment(&LineSegment::new(Vec2::new(2.5, 0.5), Vec2::new(0.5, 2.5))));

        // Start point on edge, end point on corner, line completely outside.
        assert!(!polygon
            .contains_line_segment(&LineSegment::new(Vec2::new(1.5, 2.), Vec2::new(4., 2.))));

        // Start point on edge, end point on edge, line inside.
        assert!(polygon
            .contains_line_segment(&LineSegment::new(Vec2::new(3.5, 3.), Vec2::new(3.5, 4.5))));

        // Start point on corner, end point on corner, line inside.
        assert!(polygon
            .contains_line_segment(&LineSegment::new(Vec2::new(5.5, 3.), Vec2::new(6.5, 4.5))));

        // Start point really inside, end point on edge. Line not inside.
        assert!(!polygon
            .contains_line_segment(&LineSegment::new(Vec2::new(3.5, 0.5), Vec2::new(5.5, 0.5))));

        // Start point and endpoint outside. Line completely outside.
        assert!(!polygon
            .contains_line_segment(&LineSegment::new(Vec2::new(7.0, 0.), Vec2::new(7.5, 1.))));

        // Start point on vertex, pointing in same dir as one of the adjacent edge normals,
        // completely inside.
        assert!(
            polygon.contains_line_segment(&LineSegment::new(Vec2::new(2., 0.5), Vec2::new(4., 0.)))
        );

        // Start and end point on vertex, not pointing in the dir of adjacent edge normals,
        // not completely inside.
        assert!(
            !polygon.contains_line_segment(&LineSegment::new(Vec2::new(4., 2.), Vec2::new(0., 0.)))
        );
    }

    #[test]
    fn polygon_union() {
        let first = Polygon::new(vec![
            Vec2::new(-2., 1.),
            Vec2::new(-0.5, 2.5),
            Vec2::new(2., 2.),
            Vec2::new(0.5, 1.5),
            Vec2::new(1., 0.),
            Vec2::new(-0.5, 1.),
        ]);

        let second = Polygon::new(vec![
            Vec2::new(0., 0.),
            Vec2::new(-2., 2.),
            Vec2::new(3., 2.),
            Vec2::new(1.5, 0.),
        ]);

        let union = first.unite(second);
        assert_eq!(union.len(), 1);
        let union = &union[0];

        println!("Union of the two polygons: {:?}", union);

        assert_eq!(union.corners.len(), 11);
        assert!(union
            .corners
            .iter()
            .find(|&p| p.x == 0. && p.y == 0.)
            .is_some());
    }
}