s2json_core/geometry/
bbox.rs

1use crate::*;
2use alloc::fmt;
3use core::{
4    cmp::Ordering,
5    ops::{Mul, MulAssign, Sub},
6};
7use serde::{
8    Deserialize, Deserializer, Serialize, Serializer,
9    de::{self, SeqAccess, Visitor},
10    ser::SerializeTuple,
11};
12
13trait Bounded {
14    fn min_value() -> Self;
15    fn max_value() -> Self;
16}
17macro_rules! impl_bounded {
18    ($($t:ty),*) => {
19        $(
20            impl Bounded for $t {
21                fn min_value() -> Self {
22                    <$t>::MIN
23                }
24                fn max_value() -> Self {
25                    <$t>::MAX
26                }
27            }
28        )*
29    };
30}
31
32// Implement for common numeric types
33impl_bounded!(i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, isize, usize, f32, f64);
34
35/// A BBOX is defined in lon-lat space and helps with zooming motion to
36/// see the entire line or polygon
37/// The order is (left, bottom, right, top)
38/// If WM, then the projection is lon-lat
39/// If S2, then the projection is s-t
40#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
41pub struct BBox<T = f64> {
42    /// left most longitude (WM) or S (S2)
43    pub left: T,
44    /// bottom most latitude (WM) or T (S2)
45    pub bottom: T,
46    /// right most longitude (WM) or T (S2)
47    pub right: T,
48    /// top most latitude (WM) or S (S2)
49    pub top: T,
50}
51impl<T> From<BBox<T>> for MValue
52where
53    T: Into<ValueType>,
54{
55    fn from(bbox: BBox<T>) -> MValue {
56        MValue::from([
57            ("left".into(), bbox.left.into()),
58            ("bottom".into(), bbox.bottom.into()),
59            ("right".into(), bbox.right.into()),
60            ("top".into(), bbox.top.into()),
61        ])
62    }
63}
64impl<T> From<&BBox<T>> for MValue
65where
66    T: Copy + Into<ValueType>,
67{
68    fn from(bbox: &BBox<T>) -> MValue {
69        MValue::from([
70            ("left".into(), bbox.left.into()),
71            ("bottom".into(), bbox.bottom.into()),
72            ("right".into(), bbox.right.into()),
73            ("top".into(), bbox.top.into()),
74        ])
75    }
76}
77impl<T> From<MValue> for BBox<T>
78where
79    T: From<ValueType>,
80{
81    fn from(mvalue: MValue) -> Self {
82        BBox {
83            left: mvalue.get("left").unwrap().clone().into(),
84            bottom: mvalue.get("bottom").unwrap().clone().into(),
85            right: mvalue.get("right").unwrap().clone().into(),
86            top: mvalue.get("top").unwrap().clone().into(),
87        }
88    }
89}
90impl<T> From<&MValue> for BBox<T>
91where
92    T: From<ValueType>,
93{
94    fn from(mvalue: &MValue) -> Self {
95        BBox {
96            left: mvalue.get("left").unwrap().clone().into(),
97            bottom: mvalue.get("bottom").unwrap().clone().into(),
98            right: mvalue.get("right").unwrap().clone().into(),
99            top: mvalue.get("top").unwrap().clone().into(),
100        }
101    }
102}
103impl<T> MValueCompatible for BBox<T>
104where
105    ValueType: From<T>,
106    T: From<ValueType> + Default + Bounded + Copy,
107{
108}
109impl<T> Default for BBox<T>
110where
111    T: Default + Bounded + Copy,
112{
113    fn default() -> Self {
114        BBox::new(T::max_value(), T::max_value(), T::min_value(), T::min_value())
115    }
116}
117impl<T> BBox<T> {
118    /// Creates a new BBox
119    pub fn new(left: T, bottom: T, right: T, top: T) -> Self
120    where
121        T: Copy,
122    {
123        BBox { left, bottom, right, top }
124    }
125
126    /// Checks if a point is within the BBox
127    pub fn point_overlap<P: GetXY>(&self, point: &P) -> bool
128    where
129        T: Into<f64> + Copy, // Ensures that comparison operators work for type T
130    {
131        point.x() >= self.left.into()
132            && point.x() <= self.right.into()
133            && point.y() >= self.bottom.into()
134            && point.y() <= self.top.into()
135    }
136
137    /// Merges another bounding box with this one
138    pub fn merge(&self, other: &Self) -> Self
139    where
140        T: PartialOrd + Copy,
141    {
142        let mut new_bbox = *self;
143        new_bbox.left = if new_bbox.left < other.left { new_bbox.left } else { other.left };
144        new_bbox.bottom =
145            if new_bbox.bottom < other.bottom { new_bbox.bottom } else { other.bottom };
146        new_bbox.right = if new_bbox.right > other.right { new_bbox.right } else { other.right };
147        new_bbox.top = if new_bbox.top > other.top { new_bbox.top } else { other.top };
148
149        new_bbox
150    }
151
152    /// Merges in place another bounding box with this one
153    pub fn merge_in_place(&mut self, other: &Self)
154    where
155        T: PartialOrd + Copy,
156    {
157        self.left = if self.left < other.left { self.left } else { other.left };
158        self.bottom = if self.bottom < other.bottom { self.bottom } else { other.bottom };
159        self.right = if self.right > other.right { self.right } else { other.right };
160        self.top = if self.top > other.top { self.top } else { other.top };
161    }
162
163    /// Checks if another bounding box overlaps with this one and returns the overlap
164    pub fn overlap(&self, other: &BBox<T>) -> Option<BBox<T>>
165    where
166        T: PartialOrd + Copy,
167    {
168        if self.left > other.right
169            || self.right < other.left
170            || self.bottom > other.top
171            || self.top < other.bottom
172        {
173            None
174        } else {
175            let left = if self.left > other.left { self.left } else { other.left };
176            let bottom = if self.bottom > other.bottom { self.bottom } else { other.bottom };
177            let right = if self.right < other.right { self.right } else { other.right };
178            let top = if self.top < other.top { self.top } else { other.top };
179
180            Some(BBox { left, bottom, right, top })
181        }
182    }
183
184    /// Clips the bounding box along an axis
185    pub fn clip(&self, axis: Axis, k1: T, k2: T) -> BBox<T>
186    where
187        T: PartialOrd + Copy,
188    {
189        let mut new_bbox = *self;
190        if axis == Axis::X {
191            new_bbox.left = if new_bbox.left > k1 { new_bbox.left } else { k1 };
192            new_bbox.right = if new_bbox.right < k2 { new_bbox.right } else { k2 };
193        } else {
194            new_bbox.bottom = if new_bbox.bottom > k1 { new_bbox.bottom } else { k1 };
195            new_bbox.top = if new_bbox.top < k2 { new_bbox.top } else { k2 };
196        }
197
198        new_bbox
199    }
200
201    /// Checks if this bounding box is inside another
202    pub fn inside(&self, other: &BBox<T>) -> bool
203    where
204        T: PartialOrd + Copy,
205    {
206        self.left >= other.left
207            && self.right <= other.right
208            && self.bottom >= other.bottom
209            && self.top <= other.top
210    }
211
212    /// Returns the area of the bounding box
213    pub fn area(&self) -> T
214    where
215        T: Sub<Output = T> + Mul<Output = T> + Copy,
216    {
217        (self.right - self.left) * (self.top - self.bottom)
218    }
219}
220impl BBox<f64> {
221    /// Creates a new BBox from a point
222    pub fn from_point<P: GetXY>(point: &P) -> Self {
223        BBox::new(point.x(), point.y(), point.x(), point.y())
224    }
225
226    /// Creates a new BBox from a linestring
227    pub fn from_linestring<P: GetXY>(line: &[P]) -> Self {
228        let mut bbox = BBox::default();
229        for point in line {
230            bbox.extend_from_point(point);
231        }
232        bbox
233    }
234
235    /// Creates a new BBox from a multi-linestring
236    pub fn from_multi_linestring<P: GetXY>(lines: &[Vec<P>]) -> Self {
237        let mut bbox = BBox::default();
238        for line in lines {
239            for point in line {
240                bbox.extend_from_point(point);
241            }
242        }
243        bbox
244    }
245
246    /// Creates a new BBox from a polygon
247    pub fn from_polygon<P: GetXY>(polygon: &[Vec<P>]) -> Self {
248        Self::from_multi_linestring(polygon)
249    }
250
251    /// Creates a new BBox from a multi-polygon
252    pub fn from_multi_polygon<P: GetXY>(polygons: &[Vec<Vec<P>>]) -> Self {
253        let mut bbox = BBox::default();
254        for polygon in polygons {
255            for line in polygon {
256                for point in line {
257                    bbox.extend_from_point(point);
258                }
259            }
260        }
261        bbox
262    }
263
264    /// Extends the bounding box with a point
265    pub fn extend_from_point<P: GetXY>(&mut self, point: &P) {
266        self.merge_in_place(&BBox::from_point(point));
267    }
268
269    /// Creates a new BBox from zoom-uv coordinates
270    pub fn from_uv_zoom(u: f64, v: f64, zoom: u8) -> Self {
271        let division_factor = 2. / (1 << zoom) as f64;
272
273        BBox {
274            left: division_factor * u - 1.0,
275            bottom: division_factor * v - 1.0,
276            right: division_factor * (u + 1.0) - 1.0,
277            top: division_factor * (v + 1.0) - 1.0,
278        }
279    }
280
281    /// Creates a new BBox from zoom-st coordinates
282    pub fn from_st_zoom(s: f64, t: f64, zoom: u8) -> Self {
283        let division_factor = (2. / (1 << zoom) as f64) * 0.5;
284
285        BBox {
286            left: division_factor * s,
287            bottom: division_factor * t,
288            right: division_factor * (s + 1.),
289            top: division_factor * (t + 1.),
290        }
291    }
292}
293impl<T> Serialize for BBox<T>
294where
295    T: Serialize + Copy,
296{
297    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
298    where
299        S: Serializer,
300    {
301        let mut seq = serializer.serialize_tuple(4)?;
302        seq.serialize_element(&self.left)?;
303        seq.serialize_element(&self.bottom)?;
304        seq.serialize_element(&self.right)?;
305        seq.serialize_element(&self.top)?;
306        seq.end()
307    }
308}
309impl<T: Copy> From<BBox3D<T>> for BBox<T> {
310    fn from(bbox: BBox3D<T>) -> Self {
311        BBox::new(bbox.left, bbox.bottom, bbox.right, bbox.top)
312    }
313}
314impl<'de, T> Deserialize<'de> for BBox<T>
315where
316    T: Deserialize<'de> + Copy,
317{
318    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
319    where
320        D: Deserializer<'de>,
321    {
322        struct BBoxVisitor<T> {
323            marker: core::marker::PhantomData<T>,
324        }
325
326        impl<'de, T> Visitor<'de> for BBoxVisitor<T>
327        where
328            T: Deserialize<'de> + Copy,
329        {
330            type Value = BBox<T>;
331
332            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
333                formatter.write_str("a sequence of four numbers")
334            }
335
336            fn visit_seq<V>(self, mut seq: V) -> Result<BBox<T>, V::Error>
337            where
338                V: SeqAccess<'de>,
339            {
340                let left =
341                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(0, &self))?;
342                let bottom =
343                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(1, &self))?;
344                let right =
345                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(2, &self))?;
346                let top = seq.next_element()?.ok_or_else(|| de::Error::invalid_length(3, &self))?;
347                Ok(BBox { left, bottom, right, top })
348            }
349        }
350
351        deserializer.deserialize_tuple(4, BBoxVisitor { marker: core::marker::PhantomData })
352    }
353}
354
355/// A BBOX is defined in lon-lat space and helps with zooming motion to
356/// see the entire 3D line or polygon
357#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
358pub struct BBox3D<T = f64> {
359    /// left most longitude (WM) or S (S2)
360    pub left: T,
361    /// bottom most latitude (WM) or T (S2)
362    pub bottom: T,
363    /// right most longitude (WM) or T (S2)
364    pub right: T,
365    /// top most latitude (WM) or S (S2)
366    pub top: T,
367    /// near most height (WM) or T (S2)
368    /// generic height is relative to the surface of the earth in meters
369    pub near: T,
370    /// far most height (WM) or T (S2)
371    /// generic height is relative to the surface of the earth in meters
372    pub far: T,
373}
374impl<T> BBox3D<T> {
375    /// Creates a new BBox3D
376    pub fn new(left: T, bottom: T, right: T, top: T, near: T, far: T) -> Self
377    where
378        T: Copy,
379    {
380        BBox3D { left, bottom, right, top, near, far }
381    }
382
383    /// Checks if a point is within the BBox
384    pub fn point_overlap<P: GetXY + GetZ>(&self, point: &P) -> bool
385    where
386        T: Into<f64> + Copy, // Ensures that comparison operators work for type T
387    {
388        let z = point.z().unwrap_or_default();
389        point.x() >= self.left.into()
390            && point.x() <= self.right.into()
391            && point.y() >= self.bottom.into()
392            && point.y() <= self.top.into()
393            && z >= self.near.into()
394            && z <= self.far.into()
395    }
396
397    /// Merges another bounding box with this one
398    pub fn merge(&self, other: &BBox3D<T>) -> BBox3D<T>
399    where
400        T: PartialOrd + Copy,
401    {
402        let mut new_bbox = *self;
403        new_bbox.left = if new_bbox.left < other.left { new_bbox.left } else { other.left };
404        new_bbox.bottom =
405            if new_bbox.bottom < other.bottom { new_bbox.bottom } else { other.bottom };
406        new_bbox.right = if new_bbox.right > other.right { new_bbox.right } else { other.right };
407        new_bbox.top = if new_bbox.top > other.top { new_bbox.top } else { other.top };
408        new_bbox.near = if new_bbox.near < other.near { new_bbox.near } else { other.near };
409        new_bbox.far = if new_bbox.far > other.far { new_bbox.far } else { other.far };
410
411        new_bbox
412    }
413
414    /// Merges in place another bounding box with this one
415    pub fn merge_in_place(&mut self, other: &Self)
416    where
417        T: PartialOrd + Copy,
418    {
419        self.left = if self.left < other.left { self.left } else { other.left };
420        self.bottom = if self.bottom < other.bottom { self.bottom } else { other.bottom };
421        self.right = if self.right > other.right { self.right } else { other.right };
422        self.top = if self.top > other.top { self.top } else { other.top };
423        self.near = if self.near < other.near { self.near } else { other.near };
424        self.far = if self.far > other.far { self.far } else { other.far };
425    }
426
427    /// Checks if another bounding box overlaps with this one and returns the overlap
428    pub fn overlap(&self, other: &BBox3D<T>) -> Option<BBox3D<T>>
429    where
430        T: PartialOrd + Copy,
431    {
432        if self.left > other.right
433            || self.right < other.left
434            || self.bottom > other.top
435            || self.top < other.bottom
436            || self.near > other.far
437            || self.far < other.near
438        {
439            None
440        } else {
441            let left = if self.left > other.left { self.left } else { other.left };
442            let bottom = if self.bottom > other.bottom { self.bottom } else { other.bottom };
443            let right = if self.right < other.right { self.right } else { other.right };
444            let top = if self.top < other.top { self.top } else { other.top };
445
446            let near = if self.near > other.near { self.near } else { other.near };
447            let far = if self.far < other.far { self.far } else { other.far };
448
449            Some(BBox3D { left, bottom, right, top, near, far })
450        }
451    }
452
453    /// Clips the bounding box along an axis
454    pub fn clip(&self, axis: Axis, k1: T, k2: T) -> BBox3D<T>
455    where
456        T: PartialOrd + Copy,
457    {
458        let mut new_bbox = *self;
459        if axis == Axis::X {
460            new_bbox.left = if new_bbox.left > k1 { new_bbox.left } else { k1 };
461            new_bbox.right = if new_bbox.right < k2 { new_bbox.right } else { k2 };
462        } else {
463            new_bbox.bottom = if new_bbox.bottom > k1 { new_bbox.bottom } else { k1 };
464            new_bbox.top = if new_bbox.top < k2 { new_bbox.top } else { k2 };
465        }
466
467        new_bbox
468    }
469
470    /// Creates a new BBox3D from a BBox
471    pub fn from_bbox(bbox: &BBox<T>) -> Self
472    where
473        T: Copy + Default,
474    {
475        BBox3D::new(bbox.left, bbox.bottom, bbox.right, bbox.top, T::default(), T::default())
476    }
477
478    /// Checks if this bounding box is inside another
479    pub fn inside(&self, other: &BBox3D<T>) -> bool
480    where
481        T: PartialOrd + Copy,
482    {
483        self.left >= other.left
484            && self.right <= other.right
485            && self.bottom >= other.bottom
486            && self.top <= other.top
487            && self.near >= other.near
488            && self.far <= other.far
489    }
490
491    /// Returns the area of the bounding box
492    pub fn area(&self) -> T
493    where
494        T: Sub<Output = T> + Mul<Output = T> + MulAssign + Into<f64> + Copy,
495    {
496        let mut res = (self.right - self.left) * (self.top - self.bottom);
497        if self.far.into() != 0. || self.near.into() != 0. {
498            res *= self.far - self.near
499        }
500
501        res
502    }
503}
504impl<T> Serialize for BBox3D<T>
505where
506    T: Serialize + Copy,
507{
508    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
509    where
510        S: Serializer,
511    {
512        let mut seq = serializer.serialize_tuple(6)?;
513        seq.serialize_element(&self.left)?;
514        seq.serialize_element(&self.bottom)?;
515        seq.serialize_element(&self.right)?;
516        seq.serialize_element(&self.top)?;
517        seq.serialize_element(&self.near)?;
518        seq.serialize_element(&self.far)?;
519        seq.end()
520    }
521}
522impl<T> Default for BBox3D<T>
523where
524    T: Default + Bounded + Copy,
525{
526    fn default() -> Self {
527        BBox3D::new(
528            T::max_value(),
529            T::max_value(),
530            T::min_value(),
531            T::min_value(),
532            T::max_value(),
533            T::min_value(),
534        )
535    }
536}
537impl BBox3D<f64> {
538    /// Creates a new BBox3D from a point
539    pub fn from_point<P: GetXY + GetZ>(point: &P) -> Self {
540        BBox3D::new(
541            point.x(),
542            point.y(),
543            point.x(),
544            point.y(),
545            point.z().unwrap_or(f64::MAX),
546            point.z().unwrap_or(f64::MIN),
547        )
548    }
549
550    /// Creates a new BBox from a linestring
551    pub fn from_linestring<P: GetXY + GetZ>(line: &[P]) -> Self {
552        let mut bbox = BBox3D::default();
553        for point in line {
554            bbox.extend_from_point(point);
555        }
556        bbox
557    }
558
559    /// Creates a new BBox from a multi-linestring
560    pub fn from_multi_linestring<P: GetXY + GetZ>(lines: &[Vec<P>]) -> Self {
561        let mut bbox = BBox3D::default();
562        for line in lines {
563            for point in line {
564                bbox.extend_from_point(point);
565            }
566        }
567        bbox
568    }
569
570    /// Creates a new BBox from a polygon
571    pub fn from_polygon<P: GetXY + GetZ>(polygon: &[Vec<P>]) -> Self {
572        Self::from_multi_linestring(polygon)
573    }
574
575    /// Creates a new BBox from a multi-polygon
576    pub fn from_multi_polygon<P: GetXY + GetZ>(polygons: &[Vec<Vec<P>>]) -> Self {
577        let mut bbox = BBox3D::default();
578        for polygon in polygons {
579            for line in polygon {
580                for point in line {
581                    bbox.extend_from_point(point);
582                }
583            }
584        }
585        bbox
586    }
587
588    /// Extends the bounding box with a point
589    pub fn extend_from_point<P: GetXY + GetZ>(&mut self, point: &P) {
590        self.merge_in_place(&BBox3D::from_point(point));
591    }
592
593    /// Creates a new BBox3D from zoom-uv coordinates
594    pub fn from_uv_zoom(u: f64, v: f64, zoom: u8) -> Self {
595        let division_factor = 2. / (1 << zoom) as f64;
596
597        BBox3D {
598            left: division_factor * u - 1.0,
599            bottom: division_factor * v - 1.0,
600            right: division_factor * (u + 1.0) - 1.0,
601            top: division_factor * (v + 1.0) - 1.0,
602            near: f64::MAX,
603            far: f64::MIN,
604        }
605    }
606
607    /// Creates a new BBox from zoom-st coordinates
608    pub fn from_st_zoom(s: f64, t: f64, zoom: u8) -> Self {
609        let division_factor = (2. / (1 << zoom) as f64) * 0.5;
610
611        BBox3D {
612            left: division_factor * s,
613            bottom: division_factor * t,
614            right: division_factor * (s + 1.),
615            top: division_factor * (t + 1.),
616            near: f64::MAX,
617            far: f64::MIN,
618        }
619    }
620}
621impl<T: Default + Copy> From<BBox<T>> for BBox3D<T> {
622    fn from(bbox: BBox<T>) -> Self {
623        BBox3D::from_bbox(&bbox)
624    }
625}
626impl<'de, T> Deserialize<'de> for BBox3D<T>
627where
628    T: Deserialize<'de> + Copy,
629{
630    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
631    where
632        D: Deserializer<'de>,
633    {
634        struct BBox3DVisitor<T> {
635            marker: core::marker::PhantomData<T>,
636        }
637
638        impl<'de, T> Visitor<'de> for BBox3DVisitor<T>
639        where
640            T: Deserialize<'de> + Copy,
641        {
642            type Value = BBox3D<T>;
643
644            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
645                formatter.write_str("a sequence of six numbers")
646            }
647
648            fn visit_seq<V>(self, mut seq: V) -> Result<BBox3D<T>, V::Error>
649            where
650                V: SeqAccess<'de>,
651            {
652                let left =
653                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(0, &self))?;
654                let bottom =
655                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(1, &self))?;
656                let right =
657                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(2, &self))?;
658                let top = seq.next_element()?.ok_or_else(|| de::Error::invalid_length(3, &self))?;
659                let near =
660                    seq.next_element()?.ok_or_else(|| de::Error::invalid_length(4, &self))?;
661                let far = seq.next_element()?.ok_or_else(|| de::Error::invalid_length(5, &self))?;
662                Ok(BBox3D { left, bottom, right, top, near, far })
663            }
664        }
665
666        deserializer.deserialize_tuple(6, BBox3DVisitor { marker: core::marker::PhantomData })
667    }
668}
669
670/// BBox or BBox3D
671#[derive(Serialize, Deserialize, Copy, Clone, Debug, PartialEq)]
672pub enum BBOX {
673    /// 2D bounding box
674    BBox(BBox),
675    /// 3D bounding box
676    BBox3D(BBox3D),
677}
678impl Default for BBOX {
679    fn default() -> Self {
680        BBOX::BBox(BBox::default())
681    }
682}
683impl Eq for BBOX {}
684impl PartialOrd for BBOX {
685    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
686        Some(self.cmp(other))
687    }
688}
689impl Ord for BBOX {
690    fn cmp(&self, other: &Self) -> Ordering {
691        match (self, other) {
692            (BBOX::BBox(a), BBOX::BBox(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
693            (BBOX::BBox3D(a), BBOX::BBox3D(b)) => a.partial_cmp(b).unwrap_or(Ordering::Equal),
694            // Ensure that BBox and BBox3D are ordered correctly
695            (BBOX::BBox(_), BBOX::BBox3D(_)) => Ordering::Less,
696            (BBOX::BBox3D(_), BBOX::BBox(_)) => Ordering::Greater,
697        }
698    }
699}