Skip to main content

mln_engine/camera/
tile_coordinate.rs

1use geometry::Point;
2use mln_style::constants;
3use mln_style::geo::LatLng;
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. In mapbox-gl-js, this is named
14/// `MercatorCoordinate`.
15#[derive(Clone, Copy, Debug, PartialEq)]
16pub struct TileCoordinate {
17    pub p: TileCoordinatePoint,
18    pub(crate) z: f64,
19}
20
21impl TileCoordinate {
22    #[must_use]
23    pub fn from_lat_lng(zoom: f64, lat_lng: &LatLng) -> TileCoordinate {
24        let scale = 2.0f64.powf(zoom);
25        let p = Projection::project(lat_lng, scale);
26        TileCoordinate { p: Point::new(p.x / constants::TILE_SIZE, p.y / constants::TILE_SIZE), z: zoom }
27    }
28
29    #[must_use]
30    pub(crate) fn from_screen_coordinate(
31        view: &View,
32        zoom: u8,
33        screen_coordinate: &ScreenCoordinate,
34    ) -> TileCoordinate {
35        view.screen_coordinate_to_tile_coordinate(screen_coordinate, zoom)
36    }
37
38    #[must_use]
39    pub(crate) fn zoom_to(&self, zoom: f64) -> TileCoordinate {
40        let scale_diff = 2.0f64.powf(zoom - self.z);
41        TileCoordinate { p: Point::new(self.p.x * scale_diff, self.p.y * scale_diff), z: zoom }
42    }
43
44    #[must_use]
45    pub fn to_geometry_coordinate(tile_id: &UnwrappedTileID, point: &TileCoordinatePoint) -> Point<i16> {
46        let scale = 2.0f64.powf(f64::from(tile_id.canonical.z));
47        let zoomed = TileCoordinate { p: *point, z: 0.0 }.zoom_to(f64::from(tile_id.canonical.z));
48        // Truncates toward zero and saturates to the `i16` range.
49        let clamp = |v: f64| v as i16;
50        Point::new(
51            clamp(
52                (zoomed.p.x - f64::from(tile_id.canonical.x) - f64::from(tile_id.wrap) * scale)
53                    * f64::from(constants::EXTENT),
54            ),
55            clamp((zoomed.p.y - f64::from(tile_id.canonical.y)) * f64::from(constants::EXTENT)),
56        )
57    }
58}