geometry-algorithm 0.0.8

Free-function algorithms (distance, length, area, within, intersects, …) ported from Boost.Geometry.
Documentation
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
//! `correct(&mut g)` — fix ring closure and orientation in place.
//!
//! Mirrors `boost::geometry::correct` from
//! `boost/geometry/algorithms/correct.hpp` and the closure-fix helper
//! at `algorithms/correct_closure.hpp`.
//!
//! Per-kind:
//!
//! * `Ring<P, CW, true>`   → push closing vertex if missing
//! * `Ring<P, CW, false>`  → pop closing vertex if duplicated
//! * exterior ring         → reverse so its *strategy-level* signed
//!   area (which already folds the declared `PointOrder`) is positive
//!   — i.e. the stored order matches the declaration, for CW- and
//!   CCW-declared rings alike
//! * `Polygon` outer       → as above; inners → opposite of outer
//! * `MultiPolygon`        → correct each member
//!
//! Empty and 1-point rings are left unchanged (silent no-op, matching
//! Boost). Cartesian-only: the orientation test uses the Cartesian
//! shoelace area.

use geometry_coords::CoordinateScalar;
use geometry_cs::CoordinateSystem;
use geometry_model::{
    Box as ModelBox, DynGeometry, DynGeometryCollection, Linestring, MultiLinestring, MultiPoint,
    MultiPolygon, Point as ModelPoint, Polygon, Ring, Segment,
};
use geometry_strategy::{AreaStrategy, ShoelaceArea};
use geometry_trait::{
    Closure, Linestring as LinestringTrait, Point as PointTrait, Ring as RingTrait,
};

/// Fix closure and orientation of `g` in place.
///
/// Mirrors `boost::geometry::correct(g)` from
/// `boost/geometry/algorithms/correct.hpp`.
pub fn correct<G: Correct>(g: &mut G) {
    g.correct();
}

/// Fix only ring closure, leaving orientation unchanged.
///
/// Mirrors `boost::geometry::correct_closure(g)` from
/// `boost/geometry/algorithms/correct_closure.hpp:211-224`. Closed rings
/// gain a copy of their first point when needed; open rings lose a
/// duplicated closing point. Polygons apply the same rule to their exterior
/// and interior rings, and multi-polygons apply it to every member.
#[inline]
pub fn correct_closure<G: CorrectClosure>(g: &mut G) {
    g.correct_closure();
}

/// Per-kind correction dispatch.
#[doc(hidden)]
pub trait Correct {
    fn correct(&mut self);
}

/// Per-kind closure-correction dispatch.
///
/// Mirrors the tag-specialized `dispatch::correct_closure` family from
/// `algorithms/correct_closure.hpp:102-160`.
#[doc(hidden)]
pub trait CorrectClosure {
    fn correct_closure(&mut self);
}

/// Add or drop the closing vertex so the stored point sequence matches
/// the ring's `CLOSED` const-generic.
fn fix_closure<P, const CW: bool, const CL: bool>(r: &mut Ring<P, CW, CL>)
where
    P: PointTrait + Copy,
{
    // Rings of two or fewer points are degenerate — closing one would
    // just append a spurious `[a, b, a]`. Boost leaves them untouched
    // (`algorithms/correct_closure.hpp:59`, `if (size <= 2) return;`).
    if r.0.len() <= 2 {
        return;
    }
    let first = r.0[0];
    let last = *r.0.last().unwrap();
    let should_be_closed = matches!(r.closure(), Closure::Closed);
    let already_closed = coords_equal(&first, &last);
    match (should_be_closed, already_closed) {
        (true, false) => r.0.push(first), // close it
        (false, true) => {
            r.0.pop(); // open it
        }
        _ => {}
    }
}

/// Coordinate-wise equality — `Point<T, D, Cs>` does not derive a
/// usable `PartialEq` (the derive would demand `Cs: PartialEq`), so we
/// compare per dimension via `get::<D>`.
fn coords_equal<P: PointTrait>(a: &P, b: &P) -> bool {
    geometry_trait::fold_dims(true, a, |acc, _p, d| {
        acc && match d {
            0 => a.get::<0>() == b.get::<0>(),
            1 => a.get::<1>() == b.get::<1>(),
            2 => a.get::<2>() == b.get::<2>(),
            3 => a.get::<3>() == b.get::<3>(),
            _ => unreachable!("fold_dims caps at MAX_DIM"),
        }
    })
}

/// Reverse `r` if its signed area sign disagrees with `want_positive`.
fn fix_orientation<P, const CW: bool, const CL: bool>(r: &mut Ring<P, CW, CL>, want_positive: bool)
where
    P: PointTrait,
    ShoelaceArea: AreaStrategy<Ring<P, CW, CL>, Out = P::Scalar>,
{
    let a = ShoelaceArea.area(&*r);
    let zero = <P::Scalar as CoordinateScalar>::ZERO;
    let is_positive = a > zero;
    let is_negative = a < zero;
    // Only reverse when the sign is decisively wrong; a zero-area
    // (degenerate) ring is left as-is.
    if (want_positive && is_negative) || (!want_positive && is_positive) {
        r.0.reverse();
    }
}

impl<P, const CW: bool, const CL: bool> Correct for Ring<P, CW, CL>
where
    P: PointTrait + Copy,
    P::Cs: CoordinateSystem,
    ShoelaceArea: AreaStrategy<Ring<P, CW, CL>, Out = P::Scalar>,
{
    fn correct(&mut self) {
        fix_closure(self);
        // `ShoelaceArea` already folds the declared `PointOrder` into
        // its sign: a ring stored in its declared direction has a
        // POSITIVE strategy-level area for CW-declared and
        // CCW-declared rings alike. So the target sign of a corrected
        // standalone ring is always positive — passing `CW` here would
        // double-apply the declaration flip and reverse correctly
        // wound CCW rings.
        fix_orientation(self, true);
    }
}

/// Mirrors the ring-tag closure arm at
/// `algorithms/correct_closure.hpp:131-134`.
impl<P, const CW: bool, const CL: bool> CorrectClosure for Ring<P, CW, CL>
where
    P: PointTrait + Copy,
{
    fn correct_closure(&mut self) {
        fix_closure(self);
    }
}

impl<P, const CW: bool, const CL: bool> Correct for Polygon<P, CW, CL>
where
    P: PointTrait + Copy,
    P::Cs: CoordinateSystem,
    ShoelaceArea: AreaStrategy<Ring<P, CW, CL>, Out = P::Scalar>,
{
    fn correct(&mut self) {
        fix_closure(&mut self.outer);
        // Exterior: stored order must match the declaration —
        // strategy-level area positive (see the Ring impl above).
        fix_orientation(&mut self.outer, true);
        for inner in &mut self.inners {
            fix_closure(inner);
            // Interior rings wind opposite the exterior, i.e. opposite
            // their own declared order — strategy-level area negative.
            // That is the state `ShoelacePolygonArea`'s plain ring-sum
            // relies on (holes arrive negatively signed).
            fix_orientation(inner, false);
        }
    }
}

/// Mirrors the polygon-tag closure arm at
/// `algorithms/correct_closure.hpp:136-139`.
impl<P, const CW: bool, const CL: bool> CorrectClosure for Polygon<P, CW, CL>
where
    P: PointTrait + Copy,
{
    fn correct_closure(&mut self) {
        fix_closure(&mut self.outer);
        for inner in &mut self.inners {
            fix_closure(inner);
        }
    }
}

impl<Pg: Correct + geometry_trait::Polygon> Correct for MultiPolygon<Pg> {
    fn correct(&mut self) {
        for p in &mut self.0 {
            p.correct();
        }
    }
}

/// Mirrors the multi-polygon closure arm at
/// `algorithms/correct_closure.hpp:154-160`.
impl<Pg> CorrectClosure for MultiPolygon<Pg>
where
    Pg: CorrectClosure + geometry_trait::Polygon,
{
    fn correct_closure(&mut self) {
        for polygon in &mut self.0 {
            polygon.correct_closure();
        }
    }
}

/// Mirrors the no-op point arm at `algorithms/correct_closure.hpp:110-113`.
impl<T, const D: usize, Cs> CorrectClosure for ModelPoint<T, D, Cs>
where
    T: CoordinateScalar,
    Cs: CoordinateSystem,
{
    fn correct_closure(&mut self) {}
}

/// Mirrors the no-op linestring arm at
/// `algorithms/correct_closure.hpp:115-118`.
impl<P: PointTrait> CorrectClosure for Linestring<P> {
    fn correct_closure(&mut self) {}
}

/// Mirrors the no-op segment arm at `algorithms/correct_closure.hpp:120-123`.
impl<P: PointTrait> CorrectClosure for Segment<P> {
    fn correct_closure(&mut self) {}
}

/// Mirrors the no-op box arm at `algorithms/correct_closure.hpp:126-129`.
impl<P: PointTrait> CorrectClosure for ModelBox<P> {
    fn correct_closure(&mut self) {}
}

/// Mirrors the no-op multi-point arm at
/// `algorithms/correct_closure.hpp:142-145`.
impl<P: PointTrait> CorrectClosure for MultiPoint<P> {
    fn correct_closure(&mut self) {}
}

/// Mirrors the no-op multi-linestring arm at
/// `algorithms/correct_closure.hpp:148-151`.
impl<L: LinestringTrait> CorrectClosure for MultiLinestring<L> {
    fn correct_closure(&mut self) {}
}

/// Mirrors Boost's dynamic-geometry visitor at
/// `algorithms/correct_closure.hpp:180-189`.
impl<T, Cs> CorrectClosure for DynGeometry<T, Cs>
where
    T: CoordinateScalar,
    Cs: CoordinateSystem + Copy,
{
    fn correct_closure(&mut self) {
        match self {
            DynGeometry::Point(_)
            | DynGeometry::LineString(_)
            | DynGeometry::MultiPoint(_)
            | DynGeometry::MultiLineString(_) => {}
            DynGeometry::Polygon(polygon) => polygon.correct_closure(),
            DynGeometry::MultiPolygon(multi_polygon) => multi_polygon.correct_closure(),
            DynGeometry::GeometryCollection(geometries) => {
                for geometry in geometries {
                    geometry.correct_closure();
                }
            }
        }
    }
}

/// Mirrors Boost's breadth-first geometry-collection visitor at
/// `algorithms/correct_closure.hpp:192-203`.
impl<T, Cs> CorrectClosure for DynGeometryCollection<T, Cs>
where
    T: CoordinateScalar,
    Cs: CoordinateSystem + Copy,
{
    fn correct_closure(&mut self) {
        for geometry in &mut self.0 {
            geometry.correct_closure();
        }
    }
}

#[cfg(test)]
mod tests {
    //! Reference behaviour from
    //! `boost/geometry/test/algorithms/correct.cpp`: a
    //! counter-clockwise-stored exterior of a clockwise-declared ring
    //! is reversed so its signed area becomes positive.

    #![allow(clippy::float_cmp, reason = "Areas are exact integer literals.")]

    use super::correct;
    use crate::area::ring_area;
    use geometry_cs::Cartesian;
    use geometry_model::{Point2D, Ring};

    type P = Point2D<f64, Cartesian>;

    #[test]
    fn ccw_exterior_of_cw_ring_is_reversed() {
        // A 2×2 square stored counter-clockwise. Declared CW (default),
        // so its signed area is negative until `correct` reverses it.
        let mut r: Ring<P> = Ring::from_vec(vec![
            P::new(0.0, 0.0),
            P::new(2.0, 0.0),
            P::new(2.0, 2.0),
            P::new(0.0, 2.0),
            P::new(0.0, 0.0),
        ]);
        assert!(ring_area(&r) < 0.0, "precondition: CCW ring is negative");
        correct(&mut r);
        assert_eq!(ring_area(&r), 4.0);
    }

    #[test]
    fn already_correct_ring_is_unchanged() {
        // Same square stored clockwise — already positive; correct is a
        // no-op on orientation.
        let mut r: Ring<P> = Ring::from_vec(vec![
            P::new(0.0, 0.0),
            P::new(0.0, 2.0),
            P::new(2.0, 2.0),
            P::new(2.0, 0.0),
            P::new(0.0, 0.0),
        ]);
        assert_eq!(ring_area(&r), 4.0);
        correct(&mut r);
        assert_eq!(ring_area(&r), 4.0);
    }

    #[test]
    fn two_point_ring_is_left_untouched() {
        // Regression: a degenerate 2-point ring must NOT be "closed" into
        // a spurious [a, b, a]. Boost leaves rings of size <= 2 alone
        // (correct_closure.hpp:59).
        use geometry_trait::Ring as _;
        let mut r: Ring<P> = Ring::from_vec(vec![P::new(0.0, 0.0), P::new(1.0, 1.0)]);
        correct(&mut r);
        assert_eq!(r.points().count(), 2, "2-point ring must stay 2 points");
    }

    /// An *open*-declared ring (`CLOSED = false`) that is stored with a
    /// redundant closing vertex has it dropped by `fix_closure` — the
    /// `(should_be_closed=false, already_closed=true)` arm.
    #[test]
    fn open_declared_ring_drops_redundant_closing_vertex() {
        use geometry_trait::Ring as _;
        // CW (true), OPEN (false), stored closed (first == last).
        let mut r: Ring<P, true, false> = Ring::from_vec(vec![
            P::new(0.0, 0.0),
            P::new(0.0, 2.0),
            P::new(2.0, 2.0),
            P::new(2.0, 0.0),
            P::new(0.0, 0.0),
        ]);
        correct(&mut r);
        // The closing vertex is removed: 5 stored points → 4.
        assert_eq!(r.points().count(), 4);
        // Area is unchanged by the closure fix (still the 2×2 square).
        assert_eq!(ring_area(&r), 4.0);
    }

    /// `correct` on a `MultiPolygon` corrects each member polygon: a
    /// CCW-stored member is re-wound to a positive exterior area.
    #[test]
    fn multipolygon_corrects_each_member() {
        use geometry_model::{MultiPolygon, Polygon};
        let ccw_square = || {
            Polygon::<P>::new(Ring::from_vec(vec![
                P::new(0.0, 0.0),
                P::new(2.0, 0.0),
                P::new(2.0, 2.0),
                P::new(0.0, 2.0),
                P::new(0.0, 0.0),
            ]))
        };
        let mut mpg: MultiPolygon<Polygon<P>> = MultiPolygon(vec![ccw_square(), ccw_square()]);
        // Precondition: both exteriors are negative (CCW, CW-declared).
        assert!(ring_area(&mpg.0[0].outer) < 0.0);
        correct(&mut mpg);
        assert_eq!(ring_area(&mpg.0[0].outer), 4.0);
        assert_eq!(ring_area(&mpg.0[1].outer), 4.0);
    }

    /// A 3D ring whose stored closing vertex matches the first in all
    /// three ordinates is recognised as already-closed — exercising the
    /// `coords_equal` `D == 2` arm.
    #[test]
    fn coords_equal_compares_the_third_ordinate() {
        use geometry_model::Point3D;
        use geometry_trait::Ring as _;
        type P3 = Point3D<f64, Cartesian>;
        // Open-declared 3D ring stored closed in x, y AND z. `fix_closure`
        // only drops the closer if `coords_equal` returns true across all
        // three ordinates.
        let mut r: Ring<P3, true, false> = Ring::from_vec(vec![
            P3::new(0.0, 0.0, 5.0),
            P3::new(1.0, 0.0, 5.0),
            P3::new(1.0, 1.0, 5.0),
            P3::new(0.0, 0.0, 5.0),
        ]);
        // Note: this ring's orientation correction relies on ShoelaceArea,
        // which is defined for these Cartesian points; we only assert the
        // closure fix here.
        let before = r.points().count();
        super::fix_closure(&mut r);
        assert_eq!(before, 4);
        assert_eq!(r.points().count(), 3, "closing vertex dropped");

        // And a ring whose z differs at the closer is NOT already closed.
        let mut open: Ring<P3, true, false> = Ring::from_vec(vec![
            P3::new(0.0, 0.0, 5.0),
            P3::new(1.0, 0.0, 5.0),
            P3::new(1.0, 1.0, 5.0),
            P3::new(0.0, 0.0, 9.0), // same x,y — different z
        ]);
        super::fix_closure(&mut open);
        assert_eq!(open.points().count(), 4, "z differs → not closed → kept");
    }

    #[test]
    fn ccw_ring_correctly_wound_is_a_noop() {
        // Regression: `fix_orientation(self, CW)` used to reverse a
        // CORRECTLY wound CCW-declared ring (+2 → −2), because
        // `ShoelaceArea` already folds the declared order into its
        // sign. Fixture mirrors geometry-strategy's
        // `ccw_declared_ccw_traversed_diamond_is_2`.
        let mut r: Ring<P, false> = Ring::from_vec(vec![
            P::new(1.0, 0.0),
            P::new(0.0, 1.0),
            P::new(-1.0, 0.0),
            P::new(0.0, -1.0),
            P::new(1.0, 0.0),
        ]);
        assert_eq!(ring_area(&r), 2.0, "precondition: correctly wound");
        correct(&mut r);
        assert_eq!(ring_area(&r), 2.0, "correct() must be a no-op");
    }

    #[test]
    fn ccw_ring_wrongly_wound_is_reversed() {
        // The same diamond stored clockwise under a CCW declaration:
        // strategy area −2 → correct() reverses → +2.
        let mut r: Ring<P, false> = Ring::from_vec(vec![
            P::new(1.0, 0.0),
            P::new(0.0, -1.0),
            P::new(-1.0, 0.0),
            P::new(0.0, 1.0),
            P::new(1.0, 0.0),
        ]);
        assert_eq!(ring_area(&r), -2.0, "precondition: wrongly wound");
        correct(&mut r);
        assert_eq!(ring_area(&r), 2.0);
    }

    #[test]
    fn ccw_polygon_with_hole_correctly_wound_is_a_noop() {
        // Outer 4x4 stored CCW (matches declaration, ring_area +16),
        // hole 1x1 stored CW (opposite, ring_area −1). correct() must
        // change nothing: this is exactly the state
        // ShoelacePolygonArea's ring-sum (+15) relies on.
        use geometry_model::Polygon;
        let outer: Ring<P, false> = Ring::from_vec(vec![
            P::new(0.0, 0.0),
            P::new(4.0, 0.0),
            P::new(4.0, 4.0),
            P::new(0.0, 4.0),
            P::new(0.0, 0.0),
        ]);
        let hole: Ring<P, false> = Ring::from_vec(vec![
            P::new(1.0, 1.0),
            P::new(1.0, 2.0),
            P::new(2.0, 2.0),
            P::new(2.0, 1.0),
            P::new(1.0, 1.0),
        ]);
        let mut pg: Polygon<P, false> = Polygon::new(outer);
        pg.inners.push(hole);
        assert_eq!(ring_area(&pg.outer), 16.0, "precondition: outer CCW-stored");
        assert_eq!(
            ring_area(&pg.inners[0]),
            -1.0,
            "precondition: hole CW-stored"
        );
        correct(&mut pg);
        assert_eq!(ring_area(&pg.outer), 16.0, "outer must be untouched");
        assert_eq!(ring_area(&pg.inners[0]), -1.0, "hole must be untouched");
    }

    #[test]
    fn ccw_polygon_wrongly_wound_is_fixed() {
        // Outer stored CW (wrong for a CCW declaration), hole stored
        // CCW (wrong for a hole): correct() reverses both.
        use geometry_model::Polygon;
        let outer: Ring<P, false> = Ring::from_vec(vec![
            P::new(0.0, 0.0),
            P::new(0.0, 4.0),
            P::new(4.0, 4.0),
            P::new(4.0, 0.0),
            P::new(0.0, 0.0),
        ]);
        let hole: Ring<P, false> = Ring::from_vec(vec![
            P::new(1.0, 1.0),
            P::new(2.0, 1.0),
            P::new(2.0, 2.0),
            P::new(1.0, 2.0),
            P::new(1.0, 1.0),
        ]);
        let mut pg: Polygon<P, false> = Polygon::new(outer);
        pg.inners.push(hole);
        assert_eq!(ring_area(&pg.outer), -16.0, "precondition: outer wrong");
        assert_eq!(ring_area(&pg.inners[0]), 1.0, "precondition: hole wrong");
        correct(&mut pg);
        assert_eq!(ring_area(&pg.outer), 16.0);
        assert_eq!(ring_area(&pg.inners[0]), -1.0);
    }
}