rosewood 0.6.2

A file-based RTree for geospatial data
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
// geometry.rs
//
// Copyright (c) 2021-2026  Douglas P Lau
//
//! Data types for GIS
use pointy::{BBox, Bounded, Bounds, Float, Pt, Seg};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;

/// GIS geometry which can be stored in an RTree
pub trait Gis<F>
where
    F: Float,
{
    /// Data associated with geometry
    type Data;

    /// Get bounding box
    fn bbox(&self) -> BBox<F>;

    /// Get associated data
    fn data(&self) -> &Self::Data;
}

/// Point geometry
///
/// This geometry is one or more GIS points, along with associated data.
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Points<F, D>
where
    F: Float,
{
    /// Points in geometry
    pts: Vec<Pt<F>>,

    /// Associated data
    data: D,
}

/// Line string
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Linestring<F>
where
    F: Float,
{
    /// Points in line string
    pts: Vec<Pt<F>>,
}

/// Segment iterator for Linestring
struct SegIter<'a, F>
where
    F: Float,
{
    /// Point iterator
    iter: std::slice::Iter<'a, Pt<F>>,

    /// Previous point
    ppt: Option<Pt<F>>,
}

impl<F> Iterator for SegIter<'_, F>
where
    F: Float,
{
    type Item = Seg<F>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.ppt.is_none() {
            self.ppt = Some(*self.iter.next()?);
        }
        let ppt = self.ppt?;
        let pt = self.iter.next();
        self.ppt = pt.copied();
        pt.map(|p| Seg::new(ppt, p))
    }
}

/// Line string geometry
///
/// This geometry is one or more GIS line strings, along with associated data.
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Linestrings<F, D>
where
    F: Float,
{
    /// Line strings in geometry
    lines: Vec<Linestring<F>>,

    /// Associated data
    data: D,
}

/// Polygon
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Polygon<F>
where
    F: Float,
{
    /// Points in polygon
    pts: Vec<Pt<F>>,
}

/// Polygon geometry
///
/// This geometry is one or more GIS polygons, along with associated data.
/// A polygon is a `Vec` of closed rings.  The winding order determines whether
/// a ring is "outer" or "inner".
#[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
pub struct Polygons<F, D>
where
    F: Float,
{
    /// Polygons in geometry
    rings: Vec<Polygon<F>>,

    /// Associated data
    data: D,
}

/// Enum of defined geometries
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub enum Geom<F, D>
where
    F: Float,
{
    /// Point geometry
    Point(Points<F, D>),

    /// Linestring geometry
    Linestring(Linestrings<F, D>),

    /// Polygon geometry
    Polygon(Polygons<F, D>),
}

impl<F, D> Gis<F> for Points<F, D>
where
    F: Float,
{
    type Data = D;

    fn bbox(&self) -> BBox<F> {
        BBox::new(&self.pts)
    }

    fn data(&self) -> &Self::Data {
        &self.data
    }
}

impl<F, D> Bounded<F> for &Points<F, D>
where
    F: Float,
{
    fn bounded_by(self, bbox: BBox<F>) -> bool {
        self.iter().any(|pt| pt.bounded_by(bbox))
    }
}

impl<F, D> Points<F, D>
where
    F: Float,
{
    /// Create new point geometry
    pub fn new(data: D) -> Self {
        let pts = Vec::new();
        Self { pts, data }
    }

    /// Add a point
    pub fn push<P>(&mut self, pt: P)
    where
        P: Into<Pt<F>>,
    {
        self.pts.push(pt.into());
    }

    /// Get point iterator
    pub fn iter(&self) -> impl Iterator<Item = &Pt<F>> {
        self.pts.iter()
    }
}

impl<F> Bounded<F> for &Linestring<F>
where
    F: Float,
{
    fn bounded_by(self, bbox: BBox<F>) -> bool {
        self.segments().any(|seg| seg.bounded_by(bbox))
    }
}

impl<F> Linestring<F>
where
    F: Float,
{
    /// Create a new line string
    fn new<I, P>(pts: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<Pt<F>>,
    {
        let pts = pts.into_iter().map(|pt| pt.into()).collect();
        Linestring { pts }
    }

    /// Get point iterator
    pub fn iter(&self) -> impl Iterator<Item = &Pt<F>> {
        self.pts.iter()
    }

    /// Get line segment iterator
    pub fn segments(&self) -> impl Iterator<Item = Seg<F>> + '_ {
        let iter = self.pts.iter();
        SegIter { iter, ppt: None }
    }
}

impl<F, D> Gis<F> for Linestrings<F, D>
where
    F: Float,
{
    type Data = D;

    fn bbox(&self) -> BBox<F> {
        let mut bbox = BBox::default();
        for line in self.lines.iter() {
            bbox.extend(line.iter());
        }
        bbox
    }

    fn data(&self) -> &Self::Data {
        &self.data
    }
}

impl<F, D> Bounded<F> for &Linestrings<F, D>
where
    F: Float,
{
    fn bounded_by(self, bbox: BBox<F>) -> bool {
        self.iter().any(|lines| lines.bounded_by(bbox))
    }
}

impl<F, D> Linestrings<F, D>
where
    F: Float,
{
    /// Create new line string geometry
    pub fn new(data: D) -> Self {
        let lines = Vec::new();
        Self { lines, data }
    }

    /// Push a line string
    pub fn push<I, P>(&mut self, pts: I)
    where
        I: IntoIterator<Item = P>,
        P: Into<Pt<F>>,
    {
        self.lines.push(Linestring::new(pts));
    }

    /// Get line string iterator
    pub fn iter(&self) -> impl Iterator<Item = &Linestring<F>> {
        self.lines.iter()
    }
}

/// Border around bounding box
///
/// The border is eight regions around the box, including the 4 cardinal and 4
/// ordinal directions.
#[derive(Clone, Copy, Debug, Default)]
struct BoundBorder {
    below: bool,
    below_left: bool,
    left: bool,
    above_left: bool,
    above: bool,
    above_right: bool,
    right: bool,
    below_right: bool,
}

impl BoundBorder {
    /// Add bounds to border
    fn add_bounds(&mut self, b: Bounds) -> bool {
        match b {
            Bounds::Below => self.below = true,
            Bounds::BelowLeft => self.below_left = true,
            Bounds::Left => self.left = true,
            Bounds::AboveLeft => self.above_left = true,
            Bounds::Above => self.above = true,
            Bounds::AboveRight => self.above_right = true,
            Bounds::Right => self.right = true,
            Bounds::BelowRight => self.below_right = true,
            Bounds::Within => return true,
        }
        false
    }

    /// Check if border is surrounding bounds
    ///
    /// If there are no gaps of 3 or more cardinal/ordinal directions, the shape
    /// is surrounding the box.  This can trigger false positives, but is much
    /// simpler than the "correct" algorithm.
    fn is_surrounding(&self) -> bool {
        if !(self.below | self.below_left | self.left) {
            return false;
        }
        if !(self.below_left | self.left | self.above_left) {
            return false;
        }
        if !(self.left | self.above_left | self.above) {
            return false;
        }
        if !(self.above_left | self.above | self.above_right) {
            return false;
        }
        if !(self.above | self.above_right | self.right) {
            return false;
        }
        if !(self.above_right | self.right | self.below_right) {
            return false;
        }
        if !(self.right | self.below_right | self.below) {
            return false;
        }
        if !(self.below_right | self.below | self.below_left) {
            return false;
        }
        true
    }
}

impl<F> Bounded<F> for &Polygon<F>
where
    F: Float,
{
    fn bounded_by(self, bbox: BBox<F>) -> bool {
        let mut border = BoundBorder::default();
        self.segments().any(|seg| {
            seg.bounded_by(bbox)
                || border.add_bounds(bbox.check(seg.p0.x, seg.p0.y))
        }) || border.is_surrounding()
    }
}

impl<F> Polygon<F>
where
    F: Float,
{
    /// Create a new polygon
    fn new<I, P>(pts: I) -> Self
    where
        I: IntoIterator<Item = P>,
        P: Into<Pt<F>>,
    {
        let pts = pts.into_iter().map(|pt| pt.into()).collect();
        Polygon { pts }
    }

    /// Check if a polygon has clockwise winding order
    fn is_clockwise(&self) -> bool {
        if let Some(ext) = self.find_extreme_point() {
            let len = self.pts.len();
            let a = if ext > 0 { ext - 1 } else { len - 1 };
            let b = if ext < len - 1 { ext + 1 } else { 0 };
            // Make two vectors as edges pointing toward the extreme point
            let v0 = self.pts[a] - self.pts[ext];
            let v1 = self.pts[b] - self.pts[ext];
            // Cross product determines the winding order
            (v0 * v1) > F::zero()
        } else {
            false
        }
    }

    /// Find an extreme point on the convex hull of a polygon
    fn find_extreme_point(&self) -> Option<usize> {
        self.pts
            .iter()
            .enumerate()
            .min_by(|a, b| {
                (a.1.x, a.1.y)
                    .partial_cmp(&(b.1.x, b.1.y))
                    .unwrap_or(Ordering::Greater)
            })
            .map(|e| e.0)
    }

    /// Get point iterator
    pub fn iter(&self) -> impl Iterator<Item = &Pt<F>> {
        self.pts.iter()
    }

    /// Get line segment iterator
    pub fn segments(&self) -> impl Iterator<Item = Seg<F>> + '_ {
        let iter = self.pts.iter();
        SegIter { iter, ppt: None }
    }
}

impl<F, D> Gis<F> for Polygons<F, D>
where
    F: Float,
{
    type Data = D;

    fn bbox(&self) -> BBox<F> {
        let mut bbox = BBox::default();
        for ring in &self.rings {
            bbox.extend(ring.iter());
        }
        bbox
    }

    fn data(&self) -> &Self::Data {
        &self.data
    }
}

impl<F, D> Bounded<F> for &Polygons<F, D>
where
    F: Float,
{
    fn bounded_by(self, bbox: BBox<F>) -> bool {
        self.iter().any(|poly| poly.bounded_by(bbox))
    }
}

impl<F, D> Polygons<F, D>
where
    F: Float,
{
    /// Create new polygon geometry
    pub fn new(data: D) -> Self {
        let rings = Vec::new();
        Self { rings, data }
    }

    /// Push an outer polygon
    pub fn push_outer<I, P>(&mut self, ring: I)
    where
        I: IntoIterator<Item = P>,
        P: Into<Pt<F>>,
    {
        let mut ring = Polygon::new(ring);
        if !ring.is_clockwise() {
            ring.pts.reverse();
        }
        self.rings.push(ring);
    }

    /// Push an inner polygon
    pub fn push_inner<I, P>(&mut self, ring: I)
    where
        I: IntoIterator<Item = P>,
        P: Into<Pt<F>>,
    {
        let mut ring = Polygon::new(ring);
        if ring.is_clockwise() {
            ring.pts.reverse();
        }
        self.rings.push(ring);
    }

    /// Get polygon iterator
    pub fn iter(&self) -> impl Iterator<Item = &Polygon<F>> {
        self.rings.iter()
    }
}

impl<F, D> Gis<F> for Geom<F, D>
where
    F: Float,
{
    type Data = D;

    fn bbox(&self) -> BBox<F> {
        match self {
            Geom::Point(p) => p.bbox(),
            Geom::Linestring(ls) => ls.bbox(),
            Geom::Polygon(pg) => pg.bbox(),
        }
    }

    fn data(&self) -> &Self::Data {
        match self {
            Geom::Point(p) => p.data(),
            Geom::Linestring(ls) => ls.data(),
            Geom::Polygon(pg) => pg.data(),
        }
    }
}

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

    #[test]
    fn clockwise() {
        let ring = Polygon::new([(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)]);
        assert_eq!(false, ring.is_clockwise());
        let ring = Polygon::new([(0.0, 0.0), (0.0, 1.0), (1.0, 0.0)]);
        assert_eq!(true, ring.is_clockwise());
    }
}