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`).
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 /// How many meters a pixel spans at `latitude` on the meridian through
86 /// the camera's center, as [`meters_per_pixel_at`](Self::meters_per_pixel_at)
87 /// measures them.
88 #[must_use]
89 pub fn meters_per_pixel_at_latitude(&self, latitude: f64) -> f64 {
90 let view = self.state.view();
91 let longitude = view.center(WrapMode::Unwrapped).longitude();
92 view.meters_per_pixel_at_lng_lat([longitude, latitude])
93 }
94
95 /// How many meters a pixel spans at `lat_lng`, at the camera's zoom,
96 /// whatever its pitch, as [`View::meters_per_pixel_at`] measures them: in
97 /// a registered projection, along the screen's x axis, as GL JS's
98 /// [geolocate control](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/ui/control/geolocate_control.ts#L585-L596)
99 /// measures it.
100 #[must_use]
101 pub fn meters_per_pixel_at(&self, lat_lng: &LatLng) -> f64 {
102 self.state.view().meters_per_pixel_at(lat_lng)
103 }
104
105 /// Whether the globe hides `lat_lng` from the camera; a Mercator view
106 /// hides nothing.
107 #[must_use]
108 pub fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
109 self.state.view().is_location_occluded(lat_lng)
110 }
111
112 /// The location under `pixel`: on the projection's ground, or on the
113 /// flat map ([`Map::lat_lng_for_pixel`]). Fails with
114 /// [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a NaN or
115 /// infinite pixel.
116 pub fn lat_lng_for_pixel(&self, pixel: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
117 lat_lng_for_pixel(self.state.view(), self.ground.as_deref(), pixel, wrap_mode)
118 }
119
120 /// Moves the camera as a map's [`jump_to`](Map::jump_to) would, without
121 /// its constraints. On the projection's ground, as on the map's, a move
122 /// around an anchor holds the ground under it, and the eye stays above
123 /// the ground; the center keeps the altitude it is given. The ground
124 /// stays: where the camera now sees ground it doesn't hold, it converts
125 /// as where the line of sight meets none.
126 pub fn set_camera(&mut self, camera: &CameraOptions) {
127 let mut transform = self.transform();
128 let terrain = self.ground.clone().map(|ground| TerrainGround { elevation: Some(ground), clamped: false });
129 transform.set_terrain(terrain);
130 transform.jump_to(camera);
131 self.state = transform.state().clone();
132 self.fit_planes();
133 }
134
135 /// The camera, with its center in the copy of the world that it is in.
136 #[must_use]
137 pub fn camera(&self) -> Camera {
138 self.state.view().camera()
139 }
140
141 /// A transform over a copy of the state, to move its camera as a map
142 /// would.
143 fn transform(&self) -> Transform {
144 Transform::from_state(self.state.clone())
145 }
146}
147
148/// The screen point (y down) of `lat_lng` in `view`, in the copy of the world
149/// nearest its center: standing on `ground`, the ground a renderer drew of a
150/// terrain ([`View::lat_lng_to_screen_coordinate_on`]), or at sea level
151/// without one.
152pub(crate) fn pixel_for_lat_lng(view: &View, ground: Option<&dyn Elevation>, lat_lng: &LatLng) -> ScreenCoordinate {
153 let lat_lng = view.lat_lng_near_center(lat_lng);
154 let point = match ground {
155 Some(ground) => view.lat_lng_to_screen_coordinate_on(&lat_lng, ground),
156 None => view.lat_lng_to_screen_coordinate(&lat_lng),
157 };
158 flip_y(view, &point)
159}
160
161/// The location under `pixel` (y down) in `view`: on `ground`
162/// ([`View::screen_coordinate_to_lat_lng_on`]), or at sea level without one.
163/// Fails as [`View::screen_coordinate_to_lat_lng`].
164pub(crate) fn lat_lng_for_pixel(
165 view: &View,
166 ground: Option<&dyn Elevation>,
167 pixel: &ScreenCoordinate,
168 wrap_mode: WrapMode,
169) -> Result<LatLng, Error> {
170 let point = flip_y(view, pixel);
171 match ground {
172 Some(ground) => view.screen_coordinate_to_lat_lng_on(&point, ground, wrap_mode),
173 None => view.screen_coordinate_to_lat_lng(&point, wrap_mode),
174 }
175}