Skip to main content

mln_engine/camera/
tile_coordinate.rs

1use mln_style::constants;
2use mln_style::geo::LatLng;
3use mln_style::geometry::Point;
4
5use crate::camera::view::View;
6use crate::geo::ScreenCoordinate;
7use crate::geo::projection::Projection;
8use crate::tile::UnwrappedTileID;
9
10pub(crate) type TileCoordinatePoint = Point<f64>;
11
12/// Has floating point x/y coordinates. Used for computing the tiles that
13/// need to be visible in the viewport.
14#[derive(Clone, Copy, Debug, PartialEq)]
15pub struct TileCoordinate {
16    pub p: TileCoordinatePoint,
17    pub(crate) z: f64,
18}
19
20impl TileCoordinate {
21    #[must_use]
22    pub fn from_lat_lng(zoom: f64, lat_lng: &LatLng) -> TileCoordinate {
23        let scale = 2.0f64.powf(zoom);
24        let p = Projection::project(lat_lng, scale);
25        TileCoordinate { p: Point::new(p.x / constants::TILE_SIZE, p.y / constants::TILE_SIZE), z: zoom }
26    }
27
28    #[must_use]
29    pub(crate) fn from_screen_coordinate(
30        view: &View,
31        zoom: u8,
32        screen_coordinate: &ScreenCoordinate,
33    ) -> TileCoordinate {
34        view.screen_coordinate_to_tile_coordinate(screen_coordinate, zoom)
35    }
36
37    #[must_use]
38    pub(crate) fn zoom_to(&self, zoom: f64) -> TileCoordinate {
39        let scale_diff = 2.0f64.powf(zoom - self.z);
40        TileCoordinate { p: Point::new(self.p.x * scale_diff, self.p.y * scale_diff), z: zoom }
41    }
42
43    #[must_use]
44    pub fn to_geometry_coordinate(tile_id: &UnwrappedTileID, point: &TileCoordinatePoint) -> Point<i16> {
45        let scale = 2.0f64.powf(f64::from(tile_id.canonical.z));
46        let zoomed = TileCoordinate { p: *point, z: 0.0 }.zoom_to(f64::from(tile_id.canonical.z));
47        // Truncates toward zero and saturates to the `i16` range.
48        let clamp = |v: f64| v as i16;
49        Point::new(
50            clamp(
51                (zoomed.p.x - f64::from(tile_id.canonical.x) - f64::from(tile_id.wrap) * scale)
52                    * f64::from(constants::EXTENT),
53            ),
54            clamp((zoomed.p.y - f64::from(tile_id.canonical.y)) * f64::from(constants::EXTENT)),
55        )
56    }
57}
58
59#[cfg(test)]
60#[path = "tile_coordinate_test.rs"]
61mod tests;