Skip to main content

map_tile_toolkit/
tile.rs

1//! Tile addressing on the integer grid.
2//!
3//! A tile of side `extent` owns the integer square `[x·extent, x·extent + extent - 1]` on each axis, so
4//! every vertex has exactly one owner. What a tile keeps is wider: its closed clip box
5//! `[x·extent - buffer, x·extent + extent + buffer]` shares the vertices on its edges with its neighbors.
6
7use geo_types::Coord;
8
9/// A tile address on the integer grid. Coordinates may be negative.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
11pub struct TileId {
12    pub x: i32,
13    pub y: i32,
14}
15
16impl TileId {
17    #[must_use]
18    pub fn new(x: i32, y: i32) -> Self {
19        Self { x, y }
20    }
21
22    /// This tile's origin in global coordinates - `self · extent`, the global position its local
23    /// `[0, 0]` corner maps to. **Add** it to a tile-local coordinate to lift it into the global
24    /// frame, or **subtract** it to drop a global coordinate into this tile's local frame.
25    ///
26    /// Returns `None` if `self · extent` overflows `i32` (a tile far outside the representable range
27    /// for this `extent`).
28    ///
29    /// ```
30    /// # use map_tile_toolkit::TileId;
31    /// # use geo_types::Coord;
32    /// let origin = TileId::new(2, 3).origin(25).expect("in range");
33    /// assert_eq!(origin, Coord { x: 50, y: 75 });
34    /// assert_eq!(Coord { x: 4, y: 1 } + origin, Coord { x: 54, y: 76 }); // local -> global
35    /// assert_eq!(Coord { x: 54, y: 76 } - origin, Coord { x: 4, y: 1 }); // global -> local
36    /// ```
37    #[must_use]
38    pub fn origin(self, extent: u32) -> Option<Coord<i32>> {
39        let e = i64::from(extent);
40        Some(Coord {
41            x: i32::try_from(i64::from(self.x) * e).ok()?,
42            y: i32::try_from(i64::from(self.y) * e).ok()?,
43        })
44    }
45}
46
47impl From<(i32, i32)> for TileId {
48    fn from((x, y): (i32, i32)) -> Self {
49        Self { x, y }
50    }
51}
52
53/// The tile that owns coordinate `c` for the given tile side `extent`.
54pub(crate) fn tile_of(c: Coord<i32>, extent: i32) -> TileId {
55    TileId::new(c.x.div_euclid(extent), c.y.div_euclid(extent))
56}