Skip to main content

mln_engine/tile/
tile_range.rs

1use mln_style::constants;
2use mln_style::crs::WorldBox;
3use mln_style::geo::{LatLng, LatLngBounds};
4use mln_style::geometry::Point;
5use mln_style::math::{clamp_f64, wrap};
6use mln_style::range::Range;
7use mln_style::tile_id::CanonicalTileID;
8
9use crate::geo::projection::Projection;
10
11#[derive(Clone, Copy, Debug, PartialEq)]
12pub struct TileRange {
13    pub(crate) range: Range<Point<u32>>,
14    pub(crate) zoom_range: Range<u8>,
15}
16
17impl TileRange {
18    /// Compute the range of tiles covered by the bounds at `max_zoom`.
19    #[must_use]
20    pub(crate) fn from_lat_lng_bounds_range(bounds: &LatLngBounds, mut min_zoom: u8, mut max_zoom: u8) -> TileRange {
21        if min_zoom > max_zoom {
22            std::mem::swap(&mut min_zoom, &mut max_zoom);
23        }
24
25        // Wrap the west edge into the world and keep the bounds' width, so
26        // unwrapped longitudes name the same columns as wrapped ones. `%` (fmod)
27        // is exact, so it goes first, before any rounding: a huge longitude
28        // still lands on its own meridian. The width of bounds with huge
29        // longitudes can overflow to infinity, which covers the world. An
30        // inverted interval counts as its west edge.
31        let west = wrap(bounds.west() % constants::DEGREES_MAX, -constants::LONGITUDE_MAX, constants::LONGITUDE_MAX);
32        let width = f64::max(bounds.east() - bounds.west(), 0.0);
33        let covers_world = width.is_nan() || width >= constants::DEGREES_MAX;
34        let max_tile = 2.0f64.powf(f64::from(max_zoom));
35        // `LatLng::new` fails only for a NaN or infinite edge, which these
36        // finite, in-range edges can't be.
37        let (Ok(sw), Ok(ne)) = (
38            LatLng::new(bounds.south(), west),
39            LatLng::new(bounds.north(), if covers_world { west } else { west + width }),
40        ) else {
41            debug_assert!(false, "LatLng from LatLngBounds coordinates");
42            let max = (max_tile - 1.0) as u32;
43            return TileRange {
44                range: Range::new(Point::new(0, 0), Point::new(max, max)),
45                zoom_range: Range::new(min_zoom, max_zoom),
46            };
47        };
48        let sw_proj = Projection::project_zoom(&sw, i32::from(max_zoom));
49        let ne_proj = Projection::project_zoom(&ne, i32::from(max_zoom));
50
51        // An east edge at 180° ends in the last column. Uncapped, it would
52        // name the column past the last, which wraps to column 0. A west edge
53        // just under 180° can round to 180° when projected, so it's capped
54        // too.
55        let west_column = sw_proj.x.floor().min(max_tile - 1.0);
56        let east_column = if west + width <= constants::LONGITUDE_MAX {
57            ne_proj.x.floor().min(max_tile - 1.0)
58        } else {
59            ne_proj.x.floor()
60        };
61        let mut min_x = 0u32;
62        let mut max_x = (max_tile - 1.0) as u32;
63        // Bounds that reach every column cover the world. Otherwise, bounds
64        // that cross the antimeridian end east of the last column, and wrap.
65        if !covers_world && east_column - west_column + 1.0 < max_tile {
66            min_x = west_column as u32;
67            max_x = (if east_column < max_tile { east_column } else { east_column - max_tile }) as u32;
68        }
69        let min_y = clamp_f64(ne_proj.y.floor(), 0.0, max_tile) as u32;
70        let max_y = clamp_f64(sw_proj.y.floor(), 0.0, max_tile) as u32;
71
72        TileRange {
73            range: Range::new(Point::new(min_x, min_y), Point::new(max_x, max_y)),
74            zoom_range: Range::new(min_zoom, max_zoom),
75        }
76    }
77
78    /// Compute the range of tiles covered by the bounds.
79    #[must_use]
80    pub fn from_lat_lng_bounds(bounds: &LatLngBounds, z: u8) -> TileRange {
81        Self::from_lat_lng_bounds_range(bounds, z, z)
82    }
83
84    /// The tiles from `min_zoom` to `max_zoom` that a rectangle in the world
85    /// square covers part of: a tile that the rectangle only touches at its
86    /// edge doesn't count. A rectangle as thin as a line covers the tiles it
87    /// lies in, east and south of a tile edge it lies on, and one outside the
88    /// square covers none.
89    #[must_use]
90    pub fn from_world_box(world_box: &WorldBox, mut min_zoom: u8, mut max_zoom: u8) -> TileRange {
91        if min_zoom > max_zoom {
92            std::mem::swap(&mut min_zoom, &mut max_zoom);
93        }
94        let WorldBox { min, max } = *world_box;
95        if !(max.x > 0.0 && max.y > 0.0 && min.x < 1.0 && min.y < 1.0) {
96            // A zoom range that no tile is in.
97            return TileRange { range: Range::new(Point::new(0, 0), Point::new(0, 0)), zoom_range: Range::new(1, 0) };
98        }
99        let max_tile = 2.0f64.powf(f64::from(max_zoom));
100        let first = |world: f64| clamp_f64((world * max_tile).floor(), 0.0, max_tile - 1.0);
101        // The last tile before the edge, and never one before the first,
102        // which `contains` would take for a range across the antimeridian.
103        let last = |world: f64, first: f64| clamp_f64((world * max_tile).ceil() - 1.0, first, max_tile - 1.0);
104        let (min_x, min_y) = (first(min.x), first(min.y));
105        TileRange {
106            range: Range::new(
107                Point::new(min_x as u32, min_y as u32),
108                Point::new(last(max.x, min_x) as u32, last(max.y, min_y) as u32),
109            ),
110            zoom_range: Range::new(min_zoom, max_zoom),
111        }
112    }
113
114    #[must_use]
115    pub fn contains(&self, tile_id: &CanonicalTileID) -> bool {
116        if tile_id.z <= self.zoom_range.max && tile_id.z >= self.zoom_range.min {
117            if tile_id.z == 0 {
118                return true;
119            }
120            let dz = self.zoom_range.max - tile_id.z;
121            let x0 = self.range.min.x.wrapping_shr(u32::from(dz));
122            let x1 = self.range.max.x.wrapping_shr(u32::from(dz));
123            let y0 = self.range.min.y.wrapping_shr(u32::from(dz));
124            let y1 = self.range.max.y.wrapping_shr(u32::from(dz));
125            return (if self.range.min.x > self.range.max.x {
126                // For wrapped bounds
127                tile_id.x >= x0 || tile_id.x <= x1
128            } else {
129                tile_id.x <= x1 && tile_id.x >= x0
130            }) && tile_id.y <= y1
131                && tile_id.y >= y0;
132        }
133        false
134    }
135}
136
137#[cfg(test)]
138#[path = "tile_range_test.rs"]
139mod tests;