mln_engine/camera/
tile_coordinate.rs1use 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#[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 let clamp = |v: f64| -> i16 {
49 let v = v as i64;
51 v.clamp(i64::from(i16::MIN), i64::from(i16::MAX)) as i16
52 };
53 Point::new(
54 clamp(
55 (zoomed.p.x - f64::from(tile_id.canonical.x) - f64::from(tile_id.wrap) * scale)
56 * f64::from(constants::EXTENT),
57 ),
58 clamp((zoomed.p.y - f64::from(tile_id.canonical.y)) * f64::from(constants::EXTENT)),
59 )
60 }
61}