Skip to main content

mln_engine/camera/
map_projection.rs

1// gtests-core: added for test/map/map.test.cpp (LatLngForPixelUnwrapped,
2// PixelForLatLngAfterZoomAroundAPointAcrossTheAntimeridian).
3
4use std::sync::Arc;
5
6use mln_style::error::Error;
7use mln_style::geo::{LatLng, WrapMode};
8
9use crate::camera::transform::{TerrainGround, Transform, flip_y, lowest_ground};
10use crate::camera::{Camera, CameraOptions, Elevation, MapView, TransformState, View};
11use crate::geo::ScreenCoordinate;
12use crate::map::map::Map;
13
14/// Converts coordinates for one camera and size, without a map: on the
15/// ground a renderer drew of a terrain ([`with_ground`](Self::with_ground)),
16/// or else on the flat map. It holds only a transform state and the ground,
17/// so it can move to another thread.
18pub struct MapProjection {
19    state: TransformState,
20    ground: Option<Arc<dyn Elevation>>,
21}
22
23const _: () = {
24    const fn sendable<T: Send>() {}
25    sendable::<MapProjection>();
26};
27
28impl MapProjection {
29    /// A projection for the map's camera, on the ground it draws
30    /// ([`Map::ground`]), as the map converts.
31    #[must_use]
32    pub fn new(map: &Map) -> Self {
33        Self::from_state(map.transform_state().clone()).with_ground(map.ground())
34    }
35
36    pub(crate) fn from_state(state: TransformState) -> Self {
37        MapProjection { state, ground: None }
38    }
39
40    /// A projection for one view of a map, from a [`MapSnapshot`] or a
41    /// rendered frame, on the flat map. `Err`: as [`MapView::to_state`].
42    ///
43    /// [`MapSnapshot`]: crate::map::MapSnapshot
44    pub fn from_view(view: &MapView) -> Result<Self, Error> {
45        Ok(Self::from_state(view.to_state()?))
46    }
47
48    /// The projection on `ground`, the ground a renderer drew of a terrain
49    /// ([`Map::ground`]), or on the flat map for `None`. The view's near and
50    /// far planes fit that ground as the map's do, which the line of sight
51    /// to the ground lies between.
52    #[must_use]
53    pub fn with_ground(mut self, ground: Option<Arc<dyn Elevation>>) -> Self {
54        self.ground = ground;
55        self.fit_planes();
56        self
57    }
58
59    /// Fits the view's near and far planes to the ground under the center,
60    /// or to the flat map without ground.
61    fn fit_planes(&mut self) {
62        let lowest = self.ground.as_deref().map(|ground| lowest_ground(self.state.view(), ground));
63        if lowest != self.state.view().terrain_min_elevation() {
64            self.state.set_terrain_min_elevation(lowest);
65        }
66    }
67
68    /// The screen point of `lat_lng`, in the copy of the world nearest the
69    /// camera's center: standing on the projection's ground, or at sea
70    /// level on the flat map ([`Map::pixel_for_lat_lng`]).
71    #[must_use]
72    pub fn pixel_for_lat_lng(&self, lat_lng: &LatLng) -> ScreenCoordinate {
73        pixel_for_lat_lng(self.state.view(), self.ground.as_deref(), lat_lng)
74    }
75
76    /// The height the projection's ground was drawn at, at `lat_lng`, in
77    /// meters with the terrain's exaggeration
78    /// ([`View::drawn_height_at`](crate::camera::View::drawn_height_at)).
79    /// `None` on the flat map, and where no ground was drawn.
80    #[must_use]
81    pub fn elevation(&self, lat_lng: &LatLng) -> Option<f64> {
82        self.state.view().drawn_height_at(lat_lng, &**self.ground.as_ref()?)
83    }
84
85    /// Whether the globe hides `lat_lng` from the camera; a Mercator view
86    /// hides nothing.
87    #[must_use]
88    pub fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
89        self.state.view().is_location_occluded(lat_lng)
90    }
91
92    /// The location under `pixel`: on the projection's ground, or on the
93    /// flat map ([`Map::lat_lng_for_pixel`]). Fails with
94    /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a NaN or
95    /// infinite pixel.
96    pub fn lat_lng_for_pixel(&self, pixel: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
97        lat_lng_for_pixel(self.state.view(), self.ground.as_deref(), pixel, wrap_mode)
98    }
99
100    /// Moves the camera as a map's [`jump_to`](Map::jump_to) would, without
101    /// its constraints. On the projection's ground, as on the map's, a move
102    /// around an anchor holds the ground under it, and the eye stays above
103    /// the ground; the center keeps the altitude it is given. The ground
104    /// stays: where the camera now sees ground it doesn't hold, it converts
105    /// as where the line of sight meets none.
106    pub fn set_camera(&mut self, camera: &CameraOptions) {
107        let mut transform = self.transform();
108        let terrain = self.ground.clone().map(|ground| TerrainGround { elevation: Some(ground), clamped: false });
109        transform.set_terrain(terrain);
110        transform.jump_to(camera);
111        self.state = transform.state().clone();
112        self.fit_planes();
113    }
114
115    /// The camera, with its center in the copy of the world that it is in.
116    #[must_use]
117    pub fn camera(&self) -> Camera {
118        self.state.view().camera()
119    }
120
121    /// A transform over a copy of the state, to move its camera as a map
122    /// would.
123    fn transform(&self) -> Transform {
124        Transform::from_state(self.state.clone())
125    }
126}
127
128/// The screen point (y down) of `lat_lng` in `view`, in the copy of the world
129/// nearest its center: standing on `ground`, the ground a renderer drew of a
130/// terrain ([`View::lat_lng_to_screen_coordinate_on`]), or at sea level
131/// without one.
132pub(crate) fn pixel_for_lat_lng(view: &View, ground: Option<&dyn Elevation>, lat_lng: &LatLng) -> ScreenCoordinate {
133    let lat_lng = view.lat_lng_near_center(lat_lng);
134    let point = match ground {
135        Some(ground) => view.lat_lng_to_screen_coordinate_on(&lat_lng, ground),
136        None => view.lat_lng_to_screen_coordinate(&lat_lng),
137    };
138    flip_y(view, &point)
139}
140
141/// The location under `pixel` (y down) in `view`: on `ground`
142/// ([`View::screen_coordinate_to_lat_lng_on`]), or at sea level without one.
143/// Fails as [`View::screen_coordinate_to_lat_lng`].
144pub(crate) fn lat_lng_for_pixel(
145    view: &View,
146    ground: Option<&dyn Elevation>,
147    pixel: &ScreenCoordinate,
148    wrap_mode: WrapMode,
149) -> Result<LatLng, Error> {
150    let point = flip_y(view, pixel);
151    match ground {
152        Some(ground) => view.screen_coordinate_to_lat_lng_on(&point, ground, wrap_mode),
153        None => view.screen_coordinate_to_lat_lng(&point, wrap_mode),
154    }
155}